代码之家  ›  专栏  ›  技术社区  ›  Francis Ngueukam

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

  •  1
  • Francis Ngueukam  · 技术社区  · 6 年前

    我对猫鼬很陌生,想知道是否有可能 根据查询动态添加一些参数的验证器 . 例如,我有如下模式:

    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 on required更新用户文档? 我避免复制如下用户架构:

    var userUpdate = new Schema({
         name: { type: String },
         email: { type: String },
         password: { type: String },
         city: { type: String, required: true },
         country: { type: String, required: true }
    });
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Akrion    6 年前

    在这种情况下,您需要做的是使用一个模式并使 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')
        }
      }
    });
    

    你可以提取这个并使它成为一个外部函数,然后你可以用来 county

    它的作用是使字段成为必需的,但也可以设置 为了它。通过这种方式,您可以让它在开始时为空,然后在以后设置它。

    Here is the doc 必修的 .

        2
  •  1
  •   Félix Brunet    6 年前

    据我所知,不,这是不可能的。

    您可以让两个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];
    }