如何从Mongo Shell中添加模式验证以要求MongoDB中的字符串数组?

时间:2018-11-08 21:49:40

标签: mongodb

一旦完成,我打算在我的Collection上的Mongo Shell中运行以下命令。但是,我无法弄清楚如何处理所需属性列表中的最后一项,因为它是唯一一个数组。具体来说,它是一个字符串数组。这是最后一项,imageIDs属性。我放了enum,但我认为这是不对的。如何要求其类型为字符串数组?

    db.runCommand( {
   collMod: "CustomerOrders",
   validator: { $jsonSchema: {
      bsonType: "object",
      required: [ "dateTime", "restaurantName", "restaurantCity", "restaurantCountry", "contactName", "contactPhone", "contactEmail", "menuSize", "pricePaid", "currentLanguage", "targetLanguage", "imageIDs" ],
      properties: {
         dateTime: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         restaurantName: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         restaurantCity: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         restaurantCountry: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         contactName: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         contactPhone: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         contactEmail: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         menuSize: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         pricePaid: {
            bsonType: "double",
            description: "must be a string and is required"
         },
         currentLanguage: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         targetLanguage: {
            bsonType: "string",
            description: "must be a string and is required"
         },
         imageIDs: {
            bsonType: "enum",
            description: "can only be one of the enum values and is required"
         }
      }
   } },
   validationLevel: "strict"
} )

1 个答案:

答案 0 :(得分:0)

对于imageIDs(需要为字符串数组的属性),我使用以下规范更改了架构:

 imageIDs: {
    bsonType: "array",
    description: "must be an array and is required",
    minItems: 1,
    maxItems: 25,
    items: {
       bsonType: "string",
    }
 }

老实说,MongoDB文档有点累人,并且在示例中严重缺乏。 JSON模式属性上的This page有帮助。我通过反复试验弄清楚了这一点,看看什么才被拒绝,直到我知道自己的正确才知道什么才被拒绝。