【问题标题】:Is it possible to set the MongoDb validator as such that undefined properties are not inserted?是否可以将 MongoDb 验证器设置为不插入未定义的属性?
【发布时间】:2020-02-03 21:04:48
【问题描述】:

我正在尝试使用 MongoDB 为我的 REST API 实现一个数据库,该数据库能够存储和检索具有特定字段的文档。

我可以轻松使用 mongoose,但我希望使用 MongoDB 的本地驱动程序,因为我想学习 MongoDB 而不是 mongoose。

    {
      "$jsonSchema": {
       "bsonType": "object",
       "required": [
          "name",
          "email"
        ],
        "properties": {
          "name": {
            "bsonType": "string"
          },
          "email": {
          "bsonType": "string"
          },
          "profileImagePath": {
            "bsonType": "string"
          },
          "blogs": {
            "bsonType": ["object"]
          }
        }
      }
    }

我希望只能插入诸如

之类的数据
   "name" : "john",
   "email" : "john@gmail.com"

或者

   "name" : "john",
   "email" : "john@gmail.com",
   "profileImagePath" : "somePath"

但不是

   "name" : "john",
   "email" : "john@gmail.com",
   "height" : "5'11"

由于没有在属性中指定高度。

【问题讨论】:

    标签: mongodb schema jsonschema


    【解决方案1】:

    所以我一直在浏览 MongoDB 的文档,可以通过更改 additionalProperties 属性的默认值来指定是否可以将其他属性插入到数据库中。

    文档说明

    如果为真,则允许附加字段。如果为假,则不是。如果指定了有效的 JSON Schema 对象,则必须根据该模式验证其他字段。

    默认为真。

    为避免插入任何其他属性,您只需像这样添加 additionalProperties 属性,

    {
      "$jsonSchema": {
       "bsonType": "object",
       "required": [
          "name",
          "email"
        ],
        "properties": {
          "name": {
            "bsonType": "string"
          },
          "email": {
          "bsonType": "string"
          },
          "profileImagePath": {
            "bsonType": "string"
          },
          "blogs": {
            "bsonType": ["object"]
          }
        },
        "additionalProperties": false
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 2016-11-28
      • 2018-08-14
      • 1970-01-01
      • 2010-09-28
      相关资源
      最近更新 更多