【问题标题】:Set required mongoose Schema type to null将所需的 mongoose Schema 类型设置为 null
【发布时间】:2019-01-19 17:51:10
【问题描述】:

我有一个注册流程,首页只要求输入电子邮件和密码。下一页询问国家、州(可选)和城市。

在我的 Mongoose 模型中,我将所有字段设置为 required,但国家、州和城市直到第二页才分配值,因此需要将它们分配给 null 或其他一些空或假值。

const User = mongoose.Schema({
  email: {
    type: String,
    required: true
  },
  password: {
    type: String
  },
  country: {
    type: String,
    required: true,
  },
  state: {
    type: String,
    default: null,
    required: false,
  },
  city: {
    type: String,
    required: true,
  },
});

当需要为必填字段时,如何将 null 值分配给 Mongoose 中的 SchemaType?

【问题讨论】:

    标签: mongoose schema


    【解决方案1】:

    As per the docs required 可以是布尔值或应该返回布尔值的函数。长话短说,您可以创建一个函数来检查值是字符串还是 null 并返回 true。

    例子:

    const User = mongoose.Schema({
      email: {
        type: String,
        required: true
      },
      country: {
        type: String,
        required: function() {
          return typeof this.country === 'undefined' || (this.country != null && typeof this.country != 'string')
        }
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-01
      • 2013-07-29
      • 2019-07-03
      • 2018-05-04
      • 2021-06-19
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多