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

拟墨画扇 提交于 2019-12-06 16:30:01

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.

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