gpt4 book ai didi

node.js - Mongoose 接受 Number 字段为 null

转载 作者:搜寻专家 更新时间:2023-11-01 00:37:53 29 4
gpt4 key购买 nike

我有一个 mongoose 模式,我在其中存储了一个端口号。我还为该字段设置了默认值。

port:{
type:Number,
default:1234
}

如果我没有通过我的 API 获得任何值,它将设置为 1234。但是,如果有人发送 null,它会接受 null 并保存到数据库。

它不应该将 null 转换为 1234 吗? null 不是数字!我理解错了吗?

我正在考虑给定的解决方案 here ,但我不想为没有它就应该工作的东西添加额外的代码(除非我错了并且它不应该将 null 转换为 1234)

最佳答案

查看本期评论:

null is a valid value for a Date property, unless you specify required. Defaults only get set if the value is undefined, not if its falsy.

(它是关于日期的,但它也可以应用于数字。)

您的选择是:

  • 在字段中添加required
  • 添加一个会拒绝它的自定义验证器
  • 使用钩子(Hook)/中间件解决问题

您可能会像这样使用预保存或验证后(或其他一些) Hook :

YourCollection.pre('save', function (next) {
if (this.port === null) {
this.port = undefined;
}
next();
});

但您可能必须使用类似的东西:

YourCollection.pre('save', function (next) {
if (this.port === null) {
this.port = 1234; // get it from the schema object instead of hardcoding
}
next();
});

有关如何使 null 在函数调用中触发默认值的一些技巧,另请参阅此答案:

不幸的是,Mongoose 无法配置为将 null 视为 undefined(带有一些“非空”参数或类似参数),因为有时是这种情况您处理在请求中作为 JSON 获得的数据,它有时可以将 undefined 转换为 null:

> JSON.parse(JSON.stringify([ undefined ]));
[ null ]

甚至在没有(明确的)undefined 的地方添加 null 值:

> JSON.parse(JSON.stringify([ 1,,2 ]));
[ 1, null, 2 ]

关于node.js - Mongoose 接受 Number 字段为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45208127/

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