Screen content of a post request in Node.js

Can this code in node.js + express be simplified?

// Code snippet for registering a new participant

app.post('/api/participant', function (req, res, next) {
    var data = req.body;

    // Ensure only specific fields are uploaded
    var participant = new Participant({
        first: data.first,
        last: data.last,
        email: data.email,
        category: data.category
    });
    participant.save(...);
});

I opted not to use:

    var participant = new Participant(data);

This decision was made to prevent potential advantages being gained by including unauthorized properties like score.

My question is whether this filtering logic needs to be repeated in every post handler or if there is a more efficient way to handle it.

Answer №1

I couldn't find any existing libraries through a quick search on Google, but this handy function should get the job done effectively:

function filterProperties(object, properties) {
    Object.keys(object).forEach(function(property) {
        if(properties.indexOf(property) == -1) {
            delete object[property];
        }
    });
}

For instance,

var example = {"example1": 1, "example2": 2, "example3": 3};
console.log(example); // {"example1": 1, "example2": 2, "example3": 3}
filterProperties(example, ["example1", "example3"]);
console.log(example); // {"example1": 1, "example3": 3}

In your scenario,

filterProperties(data, ["first", "last", "email", "category"]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm currently attempting to set up the React JS package, but unfortunately encountering some errors in the process

I'm having trouble installing react as I keep receiving errors. My system has npm version 8.12.1 installed. I attempted to downgrade react, but that didn't resolve the issue. I tried the following steps: Update npm using: npm install npm -g Dow ...

Node.js is not compatible with npm

After installing Node on my machine and having everything work correctly, I encountered an issue during an online course back in 2019. The instructor was using an older version of npm (v5.5.1) and recommended that everyone downgrade to the same version for ...

Populating a many-to-many relationship in Mongoose using uni-directional references

These are the schemas I'm using to represent a many-to-many relationship: var GenreSchema = new Schema({ name: {type: String}, }); mongoose.model('Genre', GenreSchema); var MovieSchema = new Schema({ title: {type: String}, genres ...

Guide on decrypting a file encrypted with C# using Node JS

I currently have encrypted files in C# using DES and PKCS7 encryption. My objective is to decrypt these files in Node JS. The decryption code in C# that I am using appears like this: public string SSFile_Reader( string fileToDecrypt ) { DESCryptoService ...

Having issues with yarn while trying to install node-sass

I recently joined a Web project that utilizes yarn instead of npm. It involves additional libraries and configurations that I am not familiar with. The issue I am facing is related to installing node-sass using yarn on my machine. yarn add node-sass Howev ...

Error: The argument passed to the function must be an Array type. Undefined value was received instead of an array

Looking for some assistance with this coding issue, hoping someone with expertise can lend a hand! (Not my forte) I've written this Typescript code snippet for a basic CloudFunction export const add2list = functions.https.onRequest((req:any , res:any ...

Updating the scope variable in an AngularJS directive

Recently delving into Angular, I encountered an issue: I have both a list view and a details view with tags. To facilitate navigating between the two views and loading new elements from a service upon click events, I created a directive. My aim is to also ...

The crosshair functionality in Zing Chart is causing a CPU leak

After enabling the crosshair feature on my chart, I noticed a significant issue when using Chrome 57 (and even with versions 58 and ZingChart 2.6.0). The CPU usage spikes above 25% when hovering over the chart to activate the crosshair. With two charts, th ...

Tips for Successfully Sending Vue Data in Axios POST Call

I'm struggling to pass Vue data to an axios.post request. Using the Vue template doesn't seem to work. How can I successfully pass the Data? Here is my Code: <body> <div id="app" class="container"> <div> ...

Passing an event from a Vue3 parent component to its child component

How do I trigger a load event from a parent component to the child component? The child component needs to be able to listen for the load event in a slot-defined element and then perform some actions with the event. For example: <template> <slot ...

Applying the jqtransform plugin to all forms except for one

We've implemented the jQuery jqtransform plugin to enhance the appearance of our website's forms. However, there is one particular form that we'd like to exclude from this transformation. I made adjustments to the script that applies jqtrans ...

Issues encountered with invoking function in CodeIgniter controller through Ajax

Running a codeigniter website with an add to cart functionality. When the user clicks the add to cart button, the product is successfully added to the cart after the page reloads. The controller code for this feature is as follows: public function buy($ ...

Sharing data from AJAX calls in Vue using vue-resource

After using Vue resource, I'm attempting to create an AJAX call that is based on the data received from a prior AJAX call. I have successfully bound the data fetched from /me to the userDetails prop. However, when trying to pass userDetails.id into t ...

Using a CSS gradient with a variable in React.js - A guide to implementation

Looking to incorporate the following CSS property into the Navlink component. In the CSS file, the property is usually written like this using gradient. .ele { background-image: linear-gradient(45deg, #808080 25%, transparent 25%), li ...

What is the conventional method for sending data by utilizing the output of a previous data submission in Node.js with Express and FaunaDB?

I am in the process of revising a project and have a question about how to post an array of data using the return value of a previous post request as the ID. Here is an overview of the data structure: Checklist A [ChecklistItem 1, ChecklistItem 2, Checkli ...

Interactive data table feature in React, transferring selected row data to a modal pop-up

I am currently developing an offline Progressive Web App (PWA) using ReactJS and have integrated the react-data-table-component, which has been very helpful so far. Within the table, I have implemented an onRowClicked function that triggers whenever a row ...

Is there a way to still access the data from a radio button even if it hasn't been selected?

I'm currently working on a questionnaire feature and facing an issue where I need to capture all answers, even if the radio button is not checked. Here's a snippet of the HTML code: $('input:radio').each(function () { if ($(this). ...

"Utilizing the Image onLoad event in isomorphic/universal React: Activating event registration once the image has been

When a page is rendered isomorphically, the image can be downloaded before the main script.js file. This means that the image may already be loaded before the react register's the onLoad event, resulting in the event never being triggered. script.js ...

Getting a null value for active user after completing the sign-in process

I am using local storage to store username and password. However, I am encountering an issue where the active user is returning null after a certain line of code, and I am unsure why. console.log("I am the Active user: " + activeUser); const me ...

Capture the 'value' of the button when clicked using ReactJS

I'm generating buttons dynamically using the map function to iterate through an array. Each button is created using React.createElement. ['NICK', 'NKJR', 'NKTNS'].map(function (brand) { return React.createElement(' ...