MongoDB: How to update multiple records based on a value in the record itself?

Viewed 22

I'd really appreciate if anyone can help with a mongodb + nodejs problem.

So Id like to write a job that updates, for example, a rating field in every document of a restaurant profile collection. The new value is going to be a calculated average rating of all the users who rated that profile, in MongoDB + Nodejs.

Lets say I have a restaurant profile collection whose schema looks like the following:

{
  _id:  XXXX,
  name: "Taco Bell",
  cuisine: "Mexican",
  address: "876 SomeRoad Rd, New York, NY, 10020",
  averageRating: 4,
  ratings: [{
     value: 1,
     byId: ObjectId("XXXXXXX")
  }, {
     value: 3,
     byId: ObjectId("XXXXXXX")
  }, {
     value: 5,
     byId: ObjectId("XXXXXXX")
  }]
}

So as users keep rating that restaurant, I keep pushing the new ratings to the "ratings" field, but then I d like to run a job that updates the "averageRating" based off the "ratings" field periodically.

How can I do that ?

1 Answers

Your problem is a good use case for database hooks. Considering you are using mongoose ORM, you can add a pre update hook on your schema and calculate and update the new average rating in the same update query. Following is an example to implement a pre update hook:

your_schema.pre('update', function(next) {
    const recordsToUpdate = this.getUpdate();
    // calculate the new average rating and append to the records
    next();
  })
});

You can check here for reference. Hope this helps.

Related