【问题标题】:Mongoose validate length of array in schemaMongoose 验证模式中数组的长度
【发布时间】:2020-07-16 19:53:08
【问题描述】:

我想创建一个模式,其中包含活动参与者姓名的数组,我这样做是为了创建参与者列表:

  quizPart:[{
    type:String,
  }]

如何验证此数组的长度是否为零(此活动没有参与者)或 2,而不是 1(每个团队活动有两个人)。我想返回一条我可以用ValidationError处理的错误消息

我正在向此架构添加数据,如下所示:

var school = new School();
school.quizPart=req.body.quiz;

req.body.quiz = ["name1","name2"]['',''] 的位置

然后,如果只有 1 个字段具有字符串值,我想将错误解析到响应正文,如下所示:

    function handleValidationError(err, body) {
      for (field in err.errors) {
        switch (err.errors[field].path) {
          case "quizPart":
            body["quizPartError"] = err.errors[field].message;
            break; 
}}}

【问题讨论】:

  • 你可以在更新前写一个猫鼬钩子
  • @KunalMukherjee 我该怎么做?

标签: javascript mongodb mongoose mongodb-query mongoose-schema


【解决方案1】:

这是我的意思的一个工作示例。

编写pre('update') mongoose 钩子并检查$set 对象是否quizParts 字段的长度为0 或2。

index.js

const mongoose = require('mongoose');
const test = require('./test');

mongoose.connect('mongodb://localhost:27017/test2', {useNewUrlParser: true});
mongoose.set('debug',true);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
});

(async() => {
    try {
        const testUpdate = test();
        const updateQuery = {
            $set: {
                quizPart: [
                    {
                        type: 'Type 1'
                    },
                    {
                        type: 'Type 2'
                    }
                ]
            }
        };
        const updateResult = await testUpdate.update({}, updateQuery).exec();
    } catch(err) {
        console.error(err);    
    }
})();

test.js

const mongoose = require('mongoose');
const { Schema } = mongoose;

module.exports = function() {   
    const testSchema = new Schema({
        quizPart: [
            {
                type: String,
            }
        ]
    },
    {
        collection: 'test',
        timestamps: true
    });

    testSchema.pre('update', function(next) {
        const update = this._update.$set;

        if (update.length === 0 || update.length === 2) {
            return next();
        }
        else {
            return next(new Error('Cannot have length 1!'));
        }
    });
    
    return mongoose.model('test', testSchema);
};

【讨论】:

  • 您好,感谢您的帮助,但很抱歉,我无法真正理解您在这里所做的事情,因为我是 mongoose 的新手并且没有使用过您正在谈论的 $set 对象将我的quizParts 设置为一个值,我已经编辑了我的问题,以便您知道我的代码中发生了什么。
【解决方案2】:

成功了:

  quizPart:[{
    type:String,
  }],

然后通过以下方式验证字段:

schoolSchema.path('quizPart').validate((list)=>{
  alNumRegex= /^[a-z0-9]+$/i
  return list[0]!=="" && list[1]!=="" || alNumRegex.test(list[0]) && alNumRegex.test(list[1]);
},'Please Register atleast two participants for quiz.');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-31
    • 2013-11-13
    • 2019-05-17
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    相关资源
    最近更新 更多