node.js - Mongoose:根据查询动态添加某些参数的验证器

标签 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 },
     country: { type: String }
});

为了进行简单的注册,我强制用户提供姓名、电子邮件和密码。上面的架构没问题。现在稍后我想强制用户给予城市和国家。 例如,是否可以根据需要使用参数城市和国家/地区更新用户的文档?我避免重复用户架构,如下所示:

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

最佳答案

在这种情况下,您需要做的是拥有一个架构,并使您的required成为一个允许nullString的函数:

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等。

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

Here is the doc 必需

关于node.js - Mongoose:根据查询动态添加某些参数的验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51863847/

相关文章:

node.js - npm glob 模式与子目录不匹配

node.js - Express/Node 应用程序的经过身份验证的登录架构

javascript - Node.js 无法使用 Promise、Mongoose 和 GET 请求推送到全局数组

node.js - 一个月 24 小时运行 Node js 代码

javascript - 如何知道函数是否异步?

javascript - 如何从多个不同的 html 页面获取 mongo db 文档的用户输入?

php - 通过php web服务将mongodb中的数据解析为android应用程序

MongoDB - 大量的 MongoCleaner 线程

arrays - 如何检查数组中的最后一个元素是否符合条件,mongodb

javascript - 如何连接 MongoDB 中两个集合的数据?