必須有一個檢查文檔存在的標準方法,然後插入(如果不存在)。這是我們大家都做的事情,從時間的黎明開始。但是那裏的例子只顯示了一半的例程。我不明白。所以我想出了以下代碼。由於某種原因,執行if
和else
。該函數沒有被調用兩次,所以...爲什麼會發生?nodejs - IF和ELSE都執行
輸出是:
Connected correctly to server
got doc
inserted doc
Disconnected from server successfully
的代碼是:
// Use connect method to connect to the Server
mongoClient.connect(url, function (err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
var cursor = db.collection('mycoll').find(mydoc).limit(1);
// i need 'each' in order to test if doc exists.
// will execute once because i said limit 1.
cursor.each(function (err, doc) {
if (doc != null) {
console.log("got doc");
}
else {
mydoc.date_submit = new Date();
db.collection('mycoll').insertOne(mydoc, function (err, r) {
assert.equal(1, r.insertedCount);
console.log("inserted doc");
db.close();
console.log('Disconnected from server successfully');
});
}
});
});
也許你應該記錄光標的大小 –
光標上有一個限制,所以我可以理解它爲什麼不被選中,但是 - 是的 - 記錄光標的大小! – akaphenom
你正在尋找* upsert *操作...?如果找到,則更新文檔,否則插入新文檔。 – deceze