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.