我已将此行添加到我的模式中...
recentTags: {type:[String], default: [], validate: tagRegex}
这是我的标签验证正则表达式...
tagRegex: /^[a-z0-9#]+( *[a-z0-9\\/:\-()[\].?#]+)*$/
注意:它不允许使用空字符串,也不允许使用空字符串,因为这不是有效的标签名称。
所以我的问题是,所有接触该架构的测试现在都因Mongo错误而失败...
ValidationError: User validation failed: recentTags: Validator failed for path `recentTags` with value ``
我不明白为什么它要尝试运行我的验证器,为什么在值数组为空时会这样做呢?为什么要传递一个空字符串?
请注意,在运行测试之前,我一直很小心地重建我的测试数据库,并等待所有索引完成,其余测试工作正常。我的Mongo版本是3.6.8,我的Mongoose版本是^ 5.9.25,所有版本都在节点v14.11.0上运行
我相信验证器会将正则表达式作为一个整体应用于整个字符串数组,并且在应用正则表达式时将隐式类型转换为字符串。空数组将隐式转换为空字符串""
。
根据我的理解,您似乎正在验证数组中的每个单独元素,而不是整个数组值。数组类型可以使用元素级验证器更复杂地指定。
这是更改的示例:
const Tags = model("tags", new Schema(
{
recentTags: {
type: [{
type: String,
validate: tagRegex,
}],
default: [],
},
},
));
以下是一些带有此验证的插入示例:
// valid, uses the default value
await Tags.insertMany([{}]);
// also valid, no elements are here so no validation is done
await Tags.insertMany([{recentTags: []}])
// also valid, the element passes the regex
await Tags.insertMany([{recentTags: ["test"]}])
// not valid, the element does not pass the regex
await Tags.insertMany([{recentTags: [""]}])
请参阅有关数组架构类型的文档:https : //mongoosejs.com/docs/schematypes.html
您可能还希望验证recentTags
实际上是一个数组,或者使用更复杂的自定义验证错误消息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句