Mongoose对Number字段接受null

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mongoose对Number字段接受null相关的知识,希望对你有一定的参考价值。

我有一个mongoose架构,我正在存储一个端口号。我也为该字段设置了默认值。

port:{
    type:Number,
    default:1234
}

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

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

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

答案

请参阅此问题中的评论:

除非您指定required,否则null是Date属性的有效值。如果值未定义,则仅设置默认值,而不是如果其值为false。

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

您可以选择:

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

您可能会使用这样的预保存或后验证(或其他)钩子:

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(带有一些“not-null”参数或类似的东西),因为有时你会使用JSON中的数据来处理它,有时它可以将undefined转换为null:

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

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

> JSON.parse(JSON.stringify([ 1,,2 ]));
[ 1, null, 2 ]
另一答案

正如在mongoose官方文档here中所解释的那样

Number要将路径声明为数字,可以使用Number全局构造函数或字符串'Number'。

const schema1 = new Schema({ age: Number }); // age will be cast to a Number
const schema2 = new Schema({ age: 'Number' }); // Equivalent
const Car = mongoose.model('Car', schema2);
There are several types of values that will be successfully cast to a Number.
new Car({ age: '15' }).age; // 15 as a Number
new Car({ age: true }).age; // 1 as a Number
new Car({ age: false }).age; // 0 as a Number
new Car({ age: { valueOf: () => 83 } }).age; // 83 as a Number

如果传递一个带有返回Number的valueOf()函数的对象,Mongoose将调用它并将返回的值赋给路径。

不会强制转换值null和undefined。

NaN,强制转换为NaN的数组,数组和没有valueOf()函数的对象都将导致CastError。

以上是关于Mongoose对Number字段接受null的主要内容,如果未能解决你的问题,请参考以下文章

如果字段设置为 null,则恢复为 mongoose 中的默认值

Mongoose 选择子文档字段

Mongoose 校验参数

Mongoose:唯一字段,如果它不为 null 或空字符串 [重复]

Mongodb - 猫鼬,通过对两个字段求和进行排序

Mongoose:填充填充字段