删除文档中的数组元素并保存,但它仍然存在(MongoDb使用NodeJS)



我有一个购物车。在模式的当前状态下,其中包含的每个元素都由Products数组中的对象表示。对该函数的每次调用都会从通过其itemId传递的对象中删除一个等于1的数量。当我想删除一个数量等于1的对象(所以数量值达到0),我想从购物车中删除对象(所以itemId &从Products数组中获取quantity)。在大于1的情况下,当只有减少数量的值时,它工作,而当有消除产品时,消息'已删除商品在购物车中'。但这不是真的,它仍然在数据库中

购物车模式

const mongoose = require('mongoose');
const idValidator = require('mongoose-id-validator');
const Schema = mongoose.Schema;

const cartSchema = new Schema ({
products: [
{
productId: { type: mongoose.Types.ObjectId, required: true, ref: 'Product' },
quantity: { type: Number, required: true },
}
],
customer: { type: mongoose.Types.ObjectId, required: true, unique: true, ref: 'User'}
});

cartSchema.plugin(idValidator);
module.exports = mongoose.model('Cart', cartSchema);

减小函数

const removeToCartByUserId = async (req, res, next) => {
const userId = req.params.uid; 
const { productId } = req.body;
const quantity = 1;
try {
let cart = await Cart.findOne({customer: userId});
//Cart exist for user
if(cart) {
let itemIndex = cart.products.findIndex(p => p.productId == productId);
//product exists in the cart, update the quantity
if (itemIndex > -1) {
let productItem = cart.products[itemIndex];
if(productItem.quantity > 1) {
productItem.quantity -= quantity;
cart = await cart.save();
res.status(201).json({ cart });
} else { // delete product in array
await cart.products.pull({ productId: productId }) // removed
cart = await cart.save();
res.status(200).json({ message: 'Deleted item in cart.' });
}
} 
} else { // no Cart for the user, exit
const error = new HttpError('Something went wrong with the cart.', 500);
return next(error); 
}
} catch(err) {
console.log(err);
const error = new HttpError('Something went wrong with the cart.', 500);
return next(error); 
}
};

更新:我编辑了代码,现在它可以工作了

//product exists in the cart, update the quantity
if (itemIndex > -1) {
let productItem = cart.products[itemIndex];
productItem.quantity -= quantity;
if(productItem.quantity > 0) {
cart = await cart.save();
res.status(201).json({ cart });
} else { // delete product in array
await Cart.updateOne(
{ itemIndex },
{$pull : { "products": { productId } } }
);
res.status(200).json({ message: 'Deleted item in cart.' });
}
}

稍微修改一下你的代码。

//product exists in the cart, update the quantity
if (itemIndex > -1) {
let productItem = cart.products[itemIndex];
productItem.quantity -= quantity;
if(productItem.quantity > 1) {
cart = await cart.save();
res.status(201).json({ cart });
} else { // delete product in array
await cart.products.pull({ productId }) // removed
res.status(200).json({ message: 'Deleted item in cart.' });
}
}

你需要在if之前降低产品质量,否则else语句将不会被调用,而它应该被调用。

另外,我已经删除了cart.save调用,这可能是为了在调用pull之后您的本地数据已经过时,因此调用save将使用pull之前的数据更新数据库,从而恢复删除项目。

最新更新