lmngn23
lmngn23

Reputation: 521

How to find and delete a particular object in an Array of Object in Mongoose

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

Answers (2)

Babak
Babak

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

Harshal Yeole
Harshal Yeole

Reputation: 4983

You can use mongoose $pull

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

Related Questions