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});
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}})
}