【问题标题】:How to define foreign keys on mongoDB如何在 mongoDB 上定义外键
【发布时间】:2020-06-16 04:35:20
【问题描述】:

我正在使用 $jsonSchema 进行 Mongo DB (4.2) 模式验证。我想使用 $jsonSchema 定义外键。是否可以? 这是我想要的一个例子。

收集客户 -> { customerid, customerName, customerAddress }

收款订单 -> { orderId, customerid, orderdate, orderdetail }

    db.createCollection("order", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "orderId", "customerId", "orderdate", "orderdetail" ],
         properties: {
            orderId: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            customerId: {
               bsonType: "string",
               description: "must be a string and is required"
               **can i define some link here that this customer ID should come from customer collection**
            },
            orderdate: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            orderdetail: {
               bsonType: "string",
               description: "must be a string and is required"
            }
         }
      }
   }
})

我想用 $jsonSchema 实现以下场景: 1)当我在订单集合中插入时,如果该客户集合中的客户不存在,则订单插入应该失败。 2)如果客户被删除,所有与其对应的订单也应该被删除。

有可能吗?

【问题讨论】:

标签: mongodb jsonschema json-schema-validator


【解决方案1】:

没有办法在$jsonSchema 中指定一个字段的值必须依赖于当前文档本身之外的任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    • 2019-04-22
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多