Ensuring the correctness of req.params using express validator

I need the user to input a specific account number in the endpoint, and I've been trying to validate this parameter against my database. However, I'm having trouble getting it to work correctly. Can you please point out what I might be doing wrong?

My validation logic:

const validateReq: [
param('accountNumber').exists().custom(acctNo => accountNumberExist(acctNo)),]

Function for checking account number existence:

    function accountNumberExist(inputAcct) {
    const isfound = accounts.find(account => account.accountNumber === inputAcct);
    if (isfound === undefined) throw new Error('Account Number not found');
  }

Data in my accounts file:

    const accounts = [
  {
    id: 1,
    accountNumber: 1234567890,
    createdOn: new Date(),
    owner: 1,
    type: 'current',
    balance: 23444.43,
    status: 'active',
  },
  {
    id: 2,
    accountNumber: 1234167890,
    createdOn: new Date(),
    owner: 1,
    type: 'savings',
    balance: 2233444.43,
    status: 'active',
  },
  {
    id: 3,
    accountNumber: 9987654321,
    createdOn: new Date(),
    owner: 2,
    type: 'saving',
    balance: 73444.43,
    status: 'active',
  },
];

Despite the fact that the requested parameter exists in my accounts database, I keep receiving the error message 'Account Number not found'. Any insights on why this could be happening?

Answer №1

When using express middleware, params are automatically parsed as strings. For example, if a request is made to the path specified as /some/1000,

app.get('/some/:path', (req, res, next) => {
  console.log(typeof req.param.path)
  // outputs string
})

To ensure that the incoming parameter is treated as an integer (Number), you should parse it accordingly since the accountNumber data is stored as an integer. You can achieve this by adding toInt in the chain as shown below:

const validateReq: [
  param('accountNumber').exists().toInt().custom(acctNo => accountNumberExist(acctNo)),
]

Answer №2

It seems that the accountNumber inside accounts array is a number, while req.params.accountNumber is a string. To resolve this, you will need to convert the data type accordingly. You can achieve this by using the following code snippet:

    accountNumberExist(inputAcct) {
        const isfound = accounts.find(account => account.accountNumber.toString() === inputAcct);
        if (isfound === undefined) throw new Error('Account Number not found');
  }

Answer №3

It appears that the issue lies in your query. The find method operates asynchronously, causing the isfound property to not contain the expected data. To address this, I have implemented a straightforward solution using promises which has proven effective.

// Function to check if account number exists.
accountNumberExist(inputAcct) {
    return accounts.find({accountNumber: inputAcct})
    .then(result => {
        if (result.length == 0) {
            console.log("Account Number not found");
            return Promise.reject('Account Number not found');
        }
        return Promise.resolve();
    });

}

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

Utilizing ExpressJS for dynamic URL segments

When faced with the need to include a dynamic segment in the URL, my initial solution was to experiment with the following code snippet: app.get('/one/*/two/*/three', (req, res, next) => { // req.params as any)[0] - first dynamic segment ...

Managing a multitude of instances in Three.js

While working on a scene in three.js that includes a high quantity of instances (around 2000) with 200-300 vertices each, I integrated some postprocessing effects using the EffectComposer. However, I noticed that the performance has been slowing down. Is ...

Determining whether a user possesses a specific role

Currently, I am using mongoDb within my express server to store user information in the following structure: var UserSchema = new Schema({ username: { type: String, required: true, index: { unique: true } }, password: { type: String, required: ...

Keep your filter content up-to-date with real-time updates in Vue.js

I am facing an issue with a markdown filter where the content of component.doc is set to update through a websocket. Despite updating the scope's component, the filtered content remains unchanged. Is there a way to dynamically refresh the v-html in t ...

The second div element remains unselected in jQuery

Below is the example of an HTML structure: <span id="17">yes here</span> <div class="PricevariantModification vm-nodisplay"></div> <div class="PricesalesPrice vm-display vm-price-value"> <span class="a"></span> ...

cdkDropList does not function properly when used with ng-template in a dynamic component list

Exploring the new Drag&Drop features introduced in Angular Material 7, I am dynamically generating components using ng-template. <div cdkDropList (cdkDropListDropped)="dropLocal($event)"> <ng-template #components></ng-templat ...

Displaying list values as titles in a slider

Currently, I am utilizing the bjqs slider plugin to slide some content. Apart from the next and previous buttons, there is a navigation feature that allows users to choose their desired slide using numbers. However, I want to display the slide's title ...

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...

You've got a function floating around without any specific theme tied to it. Make sure one of the parent elements is utilizing a ThemeProvider for proper context

I am working on implementing a Navbar in my current Project. The dependencies I am using are: mui/icons-material: ^5.2.5 mui/material: ^5.2.6 mui/styles: ^5.2.3 Here is the folder structure of my project: Root.jsx Navbar.jsx styles ...

When attempting to delete a resource using an HTTP request in Insomnia, I encountered a TypeError stating that it was unable to read the property 'id'

I recently started using Express and am in the process of setting up the Delete function for my database within the MERN stack. While testing my CRUD operations using Insomnia, I have encountered an issue specifically with the Delete operation. The proble ...

Force restart broken socket within Node.js program using Socket.IO programmatically

I have a simple one-to-one client and server Node.js based application. The Node.js is running on Linux (Intel Edison). I am attempting to automatically reboot the Linux server whenever the socket connection is broken. Is this achievable? Below is my unco ...

Is verifying email and password with jquery possible?

I am currently working on a jQuery form validation project: While the password and username validation are working fine, I am facing issues with email and password confirmation validations. Surprisingly, I have used the same technique for both. If you wa ...

Modifying data on the fly for a Highcharts series

My chart is currently functioning well with data in the options. However, when I leave the data empty for a series and attempt the following code (in order to change the data based on a click event), it fails to work. Any suggestions on how I can rectify ...

Is the ID "nodeName" specifically designated as reserved in the HTML5 language specifications?

I have an element with the following id: <span id="nodeName"></span> In my HTML code. Then, when using jQuery to do the following: $("#nodeName").html("someString"); I am getting an error in the console that says: Uncaught TypeError: Objec ...

What is the best way to remove duplicate select options while keeping the selected option intact

Is there a way to eliminate the duplicates of selected options in a dropdown using jQuery or JavaScript? I attempted using if/else statements in PHP, but it resulted in lengthy code across 12 different files. I also tested the following code snippet obta ...

What is the process for creating a MongoDB database on Heroku using MongoLab?

Utilizing Express.js and MongoLab, I have successfully implemented the Heroku setup for MongoDB in my production environment by adding this code snippet to my app.js file. //Mongo on Heroku Setup var mongo = require('mongodb'); var mongoUri = ...

A guide on converting JSON without using the "&quot" symbol

let newText = [{&quot;name&quot;:&quot;en3&quot;,&quot;value&quot;:234},{&quot;name&quot;:&quot;en4&quot;,&quot;value&quot;:135},{&quot;name&quot;:&quot;en1&quot;,&quot;value&quot;:335 ...

When attempting to update a Vue data variable, an error occurred stating that "blogItems" is not defined

I am attempting to retrieve all the posts from Firebase and store them in an array but I keep encountering the following error: Uncaught (in promise) TypeError: Cannot read property 'blogItems' of undefined Below is the script causing the issue: ...

Example of material-ui-pickers: Error - Object(...) is not a function

Trying to implement a basic material UI pickers example using a clean project and following the installation and usage instructions provided here: An error message is displayed as follows: TypeError: Object(...) is not a function Module../node_modules/@m ...

Clearbox JS "notifications"

Currently, I have integrated Clearbox JS on my website to allow users to view larger versions of images after visiting the images page. However, I have noticed that on every single page, Clearbox JS displays a message at the top of the page indicating what ...