首页 > 解决方案 > 如何在猫鼬中删除带有参考集合的集合?

问题描述

我有这个用户模型,它有博客模型作为参考,博客有评论集合作为参考

const userSchema = new Schema(
  {
    email: {
      type: String,
      required: true,
      index: {
        unique: true
      }
    },
    password: {
      type: String,
      required: true
    },
    name: {
      type: String,
      required: true
    },
    website: {
      type: String
    },
    bio: {
      type: String
    }
  },
  {
    timestamps: {
      createdAt: "created_at",
      updatedAt: "updated_at"
    }
  }
);

userSchema.virtual("blogs", {
  ref: "blogs",
  localField: "_id",
  foreignField: "author"
});

我也想删除博客数据以及博客集合中的任何嵌套集合我该如何删除它?

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


如果我说得对,这将有所帮助。

function deleteUserById(id){
    UserModel.findById(id, async (err, user) => {
        try{
            await deleteBlodById(user.blog._id);
            UserModel.findByIdAndRemove(id)
        }catch(e){
            throw e;
        }
    })
}
function deleteBlogById(id){
    BlogModel.findById(id, async (err, blog) => {
        // ... The pretty same thing like before, just delete 
    })
}

我希望这会有所帮助。如果你的问题是Is there any function that automatically remove document and all its referenced documents我找不到类似的东西。


推荐阅读