I am using mongoose.findOneAndUpdate() method for inserting and updating a document in the collection. However if there is nothing to update in the table and a new document is created, the findOneAndUpdate() callback returns null.
How would I know if the insert part of the findOneAndUpdate() was successfull?
TimeTable.getTimeTableModelObject().findOneAndUpdate({ageGroup:'2'}, timeTable, {upsert:true}, function(err, foundData){});
findOneAndUpdate () in Mongoose. Mongoose's findOneAndUpdate () function finds the first document that matches a given filter, applies an update, and returns the document. Unlike updateOne (), findOneAndUpdate () returns the updated document.
As the name implies, findOneAndUpdate () finds the first document that matches a given filter, applies an update, and returns the document. By default, findOneAndUpdate () returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied.
Mongoose transforms the result of findOneAndUpdate () by default: it returns the updated document. That makes it difficult to check whether a document was upserted or not.
Because Mongoose by default creates a new MongoDB ObjectId ( this hidden _id field) every time you pass it a Javascript Object to update the field of a document. To go around you can tell Mongoose to not create a new ObjectId, by making sure your mongoose schema is as followed:
See the documentation: http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate
Available options
new: bool - if true, return the modified document rather than the original. defaults to false
[...]
Also, you can just check for err
in your callback function.
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