Yauheni Pozdnyakov
Yauheni Pozdnyakov

Reputation: 203

Mongoose update document with conditions

I need to unset mongo field which is ObjectId and refers to another schema if this ID is Id of a current user and this field is set. In other case, if this field is unset, current user ID should be set. If the field is set and ObjectID doen't match the current user ID's mongo should return existing document but without changes apllied to the ObjectID field.

Right now I find entry by ID and then check cases in my JS code. Then I perform another query in order to update the document. But I think that this could be done by mongo in one query.

I'm using mongoose in my nodeJS

Upvotes: 0

Views: 5163

Answers (1)

Gaurav
Gaurav

Reputation: 609

Mongoose findOneAndUpdate is the function you are looking for.It has following general syntax. query.findOneAndUpdate(conditions, update, options, callback) Edit: appended an example query.

var query = {"_id": id};
var update = {name: {first: 'john', last: 'smith'}};
var options = {new: true};
People.findOneAndUpdate(query, update, options, function(err, person) {
  if (err) {
    console.log('got an error');
  }

  // at this point person is null.
});

Upvotes: 1

Related Questions