Mongodb 是否需要删除一个文档,然后更新ref model';自动创建ObjectId数组?

Mongodb 是否需要删除一个文档,然后更新ref model';自动创建ObjectId数组?,mongodb,mongoose,Mongodb,Mongoose,这是我的模型 const UserSchema = mongoose.Schema({ name: String, comments: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Comment' } ] }); const CommentSchema = new mongoose.Schema({ comment: String, creatorId: { type: mo

这是我的模型

const UserSchema = mongoose.Schema({
  name: String,
  comments: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Comment'
    }
  ]
});

const CommentSchema = new mongoose.Schema({
  comment: String,
  creatorId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
});
用户可以有很多评论。
因此,用户和评论是一对多的关系。
当用户创建新注释时,将创建新注释,并将其ObjectId推送到用户的注释数组中

我想做的是, 删除一条注释时自动删除注释的ObjectId

我知道我可以通过两个查询来实现这一点。
有没有办法把这两个结合起来

await user.comments.remove(comment.id);
await comment.remove();

您不能在两个集合/架构上运行
remove
,但是您可以利用并在
commentschema
上定义这样的中间件:

CommentsSchema.post('remove', function(comment) {
    await UserSchema.update({ _id: comment.creatorId }, { $pull: { comments: comment._id } })
});

非常感谢你。我将尝试此操作并再次发布我的代码。