【发布时间】:2020-08-03 11:12:51
【问题描述】:
我有一个 Mongoose 架构,它的属性是 ObjectId 子文档的数组。
如果需要删除/删除其中一个子文档,我当然想从父的数组属性中删除它。
我的问题是:我按什么顺序对子项执行删除/删除操作,对父项执行 findOneAndUpdate 操作?
我问的原因是,如果我先成功删除/删除子项,但随后从父项的数组属性中删除 ObjectId 时出错,则子项似乎仍存在于父项下。
但是,如果我先从父级删除 ObjectId,然后在删除/删除子级时遇到问题,我认为没有办法在删除 ObjectId 之前将父级恢复为如果我能帮上忙,我宁愿不要有孤立的文件。
我在这一点上想出的东西感觉很“骇人听闻”,并且可能反过来产生自己的错误:
async deleteForm(req,res,next) {
let currentLocation;
try {
//Remove the reference to the Form from the 'forms' array in the parent 'Location'
try {
currentLocation = await Location.findOneAndUpdate(
{
forms: mongoose.types.ObjectId(req.params.formId)
},
{
$pull: {forms: req.params.formId}
}
);
} catch (err) {
console.error(err)
throw new Error('Error removing Form from Location')
}
//Actually find and remove the 'Form' itself
try {
await Form.findByIdAndRemove(req.params.formId);
} catch (err) {
console.error(err);
/* If the 'Form' can't be removed, re-add the reference to the form back into the
parent 'Location's 'forms' array*/
await currentLocation.update({
$push: {forms: mongoose.types.ObjectId(req.params.formId)}
})
throw new Error('Error deleting Form')
}
} catch (err) {
req.session.error = err;
} finally {
res.redirect(`/locations/${currentLocation._id}`);
}
}
【问题讨论】:
标签: javascript node.js database mongoose