Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  80] [ 7]  / answers: 1 / hits: 39787  / 9 Years ago, thu, october 8, 2015, 12:00:00

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?


More From » node.js

 Answers
26

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.


[#64798] Tuesday, October 6, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
muhammadbrandend

Total Points: 670
Total Questions: 95
Total Answers: 97

Location: Saint Vincent and the Grenadines
Member since Sat, Sep 11, 2021
3 Years ago
;