Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you update if exists otherwise insert new document?

In order to create a document if it doesn't already exist, you need to pass { upsert : true } in the options hash as it defaults to false . i.e. update is deprecated. Use updateOne, updateMany, or bulkWrite instead.

What does findOneAndUpdate return if not found?

If findOneAndUpdate doesn't find any document that matches your request, doesn't mean that it's an error. err is null because there is no error in the execution of the request. It's true that your code is asynchronous, but you're using callbacks, so the given err and doc is exactly what it should be returned.

Which option of the update method creates a new document if no documents match the query to update?

Upsert with update() method: If a document or documents found that matches the given query criteria, then the update() method updates the document/documents. If no document/documents match the given query criteria, then the update() method inserts a new document in the collection.

How can I update multiple documents in Mongoose?

Model. updateMany = function ({}, {cid: ''}, function(err) { ... }); I believe that Mongoose wraps your cid in a $set, so this is not the same as running that same update in the mongo shell. If you ran that in the shell then all documents would be replaced by one with a single cid: '' .


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 document
Model.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);