2

I receive a JSON with lot of information but I want to delete a particular data, for example, if I receive the variable name, I want to remove this variable before adding my JSON in my Database. This is my function POST:

app.post("/:coleccion", function (req, res, next) {
POST
    if(req.body.name)
            // Here I need delete "name" if I receive this variable <------
    req.collection.insert(req.body, {}, function (e, result) {
        if(e) return next(e);
        res.send(result);
    });
});
Manu
  • 652
  • 3
  • 11
  • 22

2 Answers2

11
delete req.body.name

should work in a javascript object

check How do I remove a property from a JavaScript object?

Community
  • 1
  • 1
5

I would urge you to only pick the properties that you actually want instead of just removing the ones you don't. Otherwise the client could send in anything it wanted, including fields starting with $ which will get special treatment by MongoDB.

This is the easiest way to do this:

var data = {
  email: req.body.email,
  age: req.body.age,
  gender: req.body.gender
}

req.collection.insert(data, ...)

You could also use Underscore.js to do the job:

var data = _.pick(req.body, 'email', 'age', 'gender')

req.collection.insert(data, ...)
Linus Unnebäck
  • 23,234
  • 15
  • 74
  • 89