如何在猫鼬中验证对象数组

我需要验证架构中的对象数组

Schema: 
user: [{
name: String,Age: String,Contact: Number
}]

如何验证姓名,年龄和联系方式。

youbaio 回答:如何在猫鼬中验证对象数组

我假设您的用户数组在另一个架构内。

假设我们有一个课程模型,其用户如下:

const mongoose = require("mongoose");

const courseSchema = new mongoose.Schema({
  name: {
    type: String,required: true
  },users: [
    {
      name: { type: String,required: [true,"Name is required"] },age: { type: Number,"Age is required"] },contact: { type: Number,"Contact is required"] }
    }
  ]
});

const Course = mongoose.model("Post",courseSchema);

module.exports = Course;

要在发布路线中对此进行验证,可以使用猫鼬模型validateSync方法:

const Course = require("../models/course");

router.post("/course",async (req,res) => {
  const { name,users } = req.body;

  const course = new Course({ name,users });

  const validationErrors = course.validateSync();

  if (validationErrors) {
    res.status(400).send(validationErrors.message);
  } else {
    const result = await course.save();
    res.send(result);
  }
});

当我们发送一个requset正文时,没有年龄和联系方式这样的必填字段:

(您还可以转换validationErrors.errors以获取更多有用的错误消息。)

{
    "name": "course 1","users": [{"name": "name 1"},{"name": "name 2","age": 22,"contact": 2222}]
}

结果将是这样的:

Post validation failed: users.0.contact: Contact is required,users.0.age: Age is required

,

这与通常的验证类似,但是在数组内部,您需要这样创建验证器函数:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

//the custom validation that will get applied to the features attribute.
var notEmpty = function(features){
    if(features.length === 0){return false}
    else {return true};
}

var CarSchema = new Schema({
    name: {
        type: String,required: true,},features: [{
        type: Schema.ObjectId,ref: Feature
        required: true; //this will prevent a Car model from being saved without a features array.
        validate: [notEmpty,'Please add at least one feature in the features array'] //this adds custom validation through the function check of notEmpty.
    }]
});

var FeatureSchema = new Schema({
    name: {
        type: String,required: true //this will prevent a Feature model from being saved without a name attribute.
    }
});

mongoose.model('Car',CarSchema);
mongoose.model('Feature',FeatureSchema);
,

使用密钥/属性类型:

var breakfastSchema = new Schema({
  eggs: {
    type: Number,min: [6,'Too few eggs'],max: 12
  },bacon: {
    type: Number,'Why no bacon?']
  },drink: {
    type: String,enum: ['Coffee','Tea'],required: function() {
      return this.bacon > 3;
    }
  }
});
本文链接:https://www.f2er.com/3161534.html

大家都在问