Mongoose用钩子删除集合

时间:2017-12-25 21:09:10

标签: node.js mongodb mongoose

我想使用MEAN堆栈创建一个项目,但我遇到了Mongoose钩子的问题。

我有这些模特:

const UserSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: String,
    email: String
});

const ArticleSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "users"
  },
  title: {
    type: String,
    required: true
  },
  content: {
    type: String,
    required: true
  },
  comments: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: "comments"
  }]
});

const CommentSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User"
  },
  title: {
    type: String,
    required: true
  },
  content: {
    type: String,
    required: true
  }
  });  

我已成功创建了用于删​​除有关删除用户的文章和评论的钩子:

UserSchema.post("remove", function(doc) {
  console.log("user remove");
  this.model("article")
  .remove({ author: doc._id })
  .then(data => {
    console.log("articles remove");
  })
  .catch(data => {
    console.log(err);
  });
  this.model("comments")
  .remove({ author: doc._id })
  .then(err => {
    console.log("comments remove");
  })
  .catch(err => {
    console.log(err);
  });
});

并删除了删除文章中的评论引用:

CommentSchema.post("remove", function(doc) {
  console.log("comment remove");
  this.model("article")
  .update(
    { comments: doc._id },
    { $pull: { comments: doc._id } },
    { multi: true }
  )
  .then(doc => {
    console.log(doc);
  })
  .catch(err => {
    console.log(err);
  });
});

我知道model.remove不会触发钩子,但我的问题在于如何触发文章中的钩子以及在删除用户或该文章时我必须做些什么才能删除现有注释。

我想提出一些可以帮助我完成项目的建议。

0 个答案:

没有答案