Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

86
Vistas
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?

9 months ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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'}}}]);
9 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos