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

121
Vistas
How to update multiple document using mongoose and get their id's?
    const itemSchema = mongoose.Schema(
  {
    itemType: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Item_Type",
    },
   inStore:{type:Boolean,default:true}
  },
  { timestamps: true  }
);
export default mongoose.model("Item", itemSchema);

const requestingTransactionSchema = mongoose.Schema(
requestedItems: [
          {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Item",
          },
        ],       
  },{timestamps:true},
);
export default mongoose.model("Requesting_Transaction", requestingTransactionSchema );

I have multiple items that are currently in store. Then there is a department that asks for x quantity of items from store. I wanted to find those items(based on quantity needed) then update the inStore field to false then get those updated items id and add it to the Requesting_Transaction document items field. Now the problem I'm facing is updating those items inStore field and getting the id's in a single query.

I have this code but I don't think its efficient.

let updatedItemsIds=[]
for (let j = 1; j <= quantity; j++) {
          const item = await ItemCollection.findOneAndUpdate({
            inStore: true,
          },{inStore: false});
        updatedItemsIds.push(item._id);
}

await RequestingTransactionCollection.create({requestedItems:updatedItemsIds});
about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

You need to see again your query, in findAndUpdate method you need to pass find condition and updating fields. where is your find condition? if quantity is based on itemType and itemType's type is objectId, you need to use populate or aggregate function.

let updatedItemsIds=[]
for (let j = 1; j <= quantity; j++) {
      const item = await ItemCollection.findOneAndUpdate({match condition}, {$set: {isStore: false}})

}

about 4 years ago · Santiago Gelvez 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