【问题标题】:Mongoose array object maxlength validation not working猫鼬数组对象最大长度验证不起作用
【发布时间】:2017-02-24 21:55:30
【问题描述】:

我有下面的架构,它允许我为现有应用创建一个徽章为“1234567”的用户。我预计会收到 maxlength 验证的验证错误 b/c。

我的架构有问题吗?

module.exports = function(db) {
    var mongoose = require('mongoose');

    var appSchema = mongoose.Schema({
        name: {
          type: String,
          required: true,
          unique: true,
        },
        settings: mongoose.Schema.Types.Mixed,
        user: [{
          badge: {
            type: String,
            minlength: 5,
            maxlength: 5
          }
        }]
    });

    // Export the schema for the app to use
    return db.model('apps', appSchema);
}

我正在尝试使用

apps.findByIdAndUpdate(req.params.id, {$push: {user: req.body.user}}, {runValidators: true},callback()); 

向应用文档中的数组添加新的用户记录。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    验证器只会work on updates for $set and $unset operations,所以我相信在这种情况下你必须在更新之前手动验证。

    【讨论】:

      【解决方案2】:

      来自文档,mongoose requires an Schema to validate nested objects

      所以你的架构应该这样定义。

      您可以尝试使用以下定义吗?

      var userSchema = mongoose.Schema({
          badge: {
            type: String,
            minlength: 5,
            maxlength: 5
          }
      });
      
      var appSchema = mongoose.Schema({
          name: {
            type: String,
            required: true,
            unique: true,
          },
          settings: mongoose.Schema.Types.Mixed,
          user: [userSchema]
      });
      

      【讨论】:

      • 似乎仍然不起作用。这就是我尝试将用户记录插入现有应用程序的方式:apps.findByIdAndUpdate(req.params.id, {$push: {user: req.body.user}}, {runValidators: true},callback());
      猜你喜欢
      • 1970-01-01
      • 2022-07-21
      • 2017-09-12
      • 2021-07-22
      • 2017-11-18
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 2018-06-23
      相关资源
      最近更新 更多