Bear Bear - 2 months ago 8
Node.js Question

nodejs - both IF and ELSE execute

There has to be a standard way of checking for existence of a document and then inserting if it doesn't exist. This is something we all do, since the dawn of time. But the examples out there only show, like, half a routine. I don't get it. So I came up with the following code. And for some reason, both

if
and
else
execute. The function isn't getting called twice, so... why is it happening?

The output is:

Connected correctly to server
got doc
inserted doc
Disconnected from server successfully


The code is:

// 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');
});
}
});
});

Answer

Having the if (doc != null) you can identify the end of the loop. Thes mean that even if you limit the results to 1, the first iteration will give you back the document that you queried and in the second iteration the cursor will be null and indicating that this should be the end of the loop/results.

The logs are like that:

Connected correctly to server
got doc
inserted doc
Disconnected from server successfully

because you are executing an asynchronous operation in the else statement.

Cursor is not aware about your limit in the query.