Question

I have a NodeJS server running on Express. I am using MongoSkin to connect my web server to MongoDB. I have the following route:

var express = require('express');
var router = express.Router();

router.post('/add', function(req, res){
    var db = req.db;
    db.collection('products').insert(req.body, function(err){
        res.send(err);
    });
});

module.exports = router; 

The above creates an endpoint that will accept POST requests at http://domain.com/add. Right now, this endpoint will save any parameters included with an AJAX request. I have no control to limit what key / value pairs I want to save in my DB.

With PHP, you would have to explicitly look for parameters in your script to use them, ie:

$param1 = $.POST['param1'];
$param2 = $.POST['param2'];
$param3 = $.POST['param3'];  
// Do something with these values

How would I do this with NodeJS?

Was it helpful?

Solution

req.body is just an ordinary js object, so it should be exactly the same as PHP. Suppose your post request has the following values: param1=1,param2=2,param3=invalid. Then req.body will have the following form:

{
    param1: 1,
    param2: 2,
    param3: "invalid"    
}

So you just to create a new object with the values you want:

var allowed_params = {
    param1: req.body.param1, // Or if you prefer req.body["param1"]
    param2: req.body.param2
};
db.collection('products').insert(allowed_params, callback_func);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top