0

I am building REST API using node, express and MongoDB(using mongoose) i want to add validation to post requests how can I do that I have defined schema like this

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);
        });
};

but I want to add validation to the post request. I have to make sure that fields that are defined in a database are there in a request and values must be required as well I am really confused how to validate key in a JSON object inside request body. I have already added some validation using mongoose.

3 Answers 3

1

You can use Middlewares for this purpose like (If you are using express framework) :

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();
    }
});

Note : This middleware will be executed for all of your requests (If added before all the routes registration).

For more please refer : http://expressjs.com/en/guide/using-middleware.html

Sign up to request clarification or add additional context in comments.

3 Comments

i know middlewares are to defined but how
Have you tried the above code with specified note ?
i just need answer to some_function_to_validate(req) req with json how shall i do that
0

Try following code to get the valid fields. It will return false if any field i.e. not required is coming with the req. Hope this will help.

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
      }
};

1 Comment

why shall i run loop; there must be other optimized way
0

My answer seems to be too late, but hopefully it will help others in future. I think you can try express-validator, here is an article explains how to use it in detail. Its basic idea is to add a middleware, and put all the validations inside, which can be invoked in subsequent route functions. This way can keep the business logic code clean.

below is an example from 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));
});

1 Comment

on top of the reference to the article, can you share code of how it will help solve the questioner's problem... that will make it a high quality answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.