Node.js Mongoose:根据查询动态添加一些参数的验证器

Node.js Mongoose:根据查询动态添加一些参数的验证器,node.js,mongodb,mongoose,mongoose-schema,Node.js,Mongodb,Mongoose,Mongoose Schema,我是Mongoose的新手,我想知道是否可以根据查询动态添加一些参数的验证器。例如,我有如下模式: var user = new Schema({ name: { type: String, required: true }, email: { type: String, required: true }, password: { type: String, required: true }, city: { type: String }, co

我是Mongoose的新手,我想知道是否可以根据查询动态添加一些参数的验证器。例如,我有如下模式:

var user = new Schema({
     name: { type: String, required: true },
     email: { type: String, required: true },
     password: { type: String, required: true },
     city: { type: String },
     country: { type: String }
});
对于一个简单的注册,我强制用户提供姓名、电子邮件和密码。上面的模式是正常的。现在,稍后我想强迫用户给出城市和国家例如,是否可以使用所需的参数city和country更新用户文档?我避免重复如下用户模式:

var userUpdate = new Schema({
     name: { type: String },
     email: { type: String },
     password: { type: String },
     city: { type: String, required: true },
     country: { type: String, required: true }
});

在这种情况下,您需要做的是使用一个模式,并使您的
required
成为一个允许
null
String
的函数:

var user = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  city: {
    type: String,
    required: function() {
      return typeof this.city === 'undefined' || (this.city != null && typeof this.city != 'string')
    }
  }
});
您可以将其提取出来,并将其作为外部函数,然后可以将其用于
country

这样做的目的是使该字段成为必填字段,但您也可以将其设置为
null
。通过这种方式,您可以在开始时将其设置为null,然后在以后将其设置为null


就我所知,这是不可能的

Mongoose架构是在集合上设置的,而不是在文档上设置的。 您可以有两个mongoose模型指向具有不同模式的同一集合,但实际上需要有重复的模式

就个人而言,在您的情况下,我将创建一个单独的类似于模式的自制数据结构和一个函数,当使用数据结构进行反馈时,该函数将创建两个版本的模式

举例来说:

const schemaStruct = {
    base : {
      name: { type: String, required: true },
      email: { type: String, required: true },
      password: { type: String, required: true },
      city: { type: String },
      country: { type: String }
    }
    addRequired : ["city", "country"]
}
function SchemaCreator(schemaStruct) {
     const user = new Schema(schemaStruct.base)

     const schemaCopy = Object.assign({}, schemaStruct.base)
     schemaStruct.addRequired.forEach(key => {
          schemaCopy[key].required = true;
     })
     const updateUser = new Schema(schemaCopy);
     return [user, updateUser];
}

谢谢你给我指出那个链接。我想我会这样做的。我会接受答案。谢谢你的回答。@Akrion的答案是我真正需要的(避免重复)。我将投票支持你的努力。