Your search parameter is not formatted correctly

I am currently working on filtering a collection based on different fields such as name by extracting the values from the URL parameters. For example:

http://localhost:3000/patient?filter=name:jack

I have implemented a method to retrieve and convert these URL parameters into a JSON object:

const filter = handleQueryFilter(req.query.filter)

const handleQueryFilter = (query) => {
    try{
      // Convert the string to resemble a JSON object
      // For example, id: -1, name: 1 becomes { id: "-1"}, {name: "1" }
      const toJSONString = ("{" + query  ).replace(/(\w*[^:].$)/g, (matched => {
       return '"' + matched.substring(0, matched.length ) + '"}'  ;
    }));
      
      return JSON.parse(toJSONString);
    }catch(err){
      return JSON.parse("{}"); // Parse an empty JSON object if the client inputs the wrong query format
    }
  }

The result returned from the 'handleQueryFilter' function is then passed to the 'find' method to retrieve data from the database.

let patients = await Patient.find(filter);

However, I'm facing an issue where the 'handleQueryFilter' function always returns an empty object (as indicated in the catch block above). Can anyone point out what might be going wrong?

Answer №1

To automatically parse req.body in Express, start by using the following code:

app.use(express.json())

Then, update your URL to:

http://localhost:3000/patient?name=jack

Answer №2

The replace function in your code is not performing as expected:

"{id: -1, name: 1".replace(/(\w*[^:].$)/g, (matched => {
       return '"' + matched.substring(0, matched.length ) + '"}'
}))

Instead of producing valid JSON like '{id: -1, name:" 1"}', it causes an error when using JSON.parse.

You might consider using a different approach like this:

Object.fromEntries("id: -1, name: 1".split(/,\s*/).map(_=>_.split(/:\s*/)))

This will give you the result {id: '-1', name: '1'} without needing to rely on JSON.parse.

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

Whenever I attempt to run the NPM install command in the Terminal, it seems to generate multiple errors

I am encountering an issue on my work laptop. I have the latest versions of Angular, Nodejs, Nodesass, and VScode installed in the local environment path. Whenever I download an Angular template from Github and try to do NPM Install, it consistently thro ...

An array containing multiple arrays in JSon format

I am currently working on creating a JSon document along with its corresponding xsd file to generate JAXB classes, and I'm not entirely sure if I am doing it correctly. The structure I aim to achieve is as follows: team -name="name" -game="game ...

Unleash the power of ExpressJS: The ultimate guide to sending data to

I am facing an issue with a post request that redirects to a new route, and here is the provided code snippet //POST login app.post('/login', urlencodedParser, function(req,res){ userLogin(req.body, function(response){ if(response ...

Using a pipe filter to implement a search feature in an Ionic search bar

Hey everyone, I'm facing a little issue here. I created a pipe filter to sort through some data, but now I need to include two more filters and I'm not sure how to go about it within this pipe. Below is an example of the pipe I have created: ...

looping through a linked data object with ng-repeat

I am working with a Node object in my Angular controller. Each Node contains a next property which points to the next item: $scope.Stack = function () { this.top = null; this.rear = null; this.size = 0; this.max_size = 15; ...

Transport the unique identifier of the table row

After retrieving the list of followers from Instagram and storing it in an array in a session, I am displaying the data in a tabular format. <table class="tablesorter" cellspacing="0"> <thead> <tr> <th>&l ...

Unable to redirect Firebase Hosting root to a Cloud Function successfully

Currently I am utilizing Firebase Hosting along with a Firebase.json file that is configured to direct all traffic towards a cloud function (prerender) responsible for populating meta and og tags for SEO purposes. { "hosting": { "public": "dist/pr ...

Develop a cross-platform application using webpack for both web browsers and Node.js

I'm currently developing my first module, and the code is almost identical for both browser and node.js versions. The only variance lies in the use of XmlHttpRequest for the browser and the http module for node.js. Here's a sample code snippet t ...

Is it possible to transfer data from a JavaScript file to the Express server without relying on a form submission?

As a newcomer here, I apologize if I overlook any best practices. Currently, I am in the process of developing a sudoku game using express, JavaScript, HTML, and mongoDb. My current challenge involves setting up a statistics system. My goal is to send da ...

Error encountered while running npm build: Typescript issue within plotly.js/index.d.ts

Trying to implement this code snippet: import createPlotlyComponent from 'react-plotly.js/factory'; const Plot = createPlotlyComponent(window.Plotly); in my React project implemented in TypeScript. Encountered a TypeScript error during npm run ...

Storing a rendered view in a variable in ExpressJS for handling AJAX responses

I am looking to dynamically load the contents of a partial view (created in Jade) into a Bootstrap modal dialog using an AJAX call. However, I not only need to retrieve the generated HTML but also additional data along with the rendered view. I am hoping t ...

Troubleshooting an Express Server - Why can't I /GET?

I'm working on a simple app to practice using Express, but I'm encountering trouble with the setup. Whenever I try to run the app, I keep getting a Cannot /GET error message. Here is an overview of the code: In the main directory - var express ...

Can $.ajax be used as a replacement for $(document).ready(function()?

After conducting an extensive search, I am still unable to find a clear answer to my assumption. The code I used is as follows: <?php session_start(); if (isset($_SESSION['valid_user']) && $_SESSION['from']==1) { ?> ...

Removing a user profile in node.js express is a simple process that can be

Hello there, I am new to programming and have successfully created a userschema in mongoDB with register and log in API. Now, I am struggling to understand how to implement the functionality to delete a user profile entirely. Despite spending a significant ...

Explanation of JavaScript code snippet

fnTest = /abc/.test(function () { abc; }) ? /\bchild\b/ : /.*/; I am struggling to comprehend the functionality of this particular javascript snippet. Would someone be able to elaborate on the logic behind this code fragment? ...

The passport JWT authorization failed, not a single message is being printed to the console

I am currently working on building a login and registration system. I have experience using passport before and had it functioning properly. However, it seems like the npm documentation has been updated since then. I am facing an issue where I cannot even ...

Transmitting information to the service array through relentless perseverance

I need assistance finding a solution to my question. Can my friends help me out? What types of requests do I receive: facebook, linkedin, reddit I want to simplify my code and avoid writing lengthy blocks. How can I create a check loop to send the same ...

Tips for utilizing php's json_encode($var) in the outcome function when working with ajax

// Here is some ajax code snippet for retrieving survey filters var survey_id = $(this).val(); var user_id = $('#SurveyFilterUserId').val(); $.ajax({ type : 'POST', dataTyle : &apo ...

The Facebook API's JavaScript SDK displays the status as 'connected' even after logging out

As I navigate my AngularJS website, I am utilizing the Facebook SDK for JavaScript to facilitate registration forms. After successfully logging in and retrieving the necessary data from my first attempt, I proceeded to register and eventually logged out of ...

What is a Mongoose Schema type in TypeScript and how can it be used as a custom

https://i.stack.imgur.com/mtlRi.png Could anyone assist me with storing a custom object that includes attributes from the StationRating interface? ...