在mongoose模式对象上没有调用save()回调

时间:2016-11-21 05:42:06

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

我试图在我的数据库中保存一个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   用户名:1​​44   数据库中的用户数已更新!!   为这个人生成的id是:ipkoID_C144   调用保存功能   obj :: {"名称":" Abhi","密码":" jio","用户名": " abhijio"" PHNO":" 45142545""用户id":" ipkoID_C144"" _id& #34;:" 583295bfa0f9f8342035d3b9"}   obj已创建并准备存储   C:\ Users \用户shivendra \ WebstormProjects \ iParko \ node_modules \ mongodb的\ lib中\ utils.js:98       process.nextTick(function(){throw err;});                                     ^

TypeError:无法读取属性' iparkoUserCount'为null     在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     at handleCallback(C:\ Users \ shivendra \ WebstormProjects \ iParko \ node_modules \ mongodb \ node_modules \ mongodb-core \ lib \ cursor.js:156:5)     at setCursorDeadAndNotified(C:\ Users \ shivendra \ WebstormProjects \ iParko \ node_modules \ mongodb \ node_modules \ mongodb-core \ lib \ cursor.js:496:3)     at 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)     at 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)     at _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     at handleCallback(C:\ Users \ shivendra \ WebstormProjects \ iParko \ node_modules \ mongodb \ node_modules \ mongodb-core \ lib \ cursor.js:156:5)

使用退出代码1完成处理

2 个答案:

答案 0 :(得分:0)

您似乎正在使用system ("grep -E 'Type|group|slack \\\(' $a "); 打开数据库连接两次,使用mongoose.connect打开另一个数据库连接。这就是你收到错误的原因。

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

mongoose.connection.open()

答案 1 :(得分:0)

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()功能。