假设我有一个JavaScript对象(data
),我想检查它是否符合我定义的特定Schema
,那么是否有一种方法可以在不将Schema转换为模型的情况下完成这个操作,即不需要创建一个填充了data
的模型实例并运行mymodel.validate()
呢?
我希望有一个Schema(definition).validate(data, callback)
函数,但据我所知,validate
函数是在Document
类中定义的。
Mongoose在2019年(v5.8.0)添加了这个功能,作为Model.validate(...):
您可以:
try {
await Model.validate({ name: 'Hafez', age: 26 });
} catch (err) {
err instanceof mongoose.Error.ValidationError; // true
}
您可以在Mongo端验证模式link
例如:
db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name" ],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
year: {
bsonType: "int",
minimum: 2017,
maximum: 3017,
description: "must be an integer in [ 2017, 3017 ] and is required"
}
}
}
}
})
一种方法是通过自定义验证器来执行。当验证失败时,无法将文档保存到数据库中。
或者另一种方法是使用MongoDB提供的validate()函数,该函数与您定义的模式相同。
model.create(data).validate()
对我来说似乎并不难,也可能是您最好的选择。为什么您想要另一种语法呢? - Andreas Hultgren