Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose.findOneAndUpdate returns null [duplicate]

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){});
like image 323
user2498079 Avatar asked Dec 23 '16 14:12

user2498079


People also ask

How do I use findoneandupdate in mongoose?

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.

How do I use findoneandupdate ()?

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.

How to check if a document has been upserted in mongoose?

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.

Why does mongoose create a new objectId every time I update it?

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:


1 Answers

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.

like image 134
str Avatar answered Oct 26 '22 16:10

str