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

Express-validator doesn't want find any duplicates in database

我正在使用 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 不检查值是否存在于数据库中并将空数组传递给我正在检查文件并尝试 return 正确响应的控制器。用户获得成功响应(如果文件正确)但我的服务器控制台显示关于 'validation error' 的红色警报并且没有任何值被放入数据库,但正如我之前所说,用户获得成功响应。问题出在哪里?

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

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