我使用 db.collection.insert 方法通过 function(err,records) 回调在 mongodb 中添加文档。虽然插入成功(我在 mongolab 上检查了记录),但记录为空,因此它在记录[0]._id处抛出错误
这是我正在测试的 Nitrous.io 上的 Node.js 错误吗?
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();
在回调中调用:
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
连接池。通常最好在启动时打开它,并保持打开状态直到应用程序关闭。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)