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?
save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on. When you create an instance of a Mongoose model using new, calling save() makes Mongoose insert a new document.
Mongoose | save() FunctionThe save() function is used to save the document to the database. Using this function, new documents can be added to the database. Installation of mongoose module: You can visit the link to Install mongoose module.
To save the data into the database, we need to create a new instance of our model that we created early. We will pass into this instance the user's input. Once we have it then we just need to enter the command "save". Mongoose will return a promise on a save to the database.
In SQL, you would use the LIKE operator. In Mongoose, you can simply query by a regular expression as shown below. const docs = await Character. find({ rank: /Commander/ }); // ['Deanna Troi', 'William Riker'] docs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With