How to create document if not exists, otherwise, update and return document in either case with Mongoose?

Sometimes, we want to create document if not exists, otherwise, update and return document in either case with Mongoose.

In this article, we’ll look at how to create document if not exists, otherwise, update and return document in either case with Mongoose.

How to create document if not exists, otherwise, update and return document in either case with Mongoose?

To create document if not exists, otherwise, update and return document in either case with Mongoose, we can use the findOneAndUpdate method.

For instance, we write

const query = {}
const update = {
  expire: new Date()
}
const options = {
  upsert: true,
  new: true,
  setDefaultsOnInsert: true
};

Model.findOneAndUpdate(query, update, options, (error, result) => {
  if (error) {
    return;
  }
});

to call findOneAndUpdate with the query, update, options and a callback.

query has the query to find the item to update.

update is an object that has the fields with the values we want to update.

options has upsert set to true to find an existing document if it exists or create a new one.

new is set to true to create a new document if it doesn’t exist.

The result parameter in the callback should have the latest document value.

Conclusion

To create document if not exists, otherwise, update and return document in either case with Mongoose, we can use the findOneAndUpdate method.