【发布时间】: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