Home > Net >  mongoose update document when aggregating
mongoose update document when aggregating

Time:12-15

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?

CodePudding user response:

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'}}}]);
  • Related