gpt4 book ai didi

node.js - 为什么 Mongoose 验证器不验证字段类型?

转载 作者:行者123 更新时间:2023-12-04 10:12:04 26 4
gpt4 key购买 nike

我正在尝试验证 Mongoose 模式,但我无法理解类型验证的一件事。我将数字类型传递给字符串字段,并希望它在验证中失败,但它通过了。这是怎么发生的,谁能解释一下这背后的逻辑?
示例.js

const mongoose = require('mongoose');

async function validateSample(sample) {
try {
await sample.validate();
return true;
} catch (error) {
return false;
}
}

async function execMethod(){
var userSchema = new mongoose.Schema({
phone: {
type: String,
minlength: 2,
maxlength: 4,
validate: {
validator: function(v) {
return /^\d+$/.test(v);
},
message: `not a valid phone number!`
},
required: [true, 'User phone number required']
}
});

var User = mongoose.model('user', userSchema);
var validUser = new User({phone: '1234'});
var invalidUser = new User({phone: 1235});
const result = await validateSample(validUser);
const result1 = await validateSample(invalidUser);
console.log(result); // true
console.log(result1) // expected false as number type is assigned to phone. But returns true, why?
}

execMethod()


最佳答案

那实际上是 a feature Mongoose 验证。

Before running validators, Mongoose attempts to coerce values to the correct type. This process is called casting the document. If casting fails for a given path, the error.errors object will contain a CastError object.

Casting runs before validation, and validation does not run if casting fails.



在这种情况下,一个数字 1235被转换为字符串 '1235' ,通过验证就好了。

现在,有 a FR open为 Mongoose 提供覆盖转换逻辑的能力(完全禁用它或自定义),但它是开放的,未实现。

另一种方法是改变类型范围内的类型转换( allowed since 5.4 ),如下所示:
mongoose.Schema.Types.String.cast(false); // prevents all casts to string

...但它可能很麻烦,因为相同的规则适用于所有对象。

关于node.js - 为什么 Mongoose 验证器不验证字段类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61287026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com