嵌入式数组对象中的mongo db更新对象

时间:2019-09-20 09:21:09

标签: arrays node.js mongodb mongoose embedded-documents

{
  "_id": "5d845d17008e24001223005d",
  "product_brand_name": "WAREHOUSE",
  "product_sku": "45203591500",
  "product_name": "UTILITY PIQUE SHIRT",
  "product_description": "Fabric: Main, 48% nylon, 52% viscose\r\nWash Care: Machine wash",
  "product_price": 69,
  "product_attribute": [{
      "attribute_name": "color",
      "attribute_value": "White / Stone"
    },
    {
      "attribute_name": "size",
      "attribute_value": "12"
    }
  ],
  "product_images": [{
    "image_name": "sample Image",
    "image_url": null
  }],
  "product_volumes": [{
      "volume_location": {
        "_id": "5d8491ebcc31ba001bdc9b88",
        "location_name": "nasscom bangalore",
        "location_Address": "Bangalore"
      },
      "quantity": 4
    },
    {
      "volume_location": {
        "_id": "5d8491ebcc31ba001bdc9b87",
        "location_name": "nasscom Delhi",
        "location_Address": "Delhi"
      },
      "quantity": 3
    }
  ]
}

这是我要更新的产品集合。

当用户在任何位置购买任何产品时,我要从该位置的产品总数中扣除购买的产品数量。

所以我试图查找和更新带有产品ID和product_volumes.volume_location.location_name的产品,并设置product_volumes。$。quantity(当前数量与购买数量的差)。

这是我正在尝试的代码。

exports.purchase = function (req, res) {
    Customer.findByIdAndUpdate(req.body.customer, { $set: { "customer_cart": null } }).then(function (doc) {
        const prods = req.body.products;

        let requests = prods.reduce((promiseChain, item) => {
            return promiseChain.then(() => new Promise((resolve) => {
                console.log("Promise started");
                Product.findByIdAndUpdate({
                    "_id" : item.product,
                    "product_volumes.volume_location.location_name": item.pickup_location.location_name
                },{
                    $set:{
                        "product_volumes.$.quantity" : { $subtract: [ product_volumes.$.quantity, item.product_quantity ] }
                    }
                }).then(resolve)

            }));
        }, Promise.resolve());

        requests.then(() => {
            console.log("done");
            res.send(req.body);
        })
    });
};

这是我得到的错误。

The positional operator did not find the match needed from the query.
     at Connection.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/connection/pool.js:443:61)
     at Connection.emit (events.js:198:13)
     at processMessage (/usr/src/app/node_modules/mongodb-core/lib/connection/connection.js:364:10)
     at Socket.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/connection/connection.js:533:15)
     at Socket.emit (events.js:198:13)
     at addChunk (_stream_readable.js:288:12)
     at readableAddChunk (_stream_readable.js:269:11)
     at Socket.Readable.push (_stream_readable.js:224:10)
     at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)

0 个答案:

没有答案