3

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.

1
  • 1
    You need to use $pull to remove an element from the array Commented Nov 12, 2018 at 15:50

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

this works for me. but is there any alternate for this?
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.