Thursday, 10 January 2019

Mongoose - How To Update Many Specific Records With One Value Per Reord?

How can I update multiple records using mongoose in NodeJS - Express, each with a unique value (the items do not all have the same value) without causing an N+1 problem? I have the following scenario:

Products:

[
{
 _id: "407f191e810c19729de860ea",
 title: "....",
 in_stock: 100,
 },
{
 _id: "507f1f77bcf86cd799439011",
 title: "....",
 in_stock: 100,
 },
....
]

Then given an "order" request like this:

[
 {
  item_id: "507f1f77bcf86cd799439011",
  quantity: 5
 },
 {
  item_id: "407f191e810c19729de860ea",
  quantity: 8
 },
...
]

In other words, given an array of id,quantity tuples, I need to reduce the stock of each corresponding record in the database. How can this be done without having to run one query per item?

From the example above, the end result in the db should be:

[
{
 _id: "407f191e810c19729de860ea",
 title: "....",
 in_stock: 92,
 },
{
 _id: "507f1f77bcf86cd799439011",
 title: "....",
 in_stock: 95,
 },
....
]



from Mongoose - How To Update Many Specific Records With One Value Per Reord?

No comments:

Post a Comment