Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda