mongodb验证jsonschema +表达查询无法插入文档

时间:2018-10-12 01:23:09

标签: mongodb

所以这是一个分为两个部分的问题。我定义了以下验证模式:

db.createCollection(
  "users", {
    validator: {
      $or: [{
          company_name: {
            $exists: true,
            $type: "string"
          },
          type: {
            $in: [
              "creator"
            ],
            $exists: true,
            $type: "string"
          }
        },
        {
          firstname: {
            $exists: true,
            $type: "string",
          },
          lastname: {
            $exists: true,
            $type: "string",
          },
          type: {
            $in: [
              "user"
            ],
            $exists: true,
            $type: "string"
          }
        }
      ],
      $jsonSchema: {
        bsonType: "object",
        required: [
          "contacts",
          "created",
          "email",
          "password",
        ],
        properties: {
          "contacts": {
            bsonType: "array",
            items: {
              required: [
                "email",
                "name"
              ],
              properties: {
                "email": {
                  bsonType: "string",
                  description: "email of the other account"
                },
                "name": {
                  bsonType: "string",
                  description: "a way for the owner to easily identify"
                },
              }
            }
          },
          "created": {
            bsonType: "date",
            description: "the date this account was created"
          },
          "email": {
            bsonType: "string",
            description: "owner's registered email"
          },
          "password": {
            bsonType: "string",
            description: "a hashed password"
          },
          "reset_code": {
            bsonType: "string",
            description: "part of the getter link to reset password"
          },
        }
      }
    }
  }
)

并且我要插入:

db.users.insert({
    email: "sadf",
    password: "asdf",
    created: Date.now(),
    contacts: [],
    type: "user",
    firstname: "test",
    lastname: "test"
})

但这给了我“文档验证失败”`

1 个答案:

答案 0 :(得分:0)

事实证明是created格式为date的问题。我需要使用Date.now()new Date()

来代替new ISODate()