Yes, it is possible, but...
Usually you would not just use req.body
directly with your database because the client could put things into that object that you don't really want in your database. Remember, a POST coming in from a client can have anything in it - it is not just limited to what you want to be in that object.
So, the safer way to do so would be to create your own object and copy over only the properties that you specifically want. That can be done either manually or you can make a little function that you pass an array of property names to that will copy all those over. And, then after copying over the desired properties, you can then add additional properties if you want before saving it in the database.
If you really wanted to add more things to req.body
, it is just a plain Javascript object so you can just directly assign new properties to it.
FYI, here's a safeCopy function that makes a copy of a list of properties into a new object:
function safeCopy(srcObj, props, destObj = {}) {
for (let prop of props) {
if (srcObj.hasOwnProperty(prop)) {
destObj[prop] = srcObj[prop];
}
}
return destObj;
}
// sample req.body that has unplanned properties on it
const req = {body: {
fname: "Jack",
lname: "Bundy",
age: 31,
girlfriend: "Alice", // undesired property
salary: 1000000 // undesired property
}};
// make copy that only has desired properties
let newObj = safeCopy(req.body, ["fname", "lname", "age"]);
// see new object with only the desired properties
console.log(newObj);
For a way to do this with ES6 object destructuring assignment, see How to get a subset of a javascript object's properties. While cool to see the extent of what you can do with advanced destructuring assignment, I don't always find it's tricks all that readable and clear which is always a priority for me. Three years from now when I've long forgotten this code, I want to be able to easily recognize what the code does. Anyway, that's another way to make a copy of a set of properties from the object.