首页 > 解决方案 > 如何从未填充的模式(猫鼬)中删除引用的 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'}]
}

标签: mongodbmongoose

解决方案


如果一个孩子有多个父母,在从子集合中删除记录后,$unset 从父集合中的孩子,如下查询所示

Parent.updateMany(
   { child: child_id },
   { $unset: { child: "" } }
)

如果一个父母在一个数组中有多个孩子,那么使用下面的查询

Parent.updateMany(
   {  },
   { $pull: { child: child_id } }
)

如果需要,请记住 child_id 应该是 ObjectId(..) 格式


推荐阅读