Expressingx
Expressingx

Reputation: 1572

Mongoose not deleting subdocument

My delete route is

const id = req.body.id;
const postId = req.body.postId;

if (mongoose.Types.ObjectId.isValid(id)) {
    Comment.findByIdAndRemove({ _id: id }, (err, cRes) => {
        if (err) return err;

        Post.findOneAndUpdate({ _id: postId }, {
            $pull: {
                Comments: {
                    _id: id
                }
            }
        }, (err, doc, res) => {
            if (err) console.log(err);

            res.redirect(req.get('referer'));
        });
    });
}

And the problem is that it does delete the comment from the Comment table but it doesn't delete the comment to the related Post, why is that?

PostSchema

var PostSchema = new mongoose.Schema({
 Author: String,
 Title: String,
 Description: String,
 Comments: [{
    type: mongoose.Schema.Types.ObjectId, ref: 'Comment'   
 }],
 Tags: [{
    type: mongoose.Schema.Types.String, ref: 'Tag'
 }],
 CreatedOn: Date,
 LastEditOn: Date
});

CommentSchema

var CommentSchema = new mongoose.Schema({
 _postId: {
    type: String,
    ref: 'Post' 
 },
 Author: String,
 Description: String,
 CreatedOn: Date,
 LastEditBy: Date
});

Upvotes: 1

Views: 134

Answers (1)

Ashh
Ashh

Reputation: 46441

no need to put _id during pull because you haven't mentioned any key in Comments of Post collection.

if (mongoose.Types.ObjectId.isValid(id)) {
    Comment.findByIdAndRemove({ _id: id }, (err, cRes) => {
        if (err) return err;

        Post.update({ _id: postId }, {
            $pull: {
                Comments: id
            }
        }, (err, doc, res) => {
            if (err) console.log(err);

            res.redirect(req.get('referer'));
        });
    });
}

If you define _id in post schema like

Comments: [{
    _id: { type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }
 }]

then your query could have worked.

Upvotes: 2

Related Questions