mongodb - 如何从未填充的模式(猫鼬)中删除引用的 ID?
问题描述
假设我有一个父模式和一个子模式,看起来像这样:
parent{
parent_id: .... ,
name: {type: string}
child: { type: Schema.Types.ObjectId,
ref: 'Child'}
}
child{
child_id:...
name: {type:string}
}
现在我用 child_id = X 删除孩子。
但是我的父母架构中仍然有 child_id = X 的引用。
问:有没有办法删除所有未填充的引用?
编辑:父母有超过1个孩子,所以喜欢:
parent{
parent_id: .... ,
name: {type: string}
child: [{ type: Schema.Types.ObjectId,
ref: 'Child'}]
}
解决方案
如果一个孩子有多个父母,在从子集合中删除记录后,$unset 从父集合中的孩子,如下查询所示
Parent.updateMany(
{ child: child_id },
{ $unset: { child: "" } }
)
如果一个父母在一个数组中有多个孩子,那么使用下面的查询
Parent.updateMany(
{ },
{ $pull: { child: child_id } }
)
如果需要,请记住 child_id 应该是 ObjectId(..) 格式
推荐阅读
- rust - `single_use_lifetimes` 在函数中派生的结构上意味着什么以及如何解决它?
- java - 确保网络调用仅在 recyclerview 行中的每个按钮执行一次(RxJava)
- docker - docker 中的临时共享卷
- shell - 如何为 psql 输出中存在的值 grep 一个 shell 变量?
- jenkins - 如何使用 java 以编程方式更新 jenkins 作业配置并触发构建?
- java - 在 Java 中形成邮件正文
- css - 如何为 material-ui 反应组件覆盖 @media css
- angular - 模板驱动表单预选下拉值角度 6
- android-studio - 模拟器:进程以退出代码 -1073740791 (0xC0000409) 结束
- html - 将文本与列表上的缩进保持一致