我想写一个生成otp的路由。并首先检查用户是否存在。如果用户存在发送otp。如果不是先将用户保存在db中,然后生成otp。还想在db中设置生存otp数据的时间为360秒。 请告诉我我做错了什么。当运行以下代码时,它会给出无法设置null属性的错误。
TypeError:无法设置属性' mobileNo'为null
router.route('/generateOtp/:mobileNo').get(function (req, res) {
Account.findOne({ mobileNo: req.params.mobileNo }, function (err, account) {
//below is writeen to check if account exist with above mobile no
if(account===null)
{
account.mobileNo = req.body.mobileNo;
//below for a is random 4 digit code
account.OtpNo=a;
//here i am trying to saving the otp and mobile no in mongo db
newAccount.save(function (err) {
if (err) {
res.send(err);
}
console.log("Account added");
});
//console.log(account);
}
else
//if mobile no already exist than just gentating 4 digit code and saving to monodb
{
account.mobileNo = req.body.mobileNo;
account.OtpNo = a;
newAccount.save(function (err) {
if (err) {
res.send(err);
}
console.log("Account added");
});
}
});
});
我的架构如下: -
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var AccountSchema = new Schema({
mobileNo:{
type:String,
required:true,
unique:true
},
OtpNo:{
type:String,
required:true,
//unique:true
createdAt: 1,
expireAfterSeconds: 300
}
});
module.exports = mongoose.model('account', AccountSchema);
答案 0 :(得分:0)
您正试图在mobileNo
帐户上设置null
,因此您正在
TypeError:无法将属性'mobileNo'设置为null
应该是
if( account === null )
{
account = {}; // or create new account
account.mobileNo = req.body.mobileNo;
account.OtpNo = a;
//save this account
}