1

I want to update a field in my MongoDB database with Mongoose if the new value of that field wouldn't be greater than another field. Here is my code:

Training.findOneAndUpdate(
    { date: dateStringForDB, startHour: retrievedRequest.body.trainingStartHour },
    { $push: { participants: retrievedRequest.session.loggedInPhoneNumber }, $inc: { currentQuota: +1 } },
    (err, doc, updateResponse) => {
      if (err) {
        console.log("Error while updating training ", err);
        return;
      }

      retrievedResponse.redirect("/schedule");
    }
  );

What I want to do is increment the value of currentQuota only if value of 'currentQuota' is smaller than another field's (initialQuota) value. Is there a way to do it with findOneAndUpdate method or shall I call find method first and then update?

Thanks in advance!

Metin
  • 184
  • 1
  • 12
  • 1
    If you're trying to compare two fields within the same document, you can try this in your filter query object. `{ date: dateStringForDB, startHour: retrievedRequest.body.trainingStartHour, $expr: { $gt:["$initialQuota", "$currentQuota"] } }`. Ref: https://stackoverflow.com/questions/4442453/mongodb-query-condition-on-comparing-2-fields/48410935#48410935 – v1shva Jun 21 '20 at 19:41
  • Hey @v1shva! That is exactly what I was looking for - thanks a lot, been a great help. – Metin Jun 21 '20 at 20:07
  • Happy to help, I added a answer with additional docs, if you need it. – v1shva Jun 21 '20 at 20:50
  • var query = { owner: 'bingo', weight: { $lt: 55 } }; model = await Dummy.findOne(query); – user1912383 Nov 05 '20 at 19:33

1 Answers1

1

You can compare two fields within the same document using $expr in your query object.

Training.findOneAndUpdate(
    { date: dateStringForDB, startHour: retrievedRequest.body.trainingStartHour, $expr: { $gt:["$initialQuota", "$currentQuota"] } },
    { $push: { participants: retrievedRequest.session.loggedInPhoneNumber }, $inc: { currentQuota: +1 } },
    (err, doc, updateResponse) => {
      if (err) {
        console.log("Error while updating training ", err);
        return;
      }

      retrievedResponse.redirect("/schedule");
    }
  );

Refer to this for more info: MongoDb query condition on comparing 2 fields

Mongodb docs: https://docs.mongodb.com/manual/reference/operator/query/expr/

v1shva
  • 1,261
  • 3
  • 13
  • 28