Home > Net >  Mongoose - Check if `upsert` made a new document or not
Mongoose - Check if `upsert` made a new document or not

Time:09-10

Is there any way to know if Mongoose's upsert option made a new document or not via await? Essentially I want to do this except without a callback.

Note: I'm using findByIdAndUpdate

CodePudding user response:

There is no difference in the callback, async await or even in with .then of mongoose functions

Callback

User.update({ _id: usr._id }, upsertData, { upsert: true }, function(err, num) {
  console.log(err)
  console.log(num)
}

Async Await

try {
  const num = await User.update({ _id: usr._id }, upsertData, { upsert: true })
  console.log(num)  
} catch (err) {
  console.log(err)
}

So basically both the above functions will log the same thing

Now what you want is to check whether the returned document is updated or upserted using findOneAndUpdate (findByIdAndUpdate)

const num = await User.findOneAndUpdate({ _id: id }, upsertData, { upsert: true })
console.log(num) 

So here num will print either the document if it is already exists or null if it is been inserted.

  • Related