【发布时间】:2021-03-16 21:37:38
【问题描述】:
所以在产品已经存在于购物车中的情况下,我很难将文档保存到数据库中。我能够从数据库中定位项目,对其进行更改并控制台输出正确的值,但在这种特殊情况下,它不会将结果保存到数据库中。我尝试使用 updateOne() 函数重写它,但运气不佳。我真的可以使用我超级卡在这个问题上的帮助。图片了解更多信息:Block of code that's not working、console output that reflects desired change、mongoDB 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');
}
})
【问题讨论】: