如何从未填充(猫鼬)的架构中删除引用的ID?

时间:2020-05-14 14:48:15

标签: mongodb mongoose

假设我有一个看起来像这样的父母模式和孩子模式:

parent{
       parent_id: .... ,
       name: {type: string} 
       child: { type: Schema.Types.ObjectId, 
                ref: 'Child'}
}
child{
     child_id:...
     name: {type:string}
}

现在我删除child_id = X的child。

但是我的父母模式中仍然有child_id = X的引用。

问:是否可以删除所有未填充的引用?

编辑:父母有1个以上的孩子,例如:

parent{
   parent_id: .... ,
   name: {type: string} 
   child: [{ type: Schema.Types.ObjectId, 
            ref: 'Child'}]
}

1 个答案:

答案 0 :(得分:0)

如果孩子的父母更多,请从子集合中删除该记录后,从父集合中取消该子项的设置,如下查询所示

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

如果父级数组中有多个子级,则使用以下查询

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

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