英文:
How to pull an array element from array nested inside an object in mongoose?
问题
我尝试使用以下代码从items数组中删除项目:
await User.updateMany({}, { cart: { $pull: { 'items.productId': id } } });
但是这会删除整个购物车对象,而不是单个项目。请有人帮助我解决这个问题。
英文:
I am trying to remove the product from the users cart when the product is deleted.
My User Schema:
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],
});
I tried this code to remove the item from items array:
await User.updateMany({}, { cart: { $pull: { 'items.productId': id } } });
However this deletes the whole cart object instead of single items. Please someone help me with this.
答案1
得分: 2
以下是翻译好的部分:
查看这个官方示例 移除所有等于指定值的项
{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }
field1
应该是一个数组,cart.items
是一个数组。这意味着我们要从 cart.items
数组中移除一些元素。
db.collection.updateMany({},
{
$pull: {
"cart.items": {
productId: 2
}
}
})
输入:
[
{
"_id": ObjectId("5a934e000102030405000000"),
cart: {
items: [
{
productId: 1
},
{
productId: 2
},
{
productId: 3
},
]
}
}
]
输出:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"cart": {
"items": [
{
"productId": 1
},
{
"productId": 3
}
]
}
}
]
英文:
Take a look at this official example Remove All Items That Equal a Specified Value
{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }
The field1
should be an array, cart.items
is an array. This means we pull some elements from the cart.items
array.
db.collection.updateMany({},
{
$pull: {
"cart.items": {
productId: 2
}
}
})
Input:
[
{
"_id": ObjectId("5a934e000102030405000000"),
cart: {
items: [
{
productId: 1
},
{
productId: 2
},
{
productId: 3
},
]
}
}
]
Output:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"cart": {
"items": [
{
"productId": 1
},
{
"productId": 3
}
]
}
}
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论