最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何更新对象中的数组,如果不存在则推送

运维笔记admin16浏览0评论

如何更新对象中的数组,如果不存在则推送

如何更新对象中的数组,如果不存在则推送

我愿意使用req.params.cartid来更新现有的购物车来查找它并更新数组中的对象,如果产品不存在则推送新产品

这是我的猫鼬Schema

const shoppingCartSchema = mongoose.Schema({
    user_id: { type: String, required: true},
    cart_date: { type: String, required: true},
    activeCart: { type: Boolean, required: true },
    cart_content: [{
        product_id: { type: String, required: true},
        product_quantity: { type: Number, required: true},
    }]
})

让我们说我有一个购物车:

{
    "_id" : ObjectId("5c6830c9a7e056443ce8befe"),
    "user_id" : "5c4e1a3cbc446733801b5a54",
    "cart_date" : "2019-02-16T15:48:25.464Z",
    "activeCart" : true,
    "cart_content" : [ 
        {
            "_id" : ObjectId("5c6830c9a7e056443ce8beff"),
            "product_id" : "1",
            "product_quantity" : 1
        }
    ],
    "__v" : 0
}

方法:

router.post("/:update", (req, res, next) => { 
     const cart_id = req.params['update'];
     const product_id = req.body.product_id;
     Cart.update({"_id": cart_id},
     //{Here to find the cart_content[index].product_id}
     //{add +1 to product_quantity if product_id === to the req.product_id}
     //{if no such product_id, push the new product {
      "product_id": req.body.product_id,
      "product_quantity": req.body.product_quantity
}).then(response => {
console.log(response);
} 
});

如果更新结果应为:

{
    "_id" : ObjectId("5c6830c9a7e056443ce8befe"),
    "user_id" : "5c4e1a3cbc446733801b5a54",
    "cart_date" : "2019-02-16T15:48:25.464Z",
    "activeCart" : true,
    "cart_content" : [ 
        {
            "_id" : ObjectId("5c6830c9a7e056443ce8beff"),
            "product_id" : "1",
            "product_quantity" : 2 ****
        }
    ],
    "__v" : 0
}

如果没有这样的id推新产品:

{
    "_id" : ObjectId("5c6830c9a7e056443ce8befe"),
    "user_id" : "5c4e1a3cbc446733801b5a54",
    "cart_date" : "2019-02-16T15:48:25.464Z",
    "activeCart" : true,
    "cart_content" : [ 
        {
            "_id" : ObjectId("5c6830c9a7e056443ce8beff"),
            "product_id" : "1",
            "product_quantity" : 1
        }, {
            "_id" : ObjectId("5c6830c9a7e056443ce8b421"),
            "product_id" : "2",
            "product_quantity" : 1

    ],
    "__v" : 0
}
回答如下:

正如@mzparacha在我的问题评论中所述,以下是我的问题的答案:MongoDB Update array element (document with a key) if exists, else push

我想你应该检查一下stackoverflow/questions/41316056 / ...它正在描述相同问题的解决方案,但效率不高

发布评论

评论列表(0)

  1. 暂无评论