我有这个用户模型 其中以博客模型为引用,博客以评论集合为引用
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
})
}
我希望这会有所帮助。如果您的问题类似于是否有任何函数可以自动删除文档及其所有引用的文档
,我找不到类似的内容。
关于javascript - 如何删除 Mongoose 中带有引用集合的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60338590/