Get error node.js mongodb cannot read property 0 of null for records after successfull insert

故事扮演 提交于 2020-01-03 02:42:12

问题


I used db.collection.insert method to add a document in mongodb with function(err,records) callback. Though insertion succeeds (I checked on mongolab the record), records is null so that It throws error at records[0]._id

Is it a node.js bug on nitrous.io which I'm testing ?

MongoClient.connect(uri, function (err, db) {
    if (err) {
        throw err;
    } else {
        console.log("successfully connected to the database");

        // Insert document in MongoDb Collection
                var document = {title:'test',category:'node.js'}

                db.collection('tut').insert(document, function(err,records){
                        //if (err) throw err;
                        console.log('inserted record id: ' + records[0]._id);
                  });
    }
    db.close();
});

回答1:


You're closing the connection before the insert call completes. Move your db.close(); call inside the callback:

MongoClient.connect(uri, function (err, db) {
    if (err) {
        throw err;
    } else {
        console.log("successfully connected to the database");

        // Insert document in MongoDb Collection
        var document = {title:'test',category:'node.js'}

        db.collection('tut').insert(document, function(err,records){
            //if (err) throw err;
            console.log('inserted record id: ' + records[0]._id);
            db.close();
        });
    }
});

Keep in mind that you shouldn't be frequently opening and closing your MongoClient connection pool. It's generally best to open it during startup and leave it open until your app shuts down.



来源:https://stackoverflow.com/questions/24856892/get-error-node-js-mongodb-cannot-read-property-0-of-null-for-records-after-succe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!