我正在研究MongoDB (猫鼬)和NodeJS。我有个问题。我是makine一个RESTful API。我有用户模型(集合)和评论模型(集合)。用户创建注释,我将用户和用户的注释与用户的_id联系起来。当用户删除时,我想删除所有评论。我怎样才能用MongoDB制作这个?我在谷歌上搜索了两天,但是İ我找不到一个很好的来源,我看了İ手册文档,但是我什么也没找到。
请帮帮我。谢谢,祝你今天愉快..。
发布于 2018-06-12 09:50:39
MongoDB不支持集合之间的内置关系和事务。
要删除相关注释(我认为每个Comment中都有Comment字段):
db.comments.remove({userId: removedUserId})如果您有用户注释的in集合,那么:
db.comments.remove({id: {$in: collectionOfCommentIds}})猫鼬确实支持中器。但请注意
没有用于remove()的查询钩子,只有对文档的查询挂钩。
所以您可以定义remove钩子,以便与user.remove()一起使用。但对User.remove({_id: userId})来说不是
userSchema.post(`remove`, (user) => {
Comments.remove({userId: user._id})
})发布于 2022-02-03 10:38:26
如果使用父引用
userSchema.post('findOneAndDelete', async id => {
await Comments.deleteMany({ user: id });
});如果您使用的是子引用
userSchema.post("findOneAndDelete", async function (user) {
if (user.comments.length) {
const res = await Comment.deleteMany({ _id: { $in: user.comments } });
console.log(res);
}
});https://stackoverflow.com/questions/50814052
复制相似问题