【发布时间】:2019-06-23 13:07:45
【问题描述】:
当我单击重置密码按钮时,它会抛出用户未在后端的命令提示符中定义。我将 Mongoose 与 Node.js Express 一起使用。这是模型和控制器的代码。
控制器
const User = require('../models/userModels');
const passwordResetToken = require('../models/resettokenModels');
async ResetPassword(req, res) {
if (!req.body.email) {
return res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: 'Email is required' });
}
const userEmail = await User.findOne({
email: Helpers.lowerCase(req.body.email)
});
if (!userEmail) {
return res
.status(HttpStatus.CONFLICT)
.json({ message: 'Email does not exist' });
}
var resettoken = new passwordResetToken({ _userId: user._id, resettoken: crypto.randomBytes(16).toString('hex') });
resettoken.save(function (err) {
if (err) { return res.status(500).send({ msg: err.message }); }
var transporter = nodemailer.createTransport({
service: '"SendGrid"',
auth:
{
user: 'email',
pass: 'password'
}
});
var mailOptions = {
from: 'email',
subject: 'Node.js Password Reset',
text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
'http://' + req.headers.host + '/reset/' + resettoken + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
}
transporter.sendMail(mailOptions
)
})
.catch(err => {
res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: 'Error occured' });
});
},
这是模型
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const resettokenSchema = new mongoose.Schema({
_userId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
resettoken: { type: String, required: true },
createdAt: { type: Date, required: true, default: Date.now, expires: 43200 },
});
module.exports = mongoose.model('passwordResetToken', resettokenSchema);
用户模型
const userSchema = new mongoose.Schema({
username: { type: String },
email: { type: String },
password: { type: String },
...
...
控制器内的这一行显示错误
var resettoken = new passwordResetToken({ _userId: user._id, resettoken: crypto.randomBytes(16).toString('hex') });
什么会导致这样的问题?
【问题讨论】:
-
我没有看到
user对象,但我看到了userEmail对象... -
如果这里需要,我也可以导入用户模型。在项目中,它存在于控制器导入和模型中。
-
认为您错过了此处的提示,您需要将
user._id重命名为userEmail._id -
不是它抛出 can't read property of catch in this line: .catch(err => { res .status(HttpStatus.INTERNAL_SERVER_ERROR) .json({ message: 'Error occurred' });这是控制器的最后一块,
标签: node.js mongodb express mongoose mongoose-schema