【问题标题】:validation of request parameters in nodejs against database fields根据数据库字段验证nodejs中的请求参数
【发布时间】:2016-09-25 08:19:24
【问题描述】:

我正在使用 node、express 和 MongoDB(使用 mongoose)构建 REST API 我想为发布请求添加验证我该怎么做我已经定义了这样的架构

var CategorySchema = new Schema({
    name: {
        type: String,
        lowercase: true,
        default: '',
        trim: true,
        unique: [true, 'Category name already exists'],
        required: [true, 'Category Name cannot be blank'],
        minlength: [4, 'Minimum 4 characters required'],
        maxlength: [20, 'Category name cannot be That long']
    },
    parentCategory: {
        type: String,
        lowercase: true,
        default: '',
        trim: true
    },
    description: {
        type: String,
        lowercase: true,
        default: '',
        trim: true,
        required: [true, 'description cannot be blank'],
        minlength: [10, 'Very short description']
    },
    slug: {
        type: String,
        lowercase: true,
        unique: [true, 'Slug must be unique'],
        required: true,
        minlength: [4, "Minimum 4 Charater required"],
        maxlength: [20, "Slug cannot be that long"]
    },
    imageUrl: {
        type: String,
        default: '',
        trim: true
    },
    created: {
        type: Date,
        default: Date.now
    },
    updated: {
        type: Date
    }
});

    module.exports = mongoose.model('Category', CategorySchema); 


i am insert data using mongoose models like this

exports.createCategory = function (request, response) {

    var newCategory = {
        "name": request.body.categoryName,
        "parentCategory": request.body.parentCategory,
        "description": request.body.description,
        "slug": request.body.slug,
        "imageUrl": request.body.categoryImage,
        "updated": new Date()
    }

    var category = new Category(newCategory);

    category.save()
        .then(function (category) {
            sendResponse(response, 201, "success", category);
        })
        .catch(function (error) {
            sendResponse(response, 400, "error", error);
        });
};

但我想为发布请求添加验证。我必须确保在请求中存在数据库中定义的字段,并且还必须需要值,我真的很困惑如何验证请求正文中 JSON 对象中的键。我已经使用猫鼬添加了一些验证。

【问题讨论】:

    标签: node.js mongodb validation express mongoose


    【解决方案1】:

    您可以为此目的使用中间件,例如(如果您使用的是 express 框架):

    app.use(function (req, res, next) {
        var validationErrors = [];
        validationErrors = some_function_to_validate(req); // Returns array
    
        if(validationErrors.length > 0) {
            // Send Custom Response with Validation Error
        }
        else {
            next();
        }
    });

    注意:此中间件将针对您的所有请求执行(如果在所有路由注册之前添加)。

    更多信息请参考:http://expressjs.com/en/guide/using-middleware.html

    【讨论】:

    • 我知道中间件是要定义的,但如何定义
    • 你有没有试过上面的代码和指定的注释?
    • 我只需要用 json 回答 some_function_to_validate(req) req 我该怎么做
    【解决方案2】:

    尝试以下代码获取有效字段。如果 req 附带任何字段,即不需要的字段,它将返回 false。希望这会有所帮助。

    function validateReq(req)
    {
      if(req)
        {
          var prop = ['name','parentCategory','description'] //Add more property name here
          var found = false;
          for(var key in req.body)
          {
            if (prop[key] && (prop[key] !== null))
            {
              found = true;
            }
            else
            {
              return false;
    
            }
          }
        }
      else
        
        {
          return false;
        }
      }
    
    exports.createCategory = function (request, response) {
    
      var valid = validateReq(request);
      alert(valid);
      if(valid){
        var newCategory = {
            "name": request.body.categoryName,
            "parentCategory": request.body.parentCategory,
            "description": request.body.description,
            "slug": request.body.slug,
            "imageUrl": request.body.categoryImage,
            "updated": new Date()
        }
    
        var category = new Category(newCategory);
    
        category.save()
            .then(function (category) {
                sendResponse(response, 201, "success", category);
            })
            .catch(function (error) {
                sendResponse(response, 400, "error", error);
            });
        }
      else
        {
          //Error handling code
          }
    };

    【讨论】:

    • 我为什么要运行循环;一定有其他优化方式
    【解决方案3】:

    我的回答似乎为时已晚,但希望它在未来对其他人有所帮助。我想你可以试试express-validator,这里有一个article 详细解释了如何使用它。 它的基本思想是添加一个中间件,把所有的验证都放在里面,可以在后续的路由函数中调用。这样可以保持业务逻辑代码干净。

    以下是来自official docs的示例

    // ...rest of the initial code omitted for simplicity.
    const { check, validationResult } = require('express-validator');
    
    app.post('/user', [
        // username must be an email
        check('username').isEmail(),
    
        // password must be at least 5 chars long
        check('password').isLength({ min: 5 })
    
        ], (req, res) => {
    
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(422).json({ errors: errors.array() });
        }
    
        User.create({
            username: req.body.username,
            password: req.body.password
        }).then(user => res.json(user));
    });
    

    【讨论】:

    • 在文章的参考之上,你能分享它如何帮助解决提问者问题的代码......这将使它成为一个高质量的答案
    猜你喜欢
    • 1970-01-01
    • 2021-03-11
    • 2017-05-26
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多