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?
The save
function's callback will accept three arguments :
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.