2014-02-13 68 views
1

我遇到問題與使用mongodb本地驅動程序的Node.js的寫入問題。我在localhost中使用了一個MongoDB服務器。這是我使用的代碼:我已經嘗試了執行該功能之前停止MongoDB的寫關注插入文件在mongodb本地驅動程序爲node.js

function insertNewDoc(newdoc, cbsuccess, cberror){ 

db.collection('test').insert(newdoc, {w: 1, wtimeout: 2000}, function(err){ 
if (err) cberror(err); 
else cbsuccess(newdoc); 
}); 

} 

,但它不停地嘗試,直到蒙戈是一遍,然後把它插入文檔。我想要的是設置一個超時,以防文檔在2秒後未成功插入,這會返回錯誤。

+0

對於什麼是值得的,我已經看到了這種行爲,也無法弄清楚。 –

回答

0

wtimeout是關於等待寫入關注返回的超時,而不是關於實際連接或插入。在insert()之前還建立了連接。

默認情況下,node-mongodb-native驅動程序將對操作進行排隊,直到數據庫再次返回。

如果要禁用此緩衝區集bufferMaxEntries0
有關更多信息,請參閱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) { 
相關問題