简体   繁体   中英

How to validate list in mongodb schema?

I'm creating HOME collection validation where I have rooms type(double, single, ensuite) and validation should allow adding all items listed.

"rooms.type": {bsonType: ["ensuite", "double", "single"]},

This is what I have in the validator

db.createCollection("home", { 
validator : {
    $jsonSchema : {
    bsonType: "object",
    required: ["address.line1", "address.town", "rooms.type", 
    "rooms.qty", "rooms.price"],
 properties: {
    "address.line1": {bsonType: "string"},
    "address.town": {bsonType: "string"},
    "rooms.type": {bsonType: ["ensuite", "double", "single"]},
    "rooms.qty": {bsonType: "int", minimum: 0},
    "rooms.price": {bsonType: ["double"], minimum: 0},
}}}})

I'm getting an error that

"ok" : 0,
"errmsg" : "Unknown type name alias: ensuite",
"code" : 2,
"codeName" : "BadValue"

I expect array room.type to allow one or all attributes in the group specified in the schema.

You can specify that the type of rooms.type should be "array", with minimum 1 item in the array, and that each item of that array should be an enum as follows:

"rooms.type": {
    type: "array",
    minItems: 1,
    items: {
        enum: ["ensuite", "double", "single"]
    }
}

MongoDB has documentation on $jsonSchema but you can find a bit more detail in the JSON Schema validation spec linked to from the MongoDB documentation.

You can also specify the schema this way:

db.createCollection('home', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['address', 'rooms'],
      properties: {
        address: {
          bsonType: 'object',
          additionalProperties: false,
          required: ['line1', 'town'],
          properties: {
            line1: {
              bsonType: 'string'
            },
            town: {
              bsonType: 'string'
            }
          }
        },
        rooms: {
          bsonType: 'object',
          additionalProperties: false,
          required: ['type', 'qty', 'price'],
          properties: {
            type: {
              bsonType: 'string',
              enum: ["ensuite", "double", "single"]
            },
            qty: {
              bsonType: 'int',
              minimum: 0
            },
            price: {
              bsonType: 'array',
              items: {
                bsonType: 'double',
                minimum: 0
              }
            }
          }
        }
      }
    }
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM