Reputation: 521
I have this following Mongoose User Schema:
postCreated:{
type: Array,
default: []
}
which contains an Array of Object of Posts belong to that user. I plan to do the following: When I delete a particular post, I pass the id of that post and the username of the user that created to the back-end and hope that it would remove the post from both Post schema and postCreated of a user that it belongs to
server.del('/posts',(req,res,next)=>{
const {id,username} = req.body;
User.findOne({username}).then(user => {
console.log(user.postCreated)
user.postCreated.filter(post => {
post._id !== id;
});
console.log(user.postCreated)
});
Posts.findOneAndRemove({_id: id}).then((post) => {
if(!post){
return next(new errors.NotFoundError('Post not found'));
}
res.send(post);
})
.catch((e) => {
return next(new errors.BadRequestError(e.message));
});
});
However, the post only got removed from the Post Model, and not from postCreated of User Model, meaning that the user.postCreated.filter did not work.
I have tried the following, thanks to Jack, but seems like it did not solve the issue:
User.update(
{ username },
{ $pull: { postCreated: {_id: id} } },
{ multi: true }
);
Is there any way that I could fix this?
I would really appreciate any help.
Upvotes: 3
Views: 560
Reputation: 613
If you want to do it the way you were doing you need to store back your postCreated array into it self and then save the user:
User.findOne({username}).then(user => {
console.log(user.postCreated)
user.postCreated = user.postCreated.filter(post => {
post._id !== id;
});
console.log(user.postCreated);
user.save();
});
But the best way is findOneAndUpdate if you need the user object later on.
Upvotes: 2
Reputation: 4983
Use: https://docs.mongodb.com/manual/reference/operator/update/pull/
User.update(
{ username },
{ $pull: { postCreated: id } },
{ multi: true }
);
This should solve your query.
Upvotes: 1