I have this working well, however, I’m worried about the performance - eg if I have 100 locations, it means 300 operations.
Is there a way to simplify this, and still achieve the same thing?
const filter = { organizationId, itemId }
const locationsData = [{ locationId, locationQtyInc: 2 }, {...}]
const operations = []
// I have a list of locations, and the quantities to be be updated for each - looping through and adding to operations list for EACH LOCATION!
const locationQtyInc = 2
operations.push(
...[
// make sure the document exists - it might exist or not
{ updateOne: { filter, update: { $setOnInsert: { locations: [] } }, upsert: true } },
// make sure the specific location exists - the location element might exist or not
{
updateOne: {
filter: { ...filter, "locations.locationId": { $ne: locationId } },
update: { $addToSet: { locations: { locationId } } },
},
},
// add or update the location stock details
{
updateOne: {
filter: { ...filter, "locations.locationId": new ObjectId(locationId) },
update: {
$inc: {
"locations.$.committedStock": locationQtyInc,
"locations.$.stockLevel": locationQtyInc,
},
$set: { updatedAt: new Date() },
},
},
},
],
)