Mongoose不删除子文档

时间:2018-04-03 09:28:46

标签: node.js mongodb express mongoose

我的删除路线是

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'));
        });
    });
}

问题在于它确实删除了Comment表中的评论,但它没有删除对相关Post的评论,为什么会这样?

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
});

1 个答案:

答案 0 :(得分:2)

无需在_id期间提出pull因为您未在Comments Post集合中提及任何密钥。

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'));
        });
    });
}

如果您在帖子架构中定义_id,如

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

然后你的查询就可以了。