【问题标题】:Can not set property of null不能设置 null 的属性
【发布时间】:2018-01-13 18:24:05
【问题描述】:

我想写一条生成 otp 的路由。并首先检查用户是否存在。如果用户存在发送 otp。如果不是首先将用户保存在数据库中,然后生成 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);

【问题讨论】:

  • 请格式化您的代码以便于阅读。
  • 您也可以在问题中添加错误跟踪跟踪。没有人有这么多时间来调试代码。

标签: node.js mongodb


【解决方案1】:

你正在尝试在null 帐户上设置mobileNo,所以你得到了

TypeError: 无法将属性“mobileNo”设置为 null

应该是

if( account === null )
{ 
    account = {}; // or create new account
    account.mobileNo = req.body.mobileNo;
    account.OtpNo = a;
    //save this account
}

【讨论】:

    猜你喜欢
    • 2023-01-05
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多