Express-validator不想在数据库中找到任何重复项

时间:2019-04-23 17:50:31

标签: node.js express express-validator

我正在使用Express-Validator来验证前面表格中的字段,但是exists()功能不起作用。

我还有另一种表单(注册表单),我正在使用EV(Express-Validator),在这种情况下,一切都很好,我对第二种表单也做同样的事情,这里的验证不起作用。

game.js(路由)

const app = require('express')();
const gameController = require('../controllers/gameController');
const { check } = require('express-validator/check');

module.exports = () => {
  app.post('/add', [
    check('title').exists().withMessage('The PBF Game with this title is actually in database'),
    check('link').exists().withMessage('The PBF Game with this website link is actually in database')
  ], gameController.addGame);

  return app;
}

gameController.js

const db = require('../models');
const { validationResult } = require('express-validator/check');

const validation = {
  size: 40960,
  type: 'image/png'
}

const path = 'uploads/';

module.exports = {
  addGame(req, res, next) {
    const { title, link, description } = req.body;
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
      return res.status(400).json({ status: res.statusCode, message: errors.array() });
    } else if (req.files.icon.size > validation.size) {
      return res.status(400).json({ status: res.statusCode, message: [{ 'msg': 'Your file has more than 50KB!' }] });
    } else if (req.files.icon.mimetype !== validation.type) {
      return res.status(400).json({ status: res.statusCode, message: [{ 'msg': 'You can upload only PNG files!' }] });
    } else {
      let file = req.files.icon;

      file.mv(path + new Date().getTime() + '-' + file.name, err => {
        if (err) {
          return res.status(400).json({ message: [{ 'msg': err }] });
        }

        db.game.create({ title: title, link: link, icon: path + file.name, description: description, flag: false });
        return res.status(200).json({ status: res.statusCode, message: 'The game has been added for verification. It should briefly appear in the selection field in the profile. If not, it means that the administrator has not approved the request.' });
      });
    }
  }
}

Express-Validator不会检查数据库中是否存在值,并将空数组传递给我正在检查文件并尝试返回正确响应的控制器。用户获得成功响应(如果文件正确),但是我的服务器控制台显示有关“验证错误”的红色警报,并且数据库中没有值,但是我之前说过,用户获得了成功响应。问题出在哪里?

1 个答案:

答案 0 :(得分:2)

Express验证器只能验证请求。它无法验证数据库中是否已存在值。为此,您需要查询数据库并检查。

例如,验证check('title').exists()将检查请求中是否存在title字段,而不是数据库中的字段。