6

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){});
user2498079
  • 2,872
  • 8
  • 32
  • 60

1 Answers1

4

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.

str
  • 42,689
  • 17
  • 109
  • 127
  • If I set `new` to be true, will it return NON NULL value in the callback for the document that were added THE FIRST TIME? There can be a scenario where mongoose couldn't insert the document in the collection without causing an error. In that case `err` will not be set – user2498079 Dec 23 '16 at 14:52
  • 1
    Yes, when using `upsert:true` it will return the new document after insertion. "There can be a scenario where mongoose couldn't insert the document in the collection without causing an error." I don't think so. What scenario would that be? – str Dec 23 '16 at 14:56
  • 2
    it's not returning the new document after insertion. I am already using upsert=true – user2498079 Dec 23 '16 at 14:58
  • 1
    @user2498079 did you ever figure this out? this is clearly not a duplicate of the linked question – CQM Apr 06 '18 at 20:05
  • 1
    @CQM I agree with you, you can vote for `Reopen` below the question ^^ – TOPKAT Jun 30 '21 at 18:04