Mongoose - Create document if not exists, otherwise, update- return document in either case Mongoose - Create document if not exists, otherwise, update- return document in either case javascript javascript

Mongoose - Create document if not exists, otherwise, update- return document in either case


You are looking for the new option parameter. The new option returns the newly created document(if a new document is created). Use it like this:

var query = {},    update = { expire: new Date() },    options = { upsert: true, new: true, setDefaultsOnInsert: true };// Find the documentModel.findOneAndUpdate(query, update, options, function(error, result) {    if (error) return;    // do something with the document});

Since upsert creates a document if not finds a document, you don't need to create another one manually.


Since you wish to refactor parts of your code to be shorter and simpler,

  1. Use async / await
  2. Use .findOneAndUpdate() as suggested in this answer

let query = { /* query */ };let update = {expire: new Date()};let options = {upsert: true, new: true, setDefaultsOnInsert: true};let model = await Model.findOneAndUpdate(query, update, options);


///This is simple example explaining findByIDAndUpdate from my code added with try catch block to catch errorstry{const options = {            upsert: true,            new: true,            setDefaultsOnInsert: true        };        const query = {            $set: {                description: req.body.description,                title: req.body.title            }        };        const survey = await Survey.findByIdAndUpdate(            req.params.id,            query,            options        ).populate("questions");}catch(e){console.log(e)}