【问题标题】:Boolean and Number in Schema (Mongoose)Schema 中的布尔值和数字 (Mongoose)
【发布时间】:2021-04-29 08:30:53
【问题描述】:

如何在架构中的值之一,布尔和数字两种数据类型?

【问题讨论】:

标签: javascript mongoose


【解决方案1】:

我认为您要问的是是否有一种方法可以拥有一个可以是 Number 或 Boolean 类型的字段。如果是这种情况,您可以使用自定义 SchemaType 来完成此操作(请参阅 https://mongoosejs.com/docs/customschematypes.html 上有关此主题的 mongoose 文档)。代码是这样的:

class BoolOrNumber extends mongoose.SchemaType {
  constructor(key, options) {
    super(key, options, 'BoolOrNumber');
  }

  // `cast()` takes a parameter that can be anything. You need to
  // validate the provided `val` and throw a `CastError` if you
  // can't convert it.
  cast(val) {
    let _val = Number(val);
    if (isNaN(_val) && val !== true && val !== false) {
      throw new Error('BoolOrNumber: ' + val + ' must be a number or boolean');
    }
    return _val;
  }
}

// Don't forget to add `BoolOrNumber` to the type registry
mongoose.Schema.Types.BoolOrNumber = BoolOrNumber;

【讨论】:

    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    相关资源
    最近更新 更多