你必須提供一個回調的寫入功能,你已經writeConcern 1(其默認)創建與數據庫的連接時。您的代碼應該是這樣的:
db.createCollection("category",function(errDb,collection){
collection.findOne({name:"test"},function(err,value){
if(value == null)
{
collection.insert({name:"test"}, function(err, docs){
if (err) //do anything you want to do when there is an error
// Here you write code for what you would do when the documents were sucessfully inserted into the collection
});
}
})
})
但是,如果你不想寫的關注也被激活而只是想利用你做了那麼當你創建連接,你必須連接功能的嵌入式喜歡這個。
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/integration_test_?", {
db: {
w : o
}
}, function(err, db) {
test.equal(null, err);
test.ok(db != null);
// Do anything like you were doing here
}
這裏我設置writeConcern爲0。這可以防止mongo.db確認您瞭解插入或更新的成功。所以,現在你可以使用collection.insert({name:"test"});
只是一個值得關注的詞使用w:0時要小心,因爲你不希望將它用於你想要確保插入或更新的數據,因爲你可能會失去有些數據是由於寫入不成功造成的。
[通過Node.js將文檔插入MongoDB時出現錯誤](http://stackoverflow.com/questions/14407834/error-when-inserting-a-document-into-mongodb-via-node- js) – JohnnyHK
缺少回調函數。 。 –
重複顯示時,您需要提供回調函數。你的'insert'調用不使用回調。 – WiredPrairie