How does Mongoose's save callback work?

Melissa picture Melissa · Oct 8, 2015 · Viewed 32.7k times · Source

For the MEAN stack, I'm learning about Mongoose's save() function, which takes a callback. Its API states:

Model#save([options], [fn])

Saves this document.

Parameters:

[options] <Object> options set `options.safe` to override [schema's safe option](http://mongoosejs.com//docs/guide.html#safe)
[fn] <Function> optional callback

How do I know what arguments are in the optional callback? The API merely gives an example:

product.sold = Date.now();
product.save(function (err, product, numAffected) {
  if (err) ..
})
The callback will receive three parameters

err if an error occurred
product which is the saved product
numAffected will be 1 when the document was successfully persisted to MongoDB, otherwise 0.

What I think the API should say about the optional callback is the following:

[fn] <Function> optional callback with this structure:

     function(err, theDocumentToBeSaved, [isSaveSuccessful])

and it can be used like the following. Note that the second argument, the document, must be the same document that is calling the save. (Let me know if it's not the case.)

documentFoo.save(function(err, documentFoo, [isSaveSuccessful]){
    if(err){ return next(err); }

    if (isSaveSuccessful === 1){

        // documentFoo has been saved correctly 
        // do stuff with the saved documentFoo
    }
}

If my interpretation is correct, is that how the save callback parameters should always be structured?

Answer

Drown picture Drown · Oct 8, 2015

The save function's callback will accept three arguments :

  • The error
  • The document that was saved
  • The number of rows affected

The arguments are listed here

Note that the second argument, the document, must be the same document that is calling the save

You can name the arguments however you want, you're not casting it to an object or anything like that. It's simply a name that you want to use to refer it to in your function's body.