Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
mongoose update document when aggregating

I have a collection named room containing an array of pots called potArr. My room also have a property called average pot which should be equal to average of the potAmount values in potArr. I want to constantly update the average pot.

Here is my code:

const rooms = await roomModel.find({});
for (let room of rooms) {
  let sumOfPots = 0;
  room.potArr.forEach((pot) => {
    sumOfPots += pot.potAmount;
  };
  await roomModel.update({_id : room._id}, {$set : {averagePot: sumOfPots/room.pot.length}});
}

I want to be able to summorize the above code with one line using mongoose updateMany. How can I achieve that?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Do it like this:

await roomModel.collection.updateMany({}, [{$set: {averagePot: {$toInt: {$avg: '$potArr.pot'}}}}]);
  • You have to use .collection on your model to make mongoose behave like mongod.

  • I uset $toInt to round down the possible float outcome. You can skip that part like below.

await roomModel.collection.updateMany({}, [{$set: {averagePot: {$avg: '$potArr.pot'}}}]);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!