【发布时间】:2022-02-16 00:40:27
【问题描述】:
我有这个集合 Cart(cart schema)要删除,它被其他 2 个方案引用,Meal 和 Customer (所有者用户,其架构为:User Schema)。
如何通过将 HTTP 请求中的用户 ID 作为 req.params.id 传递来删除购物车?
购物车架构
const mongoose = require('mongoose');
const idValidator = require('mongoose-id-validator');
const Schema = mongoose.Schema;
const cartItemSchema = new Schema ({
quantity: { type: Number, required: true },
itemId: { type: mongoose.Types.ObjectId, required: true, ref: 'Meal' }
});
const cartSchema = new Schema ({
cartItems : [
cartItemSchema
],
customer: { type: mongoose.Types.ObjectId, required: true, ref: 'User'}
});
cartSchema.plugin(idValidator);
module.exports = mongoose.model('Cart', cartSchema);
我创建了一个删除文档的函数,但它不起作用,它返回消息:'Deleted cart.',但不是真的,文档仍在集合中。
const deleteCartByUserId = async (req, res, next) => {
const userId = req.params.uid;
let cart;
try {
cart = await Cart.find({ customer: userId });
} catch(err) {
const error = new HttpError('Something went wrong, could not delete cart.', 500);
return next(error);
}
if(!cart) {
const error = new HttpError('Could not find cart for this user id.', 404);
return next(error);
}
try {
Cart.deleteOne({ customer: userId });
} catch(err) {
console.log(err);
const error = new HttpError('Something went wrong, could not delete cart.', 500);
return next(error);
}
res.status(200).json({ message: 'Deleted cart.' });
};
【问题讨论】:
-
您可以使用 cart._id 和 Model.findByIdAndRemove() 删除购物车,但每个用户可以拥有多个购物车。你怎么知道要删除哪一个?
-
@Parham.rm 因为每个客户都只有一个购物车。用户的 id 由客户端传递,服务器删除该特定购物车。我知道我需要为购物车添加约束以使每个用户都是唯一的,但我需要先添加此功能
-
好的。所以我猜你忘了在 Cart.deleteOne 之前使用 await。
-
你是对的,它现在可以工作了。一个半小时没有意识到这个小错误。非常感谢