更新时间:2023-01-19 13:13:20
在仔细查看您的问题后,我发现您的 User
模型架构有问题.所以我相应地更新了答案.
After closely looking at your problem what I found is something wrong with your User
Model schema. So I have updated the answer accordingly.
在您的 User
模型中,_carts
字段具有您使用的以下架构.
In your User
model the _carts
filed has following schema you have used.
_carts: [{
type: Schema.Types.ObjectId,
ref: 'cart'
}]
因此,根据您的架构,该数组包含 Objectids
,它引用了 cart
模型.(例如:_carts:[ObjectId1,ObjectId2,Object3 ....])
So as per your schema the array contains Objectids
which has reference to cart
model. (example: _carts:[ObjectId1,ObjectId2,Object3 ....])
但是在您的种子数据中,文档是
But in your Seed data the document is
const User1 = {
_id: '1234',
_carts: [{
_id: '1',
_product: {},
quantity: 2
},
{
_id: '2',
_product: {},
quantity: 4
}],
admin: false
}
在 _carts
数组中有 objects
.根据架构,它应该是 ObjectIds
而不是 Objects
which has objects
in _carts
array. As per schema it should be ObjectIds
not Objects
现在根据您的查询 { $pull: { '_carts': { _id: (cart_id) }}}
您正在尝试提取具有 _id = cart_id 的文档
代码>.但是您的 _carts
架构中没有 _id
可用.
Now as per your query { $pull: { '_carts': { _id: (cart_id) }}}
you are trying to pull the document which has _id = cart_id
. But there is no _id
available in your _carts
schema .
这是我的分析.如果您想在 carts
数组中存储 cart
详细信息.那么你的 User
模型的架构应该是
So here is my analysis. If you want store cart
details in carts
array. Then your User
model's schema should be
_carts : [cartSchema]
否则您的 update
查询没有问题.它应该可以工作.
Otherwise your update
query has no problem. It should work.
您提到的错误是由于 mongodb
连接问题造成的.请按照更新的 Mongoose
文档了解如何正确连接 Mongodb.
The error you have mentioned is due to mongodb
connection issue. Please follow updated Mongoose
doc on how to connect Mongodb properly.