【问题标题】:Mongoose delete Child Document references when parent gets deleted删除父级时,猫鼬删除子文档引用
【发布时间】:2019-11-29 20:08:04
【问题描述】:

大家好,感谢您关注我的问题, 我想删除父项中引用的子项 这是结构:

const parentSchema: = new Schema({
  name: String,
  child: { type: mongoose.Schema.Types.ObjectId, ref:'Child' },
})

const childSchema: = new Schema({
  name: String,
})

子被保存到它自己的子集合中并且父包含它的引用。

我的方法如下:

parentSchema.statics.deleteByID = async function (id: string) {
  try {
    const parent = await this.findOne({ id })
    const child = await Child.findOne({_id: parent.child })

    const childDel = child && await child.remove()
    const parentDel = await parent.remove()
    
    console.log(parent, child, childDel, parentDel)

  } catch(err) {
    throw new Error(err)
  }
}

这很好用,我想知道这是否是最好的方法。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    我不认为 mongoose 是否内置了这个功能。

    您能做的最好的事情就是按照here 的描述创建一个删除中间件:

    顺便说一句,为了使您现有的代码更短,您可以使用findByIdAndDelete。它返回已删除的文档,因此使用以下代码 2 次数据库命中即可完成工作:

        const parentDel = await Parent.findByIdAndDelete(id);
        const childDel = await Child.deleteOne({_id: parentDel.child});
    
        console.log(parentDel, childDel);
    

    parentDel 将如下所示:

    {
        "_id": "5de0114ad068f335b480925a",
        "name": "Parent 1",
        "child": "5de01144d068f335b4809259",
        "__v": 0
    }
    

    childDel 看起来像这样:

    {
        "n": 1,
        "ok": 1,
        "deletedCount": 1
    }
    

    【讨论】:

    • 谢谢,我遇到了钩子不触发的问题,但问题是我希望钩子在类而不是实例上触发!
    【解决方案2】:

    我认为这是解决我的问题的最佳方法,希望它可以帮助任何人。 我的问题是认为 pre('remove') 钩子会在 Class 调用上触发,但它只在实例上调用。 所以不是Parent.deleteOne(),而是先用findOne()找到我要删除的实例,然后用parent.remove()触发pre('remove'),然后删除必要的子... 这是一个例子:

     parentSchema.pre<ParentDocument>('remove', async function() {
      try {
        if (this.child01) {
          await Child01.deleteOne({ _id: this.child01 })
        }
        if (this.child02) {
          await Child02.deleteOne({ _id: this.child02 })
        }
      } catch(err) {
        throw new Error(err)
      }
    })
    
    parentSchema.statics.deleteByID = async function (id: string) {
      try {
        const parent = await this.findOne({ id })
        return !!(parent && await parent.remove())
      } catch(err) {
        throw new Error(err)
      }
    }
     

    【讨论】:

      猜你喜欢
      • 2019-06-06
      • 2021-07-28
      • 2022-11-24
      • 2016-11-09
      • 2021-12-02
      • 2016-07-30
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多