猫鼬验证架构中数组的长度

时间:2020-07-15 16:27:05

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

我想创建一个架构,为事件中的参与者的名称提供数组,为此,我创建了参与者列表:

  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; 
}}}

2 个答案:

答案 0 :(得分:0)

这是我要说的一个实际例子。

写一个pre('update')猫鼬钩子,并检查$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);
};

答案 1 :(得分:0)

填写该字段:

  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.');