验证nodejs中的数据库字段中的请求参数

时间:2016-05-27 06:02:50

标签: node.js mongodb validation express mongoose

我正在使用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对象中验证密钥。我已经使用mongoose添加了一些验证。

3 个答案:

答案 0 :(得分:0)

您可以将中间件用于此目的(如果您使用的是快速框架):

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

答案 1 :(得分:0)

尝试使用以下代码获取有效字段。如果任何字段(即不需要的字段)随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
      }
};

答案 2 :(得分:0)

我的回答似乎为时已晚,但希望它将对以后的其他人有所帮助。我认为您可以尝试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));
});