Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
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?

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

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda