【问题标题】:Having trouble saving document to mongoDB无法将文档保存到 mongoDB
【发布时间】:2021-03-16 21:37:38
【问题描述】:

所以在产品已经存在于购物车中的情况下,我很难将文档保存到数据库中。我能够从数据库中定位项目,对其进行更改并控制台输出正确的值,但在这种特殊情况下,它不会将结果保存到数据库中。我尝试使用 updateOne() 函数重写它,但运气不佳。我真的可以使用我超级卡在这个问题上的帮助。图片了解更多信息:Block of code that's not workingconsole output that reflects desired changemongoDB document that the changes will not save to

如果有人能指出我正确的方向,我将不胜感激。

router.post('/add-to-cart',[
          auth,
          check('productId','productId is required').not().isEmpty(),
          check('quantity', 'quantity is required').not().isEmpty()
    
    ] ,   async (req,res) => {
            //checks field validation
            const errors = validationResult(req);
    
            if(!errors.isEmpty()){
                res.status(400).json({errors:errors.array()});
            };
    
            //Takes token from the header
            const token = req.header('x-auth-token');
            if (!token){
                return res.status(401).json({ msg: 'no token, auth denied'});
            }
    
            //decode token and find associated user
            const decoded = jwt.verify(token, config.get('jwtSecret'));
            let userPayload = decoded.user;
            
    
            //build cart object
            try{
                //populate from request body
                const {productId, quantity} = req.body;
                //find User using the payload
                let user = await User.findById(userPayload.id);
                //get the product from db
                let product = await Product.findById(productId);
                //calculate price of item(s) added to cart
                let total = ( quantity * product.price);
    
                //create cart object 
                //Check to see if cart already exists
                let iscart = await Cart.findOne({user:user});
                //there is an existing cart
                *if(iscart){
                    let found = false;
                    for (i=0;i<iscart.orderItems.length;i++)
                    {
                        if(iscart.orderItems[i].product._id.toString() == product._id.toString()){
                            found=true;
                            console.log('found that product!');
                            iscart.orderItems[i].qty += quantity;
                            try{
                                await iscart.save();
                                console.log(iscart); 
                                }
                            catch(err){
                                console.error(err);
                                res.status(500).send('server error');
                            }
                            res.status(200).send(iscart.orderItems[i]);
                            break;
                        }*
                    }
                    if(!found){
                        await Cart.updateOne(
                            {user:iscart.user},
                            {$push:{orderItems:
                                { 
                                product:product,
                                qty:quantity,
                                total:total 
                                }}
                            }
                            )
                            res.status(200).send('product pushed to orderItems')
                    }
                }
                //there isnt an existing cart so we create one
                else{
                    const cart = new Cart({
                        user,
                        orderItems:
                       { product:product,
                        qty:quantity,
                        total:total
                       }
                    })
    
                    await cart.save();
                   
                    res.status(200).send('cart created and saved');
                }
                
                
                
            }
            catch(err){
                console.error(err);
                res.status(500).send('server error');
            }
    
    })

【问题讨论】:

    标签: mongodb express mongoose


    【解决方案1】:

    想通了!!当您更新文档内的嵌套对象时,您必须将该对象标记为已修改,以便它知道更新它。这一行解决了我的问题:

    iscart.markModified('orderItems');
                           
                           
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      • 2017-10-08
      • 2015-01-07
      • 1970-01-01
      • 2020-01-28
      • 2021-09-22
      • 2016-10-09
      相关资源
      最近更新 更多