Как применить валидацию модели, имеющей ссылку? - PullRequest
0 голосов
/ 07 ноября 2019

Я хочу применить проверку к текущей схеме. Каким образом я могу выполнить проверку с помощью средства проверки и показать сообщение об ошибке, когда имя участника проекта не введено?

projectMembers: [{
        user: {
            type: Schema.Types.ObjectId,
            ref: 'User',
            required: true,
        },
        userRole: {
            type: Schema.Types.ObjectId,
            ref: 'UserRole',
            required: true,
        },
    }],

Модель пользователя

const userSchema = new Schema({
    username: {
        type: String,
        required: true,
        minlength: 3,
        validate: {
            validator: (username) => {
                return username.length >= 3
            },
            msg: () => {
                return 'UserName length less than 3 characters'
            }
        }
    },
    email: {
        type: String,
        required: true,
        unique: true,
        minlength: 7,
        validate: {
            validator: (email) => {
                return validator.isEmail(email)
            },
            msg: () => {
                return 'Enter a valid email'
            }
        }
    },
    password: {
        type: String,
        required: true,
        minlength: 8,
        validate: {
            validator: (password) => {
                return password.length >= 8
            }
        },
        msg: function () {
            return 'Enter atleast 8 charcters'
        }
    })

Модель UserRole

const UserRoleSchema = new Schema({
    userRole: {
        type: String,
        required: true,
        validate: {
            validator: (userRole) => {
                return userRole.length >= 0
            },
            msg: () => {
                return 'User Role should be selected'
            }
        }
    }
})

const UserRole = mongoose.model('UserRole', UserRoleSchema)
module.exports = UserRole       

1 Ответ

0 голосов
/ 07 ноября 2019

Позвольте 'сказать, что ваш projectMembers находится внутри модели с именем Project.

Вы можете установить требуемое сообщение об ошибке в схеме следующим образом:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const projectSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  projectMembers: [
    {
      user: {
        type: Schema.Types.ObjectId,
        ref: "User",
        required: [true, "User is required"]
      },
      userRole: {
        type: Schema.Types.ObjectId,
        ref: "UserRole",
        required: [true, "User Role is required"]
      }
    }
  ]
});

const Project = mongoose.model("Project", projectSchema);

module.exports = Project;

А в маршруте после проекта вы можете использоватьМетод mongoose doc.validateSync () для проверки.

Вот пример:

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

  const project = new Project({ name, projectMembers });

  const { errors } = project.validateSync();

  if (errors) {
    let convertedErrors = [];
    for (field in errors) {
      convertedErrors.push(errors[field].message);
    }

    return res.send({ errors: convertedErrors });
  }

  //todo: do whatever you want

  res.send();
});

Если вы отправляете запрос без роли пользователя на этот маршрут с этим телом:

{
 "name": "project name",
 "projectMembers": [{
    "user": "5dc12a0aa875cd0ca8b871ea"
 }] 
}

Вы получите этот ответ:

{
    "errors": [
        "User Role is required"
    ]
}

И если вы отправите запрос без роли пользователя и пользователя на этот маршрут с этим телом:

{
 "name": "project name",
 "projectMembers": [{}] 
}

Вы получите этоответ:

{
    "errors": [
        "User Role is required",
        "User is required"
    ]
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...