javascript - 如何在猫鼬中删除带有参考集合的集合?
问题描述
我有这个用户模型,它有博客模型作为参考,博客有评论集合作为参考
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"
});
我也想删除博客数据以及博客集合中的任何嵌套集合我该如何删除它?
解决方案
如果我说得对,这将有所帮助。
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
我找不到类似的东西。
推荐阅读
- c++ - 矩阵类的数组式初始化
- sql-server - MSSQL从不同vpn后面的不同服务器插入表
- scala - 以老式方式使用 Akka HTTP
- scala - 使用 grpc netty 运行 kmsClient 解密后,Google KMS 冻结
- python - 用布朗路径求解 PDE 的扩展 FFT
- python - 如何保存pytorch模型列表
- javascript - 如何在反应js中有条件地呈现错误?
- java - Android中如何使用ArrayDeque给RecyclerView设置数据
- c++ - 模板默认参数中的 C++ 临时“需要”表达式使用 GCC 产生错误
- argparse - 无法获取 URL https://pypi.org/simple/argparse/