有一种方法可以在MongoDB中强制执行参照完整性 [英] There is a way to enforce referential integrity in MongoDB

查看:109
本文介绍了有一种方法可以在MongoDB中强制执行参照完整性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您搜索与Mongo-DB相关的引用完整性时,标准响应为"MongoDB不支持此功能".标准解释是MongoDB支持引用和填充,但是没有什么可以阻止您将引用更改为无效值.对于许多来自SQL背景的开发人员来说,这是一个主要的威慑力量.

When you search for referential integrity in relation to Mongo-DB the standard response is "MongoDB does not support this". The standard explanation is that MongoDB supports refs and populate, however there is nothing that prevents you changing the ref to an invalid value. This is a major deterrent for many developers coming from a SQL background.

推荐答案

关于删除的引用完整性,如果所有删除请求均由您的应用程序提供,则可以通过在相关集合之前检查ID是否存在来进行处理.删除记录.我这样做如下

In relation to referential integrity on deletes, provided all delete requests are served by your application then it can be handled by checking ID does not exists in related collections prior to deleting records. I do this as follows

CRUD操作(这里我们仅关注Delete-请注意我如何传递对象数组,这些对象是需要与我们要删除的文档ID(记录)相匹配的集合和字段

CRUD Operations (We are only concerned with Delete here - note how I am passing an array of objects being the collection and field that needs to be matched against ID of document (record) we are deleting

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 Handler This is a generic delete request handler that I use for CRUD operations I passes an array of Collection / Field values and checks to see if there is a single record that matches the ID of the document being deleted.

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

这篇关于有一种方法可以在MongoDB中强制执行参照完整性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆