Mongoose 接受数字字段的空值

Dus*_*gal 4 mongoose node.js mongoose-schema

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

port:{
    type:Number,
    default:1234
}
Run Code Online (Sandbox Code Playgroud)

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

不应该是隐蔽null1234吗?null不是数字!我理解错了吗?

我正在考虑这里给出的解决方案,但我不想为没有它应该可以工作的东西添加额外的代码(除非我错了并且它不应该转换null1234

rsp*_*rsp 5

见本期评论:

null 是 Date 属性的有效值,除非您指定为 required。仅当值未定义时才设置默认值,如果它是假的,则不会设置。

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

您的选择是:

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

您可能会像这样使用 pre-save 或 post-validate(或其他一些)钩子:

YourCollection.pre('save', function (next) {
  if (this.port === null) {
    this.port = undefined;
  }
  next();
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

这是不幸的是,猫鼬不能被配置为胎面nullundefined(有一些“不空”的参数或类似的东西),因为它是有时的情况下,你的数据的工作,你作为JSON的请求得到它有时可以转换undefined到空值:

> JSON.parse(JSON.stringify([ undefined ]));
[ null ]
Run Code Online (Sandbox Code Playgroud)

甚至null在没有(显式)的地方添加值undefined

> JSON.parse(JSON.stringify([ 1,,2 ]));
[ 1, null, 2 ]
Run Code Online (Sandbox Code Playgroud)