Node.js MongoDB$jsonSchema验证的正确语法
我正在尝试做一些类似于此处所示示例的事情: 使用Node.js和标准MongoDB驱动程序(我没有使用Mongoose) 我尝试将validationAction更改为warm,将validationLevel更改为off,但即使如此,我仍然会收到相同的错误。 我假设我把语法搞砸了,下面是我的代码Node.js MongoDB$jsonSchema验证的正确语法,node.js,mongodb,Node.js,Mongodb,我正在尝试做一些类似于此处所示示例的事情: 使用Node.js和标准MongoDB驱动程序(我没有使用Mongoose) 我尝试将validationAction更改为warm,将validationLevel更改为off,但即使如此,我仍然会收到相同的错误。 我假设我把语法搞砸了,下面是我的代码 // Database Name const dbName = 'testproject'; // Connection URL const url = `mongodb://localhos
// 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)]: {} }
我投票取消删除之前删除的答案的想法是正确的,但遗漏了一个小细节,即“年”被作为浮点(JS!)插入,但您的模式要求它是int。如果@Rashomon将取消删除答案,我可以对其进行评论或编辑,只需稍加更正。