ajv-bsontype

添加 mongodb 的 bsonType 格式验证器

英文原地址

安装

npm install ajv-bsontype --save
1

设置

var Ajv = require('ajv');
var ajv = new Ajv;
require('ajv-bsontype')(ajv);
1
2
3

使用

const schema = {
   required: [ "name", "year", "major", "gpa" ],
   properties: {
      name: {
         bsonType: "string",
         description: "must be a string and is required"
      },
      gender: {
         bsonType: "string",
         description: "must be a string and is not required"
      },
      year: {
         bsonType: "int",
         description: "must be an integer in [ 2017, 3017 ] and is required"
      },
      major: {
         enum: [ "Math", "English", "Computer Science", "History", null ],
         description: "can only be one of the enum values and is required"
      },
      gpa: {
         bsonType: [ "double" ],
         description: "must be a double and is required"
      }
   }
}

const data = {
   name: "Alice",
   year: 2019,
   major: "History",
   gpa: 3
}

ajv.validate(schema, data)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34