在node.js的mongodb本机驱动程序中插入文档
我在使用Node.js的mongodb本机驱动程序时遇到问题。我在localhost中使用单个MongoDB服务器。这是我正在使用的代码:在node.js的mongodb本机驱动程序中插入文档,node.js,mongodb,Node.js,Mongodb,我在使用Node.js的mongodb本机驱动程序时遇到问题。我在localhost中使用单个MongoDB服务器。这是我正在使用的代码: function insertNewDoc(newdoc, cbsuccess, cberror){ db.collection('test').insert(newdoc, {w: 1, wtimeout: 2000}, function(err){ if (err) cberror(err); else cbsuccess(newdoc); });
function insertNewDoc(newdoc, cbsuccess, cberror){
db.collection('test').insert(newdoc, {w: 1, wtimeout: 2000}, function(err){
if (err) cberror(err);
else cbsuccess(newdoc);
});
}
在执行此函数之前,我尝试停止mongodb,但它一直在尝试,直到mongo再次打开,然后插入文档。我想要的是设置一个超时,以便在2秒后文档未成功插入时,返回一个错误。
wtimeout
是等待写入问题返回的超时,而不是实际的连接或插入。在插入()之前也会建立连接
默认情况下,节点mongodb本机驱动程序将对操作进行排队,直到数据库再次返回
如果要禁用此缓冲区,请将bufferMaxEntries
设置为0
。
有关更多信息,请参阅 请参见以下示例代码:
// node-mongodb-native_test-connection.js file
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
if(err) {
return console.dir(err);
}
console.log(new Date() + ' - We are connected');
// db.close();
db.on('close', function () {
console.log(new Date() + ' - Error...close');
});
var collection = db.collection('test');
setTimeout(function() {
console.log(new Date() + ' - trying to insert');
collection.insert({'newdoc': 1}, {w: 1, wtimeout: 2000}, function(err, item){
if(err) { return console.dir(err); }
console.log(item);
});
}, 2000);
});
输出示例:
$ node node-mongodb-native_test-connection.js
Wed Mar 12 2014 17:31:54 GMT+0000 (GMT) - We are connected
Wed Mar 12 2014 17:31:55 GMT+0000 (GMT) - Error...close
Wed Mar 12 2014 17:31:56 GMT+0000 (GMT) - trying to insert
[ { newdoc: 1, _id: 53209a0c939f0500006f6c33 } ]
看看日志
Wed Mar 12 17:31:55.719 [signalProcessingThread] got signal 2 (Interrupt: 2), will terminate after current cmd ends
Wed Mar 12 17:31:55.719 [signalProcessingThread] now exiting
...
Wed Mar 12 17:31:59.215 [initandlisten] MongoDB starting : pid=67863 port=27017 dbpath=/data/db/ 64-bit host=localhost
...
Wed Mar 12 17:31:59.237 [initandlisten] waiting for connections on port 27017
Wed Mar 12 17:31:59.730 [initandlisten] connection accepted from 127.0.0.1:56730 #1 (1 connection now open)
更改连接选项,如下所示:
MongoClient.connect('mongodb://localhost:27017/test', {
db: {bufferMaxEntries:0},
},
function(err, db) {
值得一提的是,我也看到过这种行为,但没能弄明白。