【问题标题】:Update document by matching subdocument (mongodb)通过匹配子文档(mongodb)更新文档
【发布时间】:2021-02-25 07:02:09
【问题描述】:

我在尝试更新购物车记录时遇到了这个问题。 我通过客户 ID 搜索购物车,然后更新文档,但 db 记录仍然相同

   const cart = new Cart({
    //customer:{_id:req.body.customer},
    product:req.body.products,
    location:req.body.location,
    totalPrice:totalPrice,
    promoCode:req.body.promoCode
    
});

const existingConsumer = await Cart.findOne({customer:{_id:req.body.customer}});


if(JSON.stringify({})===JSON.stringify(existingConsumer) || existingConsumer==null){

    const savedCustomers = await cart.save().then(data=>{
             res.json(data);
        }).catch(err=>{
            res.json(err);
        })
    //res.json(savedCustomers);
}else{
    
    // const res = await Cart.updateOne({customer:{_id:ObjectId(req.body.customer)}},cart);
    Cart.updateOne({customer:{_id:ObjectId(req.body.customer)}},{"$push":req.body.products}).then(result => {
        const { matchedCount, modifiedCount } = result;
        if(matchedCount && modifiedCount) {
          console.log(`Successfully added a new review.`)
        }
        console.log(result)
        
      })
      .catch(err => console.error(`Failed to add review: ${err}`));
    // console.log(res.n)
    // console.log(res.nModified)
}

如您所见,我尝试了几种方法。 findOneAndUpdate/UpdateOne/populate,到目前为止,这些都不适合我。 在 UpdateOne 上,我收到“在路径 '_id' 上执行更新会修改不可变字段 '_id'”错误,据我了解,这意味着它试图更新客户 _id 或某些 _id,而且它显然是不可变的。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    所以问题是 - 如果您基于 Cart 模式创建新对象,那么您会得到 _id(应该为 0),因此会引发错误。要解决这个问题,只需使用简单的对象声明。

    【讨论】:

      猜你喜欢
      • 2011-08-04
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 2018-10-08
      • 1970-01-01
      • 2014-02-05
      相关资源
      最近更新 更多