Removing Object With Objectid From Array In Mongoose/mongodb
Solution 1:
Your problem is here in update function
User.update(
{'_id':user_id}, // you not need to use ObjectId here
{ $pull: { '_carts': { _id: cart_id }}},
function(err,result){
// can you give here the output of console.log(result);
}
)
User.save();
Solution 2:
After closely looking at your problem what I found is something wrong with your User
Model schema. So I have updated the answer accordingly.
In your User
model the _carts
filed has following schema you have used.
_carts: [{
type: Schema.Types.ObjectId,
ref: 'cart'
}]
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
constUser1= {
_id:'1234',
_carts: [{
_id:'1',
_product: {},
quantity:2
},
{
_id:'2',
_product: {},
quantity:4
}],
admin:false
}
which has objects
in _carts
array. As per schema it should be ObjectIds
not Objects
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 .
So here is my analysis. If you want store cart
details in carts
array. Then your User
model's schema should be
_carts : [cartSchema]
Otherwise your update
query has no problem. It should work.
The error you have mentioned is due to mongodb
connection issue. Please follow updated Mongoose
doc on how to connect Mongodb properly.
Post a Comment for "Removing Object With Objectid From Array In Mongoose/mongodb"