简体   繁体   English

从NodeJS ExpressJS中的req.body中删除变量

[英]To delete a variable from req.body in NodeJS ExpressJS

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. 我收到了包含大量信息的JSON,但是我想删除特定的数据,例如,如果收到变量名,则想在将JSON添加到数据库中之前删除此变量。 This is my function POST: 这是我的功能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);
    });
});
delete req.body.name

should work in a javascript object 应该在javascript对象中工作

check How do I remove a property from a JavaScript object? 检查如何从JavaScript对象中删除属性?

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. 否则,客户可以发送任何想要的内容,包括以$开头的字段,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: 您还可以使用Underscore.js来完成这项工作:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM