关于删除的引用完整性,如果所有删除请求均由您的应用程序提供服务,则可以通过在删除记录之前检查相关集合中不存在 ID 来处理。我这样做如下
CRUD 操作(我们在这里只关心删除 - 请注意我如何传递一个对象数组,这些对象是需要与我们要删除的文档(记录)的 ID 进行匹配的集合和字段
const express = require('express')
const router = express.Router()
const iflexCRUD = require('../../lib/iflexCRUD')
const { UnitType } = require('../../models/Unittype')
const { Unit } = require('../../models/Unit')
iflexCRUD.create(router, '/', UnitType)
iflexCRUD.read(router, '/', UnitType, { sort: 'name' })
iflexCRUD.update(router, '/:id', UnitType)
iflexCRUD.deleteByID(router, '/:id', UnitType, [
{
model: Unit,
field: 'unittype'
}
])
iflexCRUD.delete(router, '/unittype/:unittype', UnitType)
module.exports = router
CRUD 删除处理程序
这是我用于 CRUD 操作的通用删除请求处理程序
我传递一个集合/字段值数组,并检查是否有一条记录与要删除的文档的 ID 相匹配。
// CRUD-DELETE
iflexCRUD.deleteByID = (router, route, Collection, refs = []) => {
router.delete(route, async (req, res) => {
try {
let exception = false
//Enforce Referential Integrity for deletes - Deny when ID is used in any of refs collections
//Loop through any referenced files (first record) to ensure there are no other collections using this document
for (let i = 0; i < refs.length; i++) {
if (!exception) {
let refObj = {}
refObj[refs[0].field] = req.params.id
const result = await refs[i].model.findOne(refObj, (err, rec) => {})
exception = result !== null
}
}
// Process deletion of there are no exceptions
if (!exception) {
const doc = await Collection.deleteOne({ _id: req.params.id })
res.send(doc)
} else {
return res
.status(401)
.json(
'Document is already use in related collection - it cannot Delete!'
)
}
} catch (e) {
return res.status(401).json(e.message)
}
})
}