I am fairly new to express-js, so this question might seem silly, but been looking around and I can't find a elegant answer.
For a given route handling a post or put method, I want to be able to drop all of the properties not specified. For example if there is a post request to create an obj as:
{
title: "some title",
user: "some user",
body: "post body",
_id: "1332433242343",
}
I want to be able to have a middleware which only takes the properties that I need, such as:
(req, res, next) => {
const { title, user, body } = req.body;
clean_request = { title: title, user: user, body: body, };
}
The reason being that not malicious agent, could manipulate the internal database data, as the _id property is user by the database, and it can be set by the requester.
I am using express-validate to validate an sanitize my properties, but so far I have not found a way to be able to drop properties entirely and keep only the ones I need.
Thanks again, for any advice. ^^
at then end of the day I ended up writting my own middle ware for droppping unwanter properties in a the req body:
allowed_properties = {
username: true,
lastname: true,
firstname: true,
condition: true,
image: true,
password: true,
email: true,
}
const cleanProperties = (req, res, next) => {
/* clean the json of any unwanted properties */
const clean_json = {}
Object.keys(req.body).forEach(
property => // for property
allowedProperties[property] && // if is make as acceptable
(clean_json[property] = req.body[property]) // pass to new obj
);
req.body = clean_json;
next();
}