B M
B M

Reputation: 4019

mongoose callback results if _id not found

I was looking for documentation on what arguments mongoose callbacks get if an operation fails due to an object _id not being found. I cannot find any. Thus I compared three cases myself. Called with id = 'foofoofoofoo' the following happens:

// returns: err = null, obj = null
mySchema.statics.findById = function(id, cb) {
  this.findOne({ _id: new ObjectId(id) }, cb);
}

// returns: err = null, obj is a cursor with obj.result = { n: 0, ok: 1 }
mySchema.statics.deleteById = function(id, cb) {
  this.remove({ _id: new ObjectId(id) }, cb);
}

// returns: err = null, obj is an Object with obj = { n: 0, nModified: 0, ok: 1 }
mySchema.statics.updateById = function(id, updObj, cb) {
  this.where({ _id: new ObjectId(id) }).update(updObj, cb);
}

This imho is a horrible result. I get three completely different types as 2nd argument in the cb: a null, a cursor and a simple object. Not even the cursor.result equals the "simple object" in structure.

My questions are:

  1. Am I using some anti pattern / mixed syntax here that leads to such inconsistent results?
  2. Where can I find details about what results the mongoose callbacks get called with in different situations?

Upvotes: 0

Views: 355

Answers (1)

JavaNoScript
JavaNoScript

Reputation: 2413

The second parameter result in the callback function would be different which depends on the operation. See more details here:

Anywhere a callback is passed to a query in Mongoose, the callback follows the pattern callback(error, results). What results is depends on the operation:

  • For findOne() it is a potentially-null single document.
  • find() a list of documents
  • count() the number of documents
  • update() the number of documents affected, etc.

The API docs for Models provide more detail on what is passed to the callbacks.

Hope this help.

Upvotes: 1

Related Questions