Javascript Mongoose中是否可能至少需要一个属性?

Javascript Mongoose中是否可能至少需要一个属性?,javascript,node.js,mongodb,mongoose,backend,Javascript,Node.js,Mongodb,Mongoose,Backend,我在Mongoose中创建了一个模式模型,它有几个属性,包括如下所示 所有这些的问题在于属性:名称、描述和国家,只需要其中一个,而不是全部三个 也就是说,如果我对这个模型做了一个PUT,而我没有放置任何属性,那么这个模型是无效的,但是,如果我放置其中一个,那么这个模型是有效的(或者如果我放置两个,甚至三个) 但是,此处所需的参数无效,因为它意味着要添加三个属性 我试过使用required、validate或Mongoose自己的钩子,但都没有成功 const example = new Sche

我在Mongoose中创建了一个模式模型,它有几个属性,包括如下所示

所有这些的问题在于属性:名称、描述和国家,只需要其中一个,而不是全部三个

也就是说,如果我对这个模型做了一个PUT,而我没有放置任何属性,那么这个模型是无效的,但是,如果我放置其中一个,那么这个模型是有效的(或者如果我放置两个,甚至三个)

但是,此处所需的参数无效,因为它意味着要添加三个属性

我试过使用required、validate或Mongoose自己的钩子,但都没有成功

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

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

我希望对于required,我将始终需要三个属性

作为所需属性的值

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
  },
});


我怀疑是否存在实现这种特定类型验证的内置方法。下面是如何使用
验证
方法实现您想要的:

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
的值)引用了模型实例

编辑:更好的方法是使用所需的方法,其基本工作方式与另一个答案中指出的相同