简体   繁体   中英

Update document by matching subdocument (mongodb)

I am facing this issue when I am trying to update cart record. I search for cart by customer ID and then update document, but db record is still the same

   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)
}

As you can see I tried few ways. findOneAndUpdate/UpdateOne/populate, none of these work for me so far. on UpdateOne I get "Performing an update on the path '_id' would modify the immutable field '_id'" error, which as far as i understand means it tries to update customer _id or some _id and it obviously immutable.

So the problem was - if you create new object based on Cart schema, then you get _id (which should be 0), hence it throws error. To fix that, just use simple object declaration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM