猫鼬是否可能需要至少一项财产?

时间:2019-09-11 15:34:51

标签: javascript node.js mongodb mongoose backend

我已经在Mongoose中创建了一个Schema模型,该模型具有多个属性,包括以下所示的属性。

所有这一切的问题在于,属性:名称,描述和国家(仅其中之一)是必需的,而不是全部三个。

这就是说,如果我对此模型进行PUT,并且不放置任何属性,则该模型无效,但是,如果放置其中一个,则该模型为(或者如果放置两个, ,甚至其中三个)。

但是,这里的要求无效,因为这意味着要添加三个属性。

我尝试使用了必需的,验证的或Mongoose的钩子,但没有一个起作用。

const example = new Schema({
  name: {
    type: String,
    required: true,
    unique: true
  },
  description: String,
  countries: {
    type: [
      {
        type: String,
      }
    ],

  },
  email: {
    type: String
  },
  sex: {
    type: String
  },
});

我希望随着需要,我将始终需要这三个属性

2 个答案:

答案 0 :(得分:0)

您可以使用custom function作为必需属性的值。

const example = new Schema({
  name: {
    type: String,
    required: function() {
      return !this.description || !this.countries
    },
    unique: true
  },
  description: String,
  countries: {
    type: [
      {
        type: String,
      }
    ],

  },
  email: {
    type: String
  },
  sex: {
    type: String
  },
});

答案 1 :(得分:0)

我怀疑是否有内置方法可以实现这种特定类型的验证。使用validate方法可以达到以下目的:

const example = new Schema({
  name: {
    type: String,
    unique: true,
    validate() {
      return this.name || this.countries && this.countries.length > 0 || this.description
    }
  },
  description: {
    type: String,
    validate() {
      return this.name || this.countries && this.countries.length > 0 || this.description
    }
  },
  countries: {
    type: [String],
    validate() {
      return this.name || this.countries && this.countries.length > 0 || this.description
    }
  }
});

将为您架构中的所有三个字段调用该字段,只要其中至少一个不为null,它们都将有效。如果所有三个都丢​​失,那么所有三个都将无效。您还可以对其进行调整,以适应您的一些更具体的需求。

请注意,这是因为validate方法的上下文(this的值)是引用模型实例的。

编辑:更好的是,使用所需的方法,该方法基本上以相同的方式工作,如另一个答案中指出的那样。