用户注册后,我会给他们发送一封电子邮件,其中包含一个包含令牌及其电子邮件地址的链接。当他们单击该链接时,我试图通过从url查询字符串中获取令牌对象和电子邮件值来验证令牌,然后在我的数据库中找到匹配的令牌。即使我将令牌变量存储在外部函数中,但我仍然不断获得令牌变量的空值(当我在内部函数中使用它时)。
//------------------------------------------------- TOKEN VERIIFICATION ------------------------------------------------
function verifyToken(req, res)
{
var email = req.query.email
var token = req.query.token
Token.findOne({ token: token },
function (err, token) {
console.log(token)
if (!token || token === undefined)
res.render('verify', { notif: 'We were unable to find a valid token. Your token may have expired.' });
// If we found a token, find a matching user
console.log("token was found")
User.findOne({ _id: token._userId, email: email }, function (err,) {
if (!user) res.render('verify', { notif: 'We were unable to find a user for this token.' });
if (user.isVerified) res.render('verify', { notif: 'This user has already been verified.' });
// Verify and save the user
user.isVerified = true;
user.save(function (err) {
if (err) { res.render('verify', { notif: err.message }); }
res.render('verify', { notif: 'The account has been verified. Please log in.' });
});
});
});
}
// ------------------------------------------------- END OF TOKEN VERIFICATION ---------------------------------------------
exports.registerUser = registerUser
我在我的server.js中这样调用此函数:
app.get('/verify', function (req, res) {
userController.verifyToken(req, res);
//res.render('verify', { title: "Email Verification" });
})
我成功获取了电子邮件和令牌值,然后将它们存储在变量中,但是当我尝试在Token.findOne的相应函数中访问它们时,它们为NULL。请帮助我
编辑 *
这是我的令牌的模式
const tokenSchema = new mongoose.Schema({
_userId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
token: { type: String, required: true },
createdAt: { type: Date, required: true, default: Date.now, expires: 43200 }
});
这是数据库中的样子:
{ "_id" : ObjectId("5f640985f6dcb40988328a57"), "_userId" : ObjectId("5f640985f6dcb40988328a56"), "token" : "487f7b22f68312d2c1bbc93b1aea445b", "createdAt" : ISODate("2020-09-18T01:12:37.339Z"), "__v" : 0 }
ALSO
现在,当我设置Token.findOne({token:token})时 我收到此错误:TypeError:无法读取null的属性“ _userId”
答案 0 :(得分:0)
我发现了问题所在。
令牌模型未注册为架构,因为我正在使用:
const tokenSchema = new mongoose.Schema
即使我已经通过使用来定义“模式”:
var Schema = mongoose.Schema
因此它是通过以下方式解决的:
const tokenSchema = new Schema