Categories
JavaScript Answers

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

Spread the love

To create document if not exists, otherwise, update and return document in either case with Node.js Mongoose, we call 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 and the update object that has the values to update in the documents.

And then the updated document are set as the value of the result parameter.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *