Is there any situation when col.insert doesn't send any error but the document(s) is (are) not inserted?

Problem

I see often the following code snippet:

collection.insert({"some": "data"}, function (err, inserted) {
   if (err) { /* do something */ return; }
   if (!inserted || !inserted.length) {
       console.error("Nothing inserted ...");
       return;
   }
   /* do something */
});

Is the second if really required?

When the insert method doesn't send an err in callback and inserted variable is undefined, null or something like this?

Problem courtesy of: Ionică Bizău

Solution

The second argument passed to the callback of insert can be null (with err being null as well), according to the sources, when you're using MongoDB 2.6 (or higher), the write concern is 0 and there's a callback function passed.

I'm not running 2.6, so can't test this myself:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/demo?w=0', function(err, db) {
  db.collection('test').insert({ foo : 'bar' }, function(err, inserted) {
    console.log('I', inserted);
  });
});

However, inserted would not be an array in this situation, but plain null. So the check would have to be if (! inserted) { ... }, and it wouldn't be an error (setting the write concern to 0 means you're just not interested in knowing if the insert failed or not).

Solution courtesy of: robertklep

Discussion

We don't need second if for insert() callback. But we may need second if for update() callback.

I think the author of that code confused insert() with update() (?)

Insert document link

collection.insert({"some": "data"}, {safe: true}, function(err, records){
  if (err) throw err;
  console.log(records);
});

Side note: According to document, we must pass {safe: true} to get the err param in callback, because it is default to false. But I feel like it is true by default for me (including production mode)

Update document link

collection.update({"some": "data"}, function (err, count) {
    if(err) throw err;

    // SECOND IF        
    if(!count) {
        console.log('NOTHING UPDATED');
    }
});
Discussion courtesy of: damphat

This recipe can be found in it's original form on Stack Over Flow.