Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

javascript - 当删除父级时,猫鼬删除子级文档引用(Mongoose delete Child Document references when parent gets deleted)

Hi all thanks for looking to my question, I would like to delete a child referenced in a parent here is the structure:

(大家好,感谢您关注我的问题,我想删除在父级中引用的子级,其结构如下:)

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

the child is saved to its own child collection and the parent contains its reference.

(子级将保存到其自己的子级集合中,父级将包含其引用。)

my approach for this is as follow:

(我的方法如下:)

 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) } } 

this works just fine, i wanted to know if this is the best approach.

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

  ask by Goncalo Santos translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't think if mongoose has this feature built-in.

(我不认为猫鼬是否内置此功能。)

The best you can do is to create a remove middleware as described here :

(你能做的最好的是创建一个删除中间件作为描述在这里 :)

By the way, to make your existing code shorter, you can use findByIdAndDelete .

(顺便说一句,为了使现有代码更短,可以使用findByIdAndDelete 。)

It returns the deleted document, so with the following code 2 database hits make the job:

(它返回已删除的文档,因此使用以下代码2命中数据库即可完成工作:)

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

    console.log(parentDel, childDel);

parentDel will look like this:

(parentDel将如下所示:)

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

And childDel will look like this:

(而且childDel将如下所示:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...