首页 > 解决方案 > MongoDB $jsonSchema 验证的正确语法

问题描述

我正在尝试执行与此处显示的示例类似的操作:https ://docs.mongodb.com/manual/reference/operator/query/jsonSchema/

使用 Node.js 和标准 MongoDB 驱动程序(我没有使用 Mongoose)。

我尝试将validationAction 更改为warm 并将validationLevel 更改为off,但即便如此我仍然会遇到相同的错误。我假设我用语法弄乱了一些东西,下面是我的代码



// Database Name
const dbName = 'testproject';

// Connection URL 
const url = `mongodb://localhost:27017/${dbName}`;


function createStudents(db) {
    db.createCollection("students", {
        validator: {
           $jsonSchema: {
              bsonType: "object",
              required: [ "name", "year", "major", "address.city", "address.street" ],
              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",
                    minimum: 2017,
                    maximum: 3017,
                    exclusiveMaximum: false,
                    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"
                 },
                 "address.city" : {
                    bsonType: "string",
                    description: "must be a string and is required"
                 },
                 "address.street" : {
                    bsonType: "string",
                    description: "must be a string and is required"
                 }
              }
           }
        }
     })
}

async function insertStudent(db){
  await db.collection('students').insertOne({
        name: "Alice",
        year: 2019,
        major: "History",
        address: {
           city: "NYC",
           street: "33rd Street"
        }
     }).catch(e => console.log(e))
}


// Use connect method to connect to the server
async function connect () {
    //Connect to the client
    const client = await MongoClient.connect(url, { useNewUrlParser: true }).catch(e => {throw new Error(400)})
    const db = client.db(dbName)
    //Create the students collection
    createStudents(db);
    //Insert a Student
    await insertStudent(db)
    const cursor = await db.collection('students').find({}).toArray();
    console.log(cursor)
}

connect();

光标始终为空,因此不会将任何文档添加到集合中。

我得到的错误如下:

    at Function.create (/Users/myuser/projects/Javascript/mongotest/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:43:12)
    at toError (/Users/myuser/projects/Javascript/mongotest/node_modules/mongodb/lib/utils.js:149:22)
    at coll.s.topology.insert (/Users/myuser/projects/Javascript/mongotest/node_modules/mongodb/lib/operations/collection_ops.js:848:39)
    at /Users/myuser/projects/Javascript/mongotest/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js:532:18
    at process._tickCallback (internal/process/next_tick.js:61:11)
  driver: true,
  name: 'MongoError',
  index: 0,
  code: 121,
  errmsg: 'Document failed validation',
  [Symbol(mongoErrorContextSymbol)]: {} }


标签: node.jsmongodb

解决方案


推荐阅读