【问题标题】:save() callback not being invoked on a mongoose schema object未在猫鼬模式对象上调用 save() 回调
【发布时间】:2017-04-04 10:52:00
【问题描述】:

我试图在我的数据库中保存一个 json 对象。 save() 函数没有被调用,但是 json 对象永远不会被保存。 帮我找出问题所在。 我想这是与猫鼬的连接问题。 这是我的代码..

    var config = require('../config');
    var user = require('../user');
api.post('/addUser',function(req,res) {
    var userID;
    //creating a sample user under Model collection User.. so this becomes a document!!
    console.log("addition of new user api hit!!");
    //sending a query to retrieve the no of users served
    MongoClient.connect(dbURL, function (err, db) {
        var UserCountCursor = db.collection("ourusers").find({"docName": "userCount"}).limit(1);

        UserCountCursor.each(function (err, doc) {
            if (err)
                console.log("did not get the count");
            else
            // var countString= JSON.stringify(doc);
            //var docJson=JSON.parse(countString);
                console.log("the json content is:" + doc.iparkoUserCount);

            //increase the user count by 1 in the db.
            var incCount = parseInt(doc.iparkoUserCount) + 1;
            console.log("no of userrs:" + incCount);
            // making an userId
            userID = "ipkoID_C" + incCount.toString();
            //updating using MOngoClient
            db.collection("ourusers").update({"docName": "userCount"}, {$set: {"iparkoUserCount": incCount}});
            console.log("the user count in the db has been updated!!");
            console.log("generated id for this guy is:" + userID);

            if (userID != null) {
                console.log("calling the save function");
                //closing the mongoclient connection
                db.close();
                signUpUser(userID);
            }
        });
    });


    function signUpUser(userIDD) {
        var me = new user({
            name: req.body.new_name,
            password: req.body.new_pswd,
            username: req.body.new_username,
            phno: req.body.new_phn,
            userId: userIDD
        });

        console.log("the obj ::" + JSON.stringify(me));
        console.log("obj created and ready to be stored");
//connecting to the db using mongoose
        mongoose.connect(config.database, function (err) {
            if (err)
                console.log("The error is :"+err);
            else {
                console.log("WE ARE CONNECTED USING MONGOOSE");
                //saving the sample user document
                me.save(function (err) {
                    console.log("in the save func");
                    if (err) throw err;
                    else {
                        console.log('User saved Successfully!!!!!');
                        res.json({
                            'whatStatus': 'user saved in the database!!',
                            'userID': userIDD
                        });
                        mongoose.connection.close();
                    }
                });
            }
        });
    }
});

我的控制台日志::

新增用户 api 命中!! json内容为:143 用户数:144 数据库中的用户数已更新!! 为这家伙生成的 id 是:ipkoID_C144 调用保存函数 obj ::{"name":"Abhi","password":"jio","username":"abhijio","phno":"45142545","userId":"ipkoID_C144","_id":" 583295bfa0f9f8342035d3b9"} obj 创建并准备存储 C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\lib\utils.js:98 process.nextTick(function() { throw err; }); ^

TypeError:无法读取 null 的属性“iparkoUserCount” 在 C:\Users\shivendra\WebstormProjects\iParko\routes\RegisteredParkingLots.js:76:57 在 handleCallback (C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\lib\utils.js:96:12) 在 C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\lib\cursor.js:742:16 在 handleCallback (C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\lib\utils.js:96:12) 在 C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\lib\cursor.js:676:5 在 handleCallback (C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\node_modules\mongodb-core\lib\cursor.js:156:5) 在 setCursorDeadAndNotified (C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\node_modules\mongodb-core\lib\cursor.js:496:3) 在 nextFunction (C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\node_modules\mongodb-core\lib\cursor.js:588:12) 在 Cursor.next [as _next] (C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\node_modules\mongodb-core\lib\cursor.js:681:3) 在 nextObject (C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\lib\cursor.js:673:8) 在 Cursor.next (C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\lib\cursor.js:262:12) 在 _each (C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\lib\cursor.js:738:10) 在 C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\lib\cursor.js:746:7 在 handleCallback (C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\lib\utils.js:96:12) 在 C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\lib\cursor.js:676:5 在 handleCallback (C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\node_modules\mongodb-core\lib\cursor.js:156:5)

进程以退出代码 1 结束

【问题讨论】:

    标签: javascript node.js express mongoose mongoose-schema


    【解决方案1】:

    您似乎打开了两次数据库连接,一次使用mongoose.connect,另一次使用mongoose.connection.open()。这就是你得到错误的原因。

    尝试只使用一个连接,如下所示。

    mongoose.connect(config.database, function(err, db) {
                //var dbcon=mongoose.connection.open();
    
                //dbcon.on('error',function(){console.log('connction error:')});
                //dbcon.once('open',function(){
       if(err) {
          console.log(err);
       } else {
                    console.log("WE ARE CONNECTED USING MONGOOSE");
                    //saving the sample user document
                    me.save(function (err) {
                        console.log("in the save func");
                        if (err) throw err;
                        else {
                            console.log('User saved Successfully!!!!!');
                            res.json({
                                'whatStatus': 'user saved in the database!!',
                                'userID': userIDD
                            });
                            //mongoose.connection.close();
                        }
                    });
              }
        });
    

    【讨论】:

    • Aruna 我试过了,但我仍然没有进入 save() 函数。我已经更新了问题中的代码以及控制台日志..可能想看看..-感谢您的帮助
    • 错误是Cannot read property 'iparkoUserCount' of null。你能检查一下这个错误吗?
    • 实际上 iparkoUserCount 变量是一个文档键。现在在 doc.each(...) 函数中,我可以记录变量内容。但是该文档只有一个 json 对象。因此,当 each() 第一次运行时,它不会给出该错误,但是当读取文档中的唯一对象并且文档现在为空时(因为它只有一个 json obj)。现在,当 each() 函数运行时,它找不到要读取的任何其他 json 对象,因此会抛出该错误。这就是为什么我使用了 signUpUser(userIDD) 函数,一旦创建了用户 ID,它就会被调用。并且控件正在进入signUpUser()
    • 我想知道您在哪里创建user 架构,因为mongoose.connect 应该在schema 创建之前调用一次。一旦你这样做了,mongoose.connectme.save 的时候就不需要了。
    • 哦.. 我在另一个名为 user.js 的 JS 文件中创建我的架构,然后我将该文件导入到当前的 JS 文件 :: var user= require('../user') ;
    【解决方案2】:

    在您的UserCountCursor.each(...) 循环中,在检查err 之后,您还应该检查doc。所以你有这个:

    UserCountCursor.each(function (err, doc) {
       if (err)
         console.log("did not get the count");
       else 
    
         // var countString= JSON.stringify(doc);
    
         //...
    
    })
    

    改为这样做:

    UserCountCursor.each(function (err, doc) {
       if (err){
         console.log("did not get the count");
       }else if(doc){ 
    
         // var countString= JSON.stringify(doc);
    
         //...
    
       }
    
    })
    

    然后您将避免 Cannot read property 'iparkoUserCount' of null 错误并进入您的 save() 函数。

    【讨论】:

    • 感谢斯蒂芬!这真的很有效.. 这很容易.. 感谢所有的帮助。
    猜你喜欢
    • 1970-01-01
    • 2018-01-15
    • 2016-12-27
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 2021-04-10
    • 2016-01-23
    相关资源
    最近更新 更多