Пользовательская модель
```
const crypto = require('crypto');
const mongoose = require('mongoose');
const validator = require('validator');
const bcrypt = require('bcryptjs');
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
unique: [true, 'Username already taken'],
required: [true, 'Please enter a usernam']
},
dob: String,
email: {
type: String,
required: [true, 'Please provide your email'],
unique: true,
lowercase: true,
validate: [validator.isEmail, 'Please provide with a mail']
},
profile_img: String, //url of the image |||Should think how we have store the image|||
password: {
type: String,
required: [true, 'Please provide with a password'],
minlength: 8,
select: false
},
passwordConfirm: {
type: String,
required: [true, 'Please confirm your password'],
validate: {
validator: function(el) {
return el === this.password;
},
message: "Password don't match"
}
},
passwordChangedAt: Date,
passwordResetToken: String,
passwordResetExpires: Date,
areaOfInterest: [], //array of String
friends: [
{
type: mongoose.Schema.ObjectId,
ref: 'User'
}
],
isBoarded: { type: Boolean, default: false },
createdAt: {
type: Date,
default: Date.now()
}
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true }
}
);
//virtual populate
UserSchema.virtual('posts', {
ref: 'Post',
foreignField: 'userId',
localField: '_id'
});
UserSchema.pre('save', async function(next) {
if (!this.isModified('password')) return next();
this.password = await bcrypt.hash(this.password, 12);
this.passwordConfirm = undefined;
next();
});
UserSchema.pre('save', function(next) {
if (!this.isModified('password') || this.isNew) return next();
this.passwordChangedAt = Date.now() - 1000;
next();
});
UserSchema.methods.correctPassword = async function(passwordToMatch, password) {
return await bcrypt.compare(passwordToMatch, password);
};
UserSchema.methods.changedPasswordAfter = function(JWTTimeStamp) {
if (this.passwordChangedAt) {
const changedTimeStamp = parseInt(
this.passwordChangedAt.getTime() / 1000,
10
);
return JWTTimeStamp < changedTimeStamp;
}
return false;
};
Здесь метод добавляется с использованием свойства методов перед экспортом модели
UserSchema.methods.createPasswordResetToken = function() {
const resetToken = crypto.randomBytes(32).toString('hex');
this.passwordResetToken = crypto
.createHash('sha256')
.update(resetToken)
.digest('hex');
// console.log({ resetToken }, this.passwordResetToken);
this.passwordResetExpires = Date.now() + 10 * 60 * 1000;
return resetToken;
};
const User = mongoose.model('User', UserSchema);
module.exports = User;
И метод вызывается в этой функции
const { promisify } = require('util');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const User = require('../models/userModel');
const catchAsync = require('../utils/catchAsync');
const AppError = require('../utils/appError');
const sendEmail = require('../utils/email');
exports.forgotPassword =async (req, res, next) => {
console.log(User.schema.methods);
const user = await User.findOne({ email: req.body.email });
console.log(user);
if (!user) {
return next(new AppError('No user with that email address', 404));
}
Вот где возникает ошибка, когда я вызвал метод с ошибкой «user.createPassswordResetToken не является функцией», «stack»: «TypeError: user.createPassswordResetToken не является функцией \ n в controllers / authController. js: 117: 27 \ n в processTicksAndRejections (internal / process / task_queues. js: 93: 5) "В вышеупомянутой ошибке это строка no, на которую она указывает
const resetToken = user.createPassswordResetToken();
await user.save({ validateBeforeSave: false });
const resetURL = `${req.protocol}://${req.get(
'host'
)}/api/v1/users/resetPassword/${resetToken}`;
const message = `Forgot your Password? Submit your new password and confirm your password at ${resetURL}.\n If you didn't forgot your password, please ignore this email.`;
The console log of User.schema.methods is
{
correctPassword: [AsyncFunction (anonymous)],
changedPasswordAfter: [Function (anonymous)],
createPasswordResetToken: [Function (anonymous)]
}