必须有一个检查文档存在的标准方法,然后插入(如果不存在)。这是我们大家都做的事情,从时间的黎明开始。但是那里的例子只显示了一半的例程。我不明白。所以我想出了以下代码。由于某种原因,执行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