当产品被删除时,我正在try 从用户购物车中删除该产品.
我的用户架构:
const userSchema = new Schema({
username: { type: String, required: true },
phone: {
type: String,
match: [/\d{10}/, 'Phone number should only 10 have digits'],
},
email: {
type: String,
match: [/\S+@\S+\.\S+/, 'Email must be valid'],
required: [true, 'Email must be valid'],
unique: true,
},
password: {
type: String,
required: [true, 'Password is not valid'],
},
cart: {
items: [
{
productId: {
type: Schema.Types.ObjectId,
ref: 'Product',
},
quantity: {
type: Number,
max: [10, 'Only 10 quantity of one item can be added.'],
required: true,
},
},
],
total: { type: Number, default: 0 },
},
admin: { type: Boolean, default: false },
addresses: [addressSchema],
});
我try 使用以下代码从Items数组中删除该项:
await User.updateMany({}, { cart: { $pull: { 'items.productId': id } } });
个
但是,这会删除整个购物车对象,而不是单个项目.请谁来帮帮我.