Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!