gpt4 book ai didi

node.js - Write关注在node.js的mongodb native 驱动程序中插入文档

转载 作者:太空宇宙 更新时间:2023-11-04 01:07:26 25 4
gpt4 key购买 nike

我在使用 Node.js 的 mongodb native 驱动程序的写入问题时遇到问题。我在本地主机中使用单个 MongoDB 服务器。这是我正在使用的代码:

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 是关于等待写入关注返回的超时,而不是关于实际连接或插入。连接也是在 insert() 之前建立的。

默认情况下,node-mongodb-native 驱动程序会将操作排队,直到数据库再次返回。

如果您想禁用此缓冲区,请将 bufferMaxEntries 设置为 0
参见here了解更多信息。

请参阅此示例代码:

// 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) {

关于node.js - Write关注在node.js的mongodb native 驱动程序中插入文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21762389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com