问题描述
我使用db.collection.insert方法在mongodb中使用function(err,records)回调添加了一个文档.尽管插入成功(我在mongolab上检查了记录),但记录为null,因此在记录[0]上出现错误._id
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
我正在测试的是nitroous.io上的node.js错误吗?
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();
});
推荐答案
您要在insert
调用完成之前关闭连接.将您的db.close();
调用移至回调内:
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();
});
}
});
请记住,您不应该经常打开和关闭MongoClient
连接池.通常最好在启动过程中将其打开,并保持打开状态,直到您的应用关闭.
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.
这篇关于获取错误node.js mongodb成功插入后无法读取记录的null属性0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!