Álvaro Valencia
Álvaro Valencia

Reputation: 1217

How to update a document only if a condition is met?

I'm trying to implement a put method in a express API in order to allow the user to update a document, but only if a condition is met. Let's say I have an Instance document. One of its attributes is executed, which can be true if the instance was execute or false if it wasn't. Basically I want to allow the user to update this document only if the instance hasn't been executed, it is, if the executed attribute is false.

I've come up with this approach, but I'd like to know whether there is a better approach to do it, for instance, using the pre function in the schema definition.

Instance.findOne({'_id': req.params.id}, function(err, element){
    if(!element.executed){
        Instance.findOneAndUpdate({'_id': req.params.id}, {$set: req.body}, function(err, element){
            ...
        });
    }
})

Thanks!

Upvotes: 1

Views: 497

Answers (2)

Niral Munjariya
Niral Munjariya

Reputation: 1391

If you want to update the single document, you can use:

Instance.findOneAndUpdate({
  '_id': req.params.id,
  executed: false
}, req.body, {
  new: true
}, (err, instance) => {
  if(err){
    console.error('error occurred', err);
  } else {
    console.log('updated instance', instance)
  }
});

{new: true} will return the updated instance.

For more detail please check the documentation here.

Upvotes: 1

rajansoft1
rajansoft1

Reputation: 1356

You can use update method,

Instance.update({'_id': req.params.id, executed: false}, req.body, function(){})

Upvotes: 1

Related Questions