How to Build an Express.js Query by Using a URL Parameter?

Is there a way to retrieve specific data from my MongoDB database based on the URL? For example, if I navigate to localhost:3000/phones, I want to fetch all entries with the category "phones", and if it's localhost:3000/laptops, I need data related to laptops.

Here is the schema for the data:

    name: {
        required: true,
        type: String
    },
    category: {
        required: true,
        type: String
    },

Currently, my code looks like this:

router.get('/getAll', async (req, res) => {
    try {
        const data = await Model.find();
        res.json(data)
    }
    catch (error) {
        res.status(500).json({ message: error.message })
    }
})

I attempted to use findByID method but encountered some issues.

Answer №1

To easily find the answer, refer to the documentation available at: https://www.mongodb.com/docs/drivers/node/current/quick-reference/

router.get('/phones', async (req, res) => {
    try {
        const data = await Model.find({category: "phones"});
        res.json(data)
    }
    catch (error) {
        res.status(500).json({ message: error.message })
    }
})

If you need to handle both phone and laptop requests using the same query, consider refactoring it to manage in a single endpoint by utilizing query parameters in the request

The URL format should be: localhost:3000/getAll?category=phones

router.get('/getAll', async (req, res) => {
    try {
        const category = req.query.category
        const data = await Model.find({category: category});
        res.json(data)
    }
    catch (error) {
        res.status(500).json({ message: error.message })
    }
})

Answer №2

Ensure to include the query parameter ?category=phones or ?category=laptops in your request

This way, you can retrieve the category using req.query.category.

Here is the code snippet you need:


router.get('/getAll', async (req, res) => {
    try {
        const category = req.query.category;

        const data = await Model.find({
            category,
        });

        res.json(data)
    }
    catch (error) {
        res.status(500).json({ message: error.message })
    }
})

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

NextJs only displays loading animation once

Currently, I am developing an app using Next.js and I am facing a challenge with implementing a loading animation. The animation I am attempting to incorporate consists of three bouncing balls which display correctly. When I launch the Next.js app with n ...

Using iMacros to assign a variable the value of another variable

Running an imacro to automate the addition of sub-domain DNS records through the 123reg front end has presented some challenges due to my specific naming convention. I am mapping two sets of domains as follows: - x.x.x.1 to x.x.x.128 on domain1.com - x.x. ...

Troubleshooting: xPages radio button group onchange event malfunctioning

I have created a simple page with a listbox control that should update its values based on the selection made in a radiobutton group. The listbox is connected to a scope variable array as its data source. However, I am experiencing an issue where the lis ...

What is the best way to generate a box when a button is pushed?

How can I make a button create a box with text inside it when clicked? <div class="trades"> </div> <button onclick="create()">add</button> Here is the JavaScript function to create the box: function create() { var box = docu ...

Safari encountering parsing date error

My Angular application is receiving date formats from a web service in the following format: myDate = "2020-03-05T08:00:00" This translates to the fifth of March, 2020 for me For Chrome, Firefox, and IE, the format is yyyy-mm-ddThh:mm:ss However, Safar ...

unable to find the desired perspectives

My structure is as follows: app.js routes index.js views partials index.ejs The index.js file in the routes folder is rendering the template called index.ejs from the views folder const express = require('express'); const router = e ...

Limit the access to Google Maps data based on the size of the user's device for improved performance

I'm currently developing a web application that involves the integration of Google Maps. The idea is to have a desktop version displaying a map with markers for each listed object, but I want to avoid showing the map on smaller devices like iPhones. T ...

The Gatsby and React navigator

Hey there, I've run into a little snag while working on my React component. I'm trying to display a pop-up using JS, but when I try to build my Gatsby site, I encounter an error stating: WebpackError: ReferenceError: navigator is not defined. Bel ...

Issue encountered while activating react/jsx-sort-props [eslint-plugin-react Rules]

For my project, I am attempting to arrange props names alphabetically by utilizing the eslint-plugin-react plugin. After reviewing the example of the jsx-sort-props rules option at https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/js ...

Using Chrome's tabs.executeScript() method with an included script file

I'm in the process of creating a basic Chrome extension, where I need to actively monitor the AJAX calls being made on the page. Here is the code snippet I have implemented to listen to AJAX calls: var isAjaxWorking = false; //timeout var timeout; ...

Ways to update the contents of an individual div within an ng-repeat loop

I am currently working on some Angular code. <div ng-repeat="item in items | filter:search" class="container"> <h3>{{item.name}}</h3> <p>category:{{item.category}}</p> <p>price:INR {{ ...

Converting a MongoDB query into a query for the MongoDB Java driver

I'm in need of assistance with translating the following MongoDB query into a Java-based query using the Java MongoDB driver. Your help is greatly appreciated! db.playerscorecollection.aggregate( { $unwind: "$scorearray"}, { $group: { _id ...

Enabling and disabling HTML image input based on checkbox selection

I have utilized the code below to toggle the status of the image button between enabled and disabled modes using JQuery. Here is the code for a checkbox in Yii format: <?php echo CHtml::CheckBox('TermsAgreement','', array ('ch ...

Mongo DB's $set operation fails to update the req.body object

app.put('/accountlist/:id', function (req, res) { var id = req.params.id; console.log(req.body)); db.accounts.findAndModify({ query: {_id: mongojs.ObjectId(id)}, update: {$set:req.body}}, new: true}, function (err, ...

The problem arises when the type of a Typescript literal union becomes more specific within React children

Currently, I am in the process of converting our React/Redux project to TypeScript and encountering a challenge with TypeScript literal type union types. The issue that I'm facing is as follows: I have instantiated a Wrapper component with a type pr ...

I am encountering issues with getting jquery.multiple.select.js to properly validate and send the checked boxes to PHP

I'm having trouble with the validation and output in my PHP mailer using jquery.multiple.select.js v1.1.0. My goal is to allow visitors to select multiple options to request a quote on my site. Currently, I am able to receive the email with all other ...

sending functions into angular as opposed to using 'function()'

Lately, I've been immersing myself in Angular development. One thing that caught my interest was the idea of using a declared function instead of a generic "function() {}" placeholder, particularly in scenarios like handling promise callbacks. I encou ...

Incorporating JSON data into an array using d3

I'm currently working on mapping JSON data to an array variable in d3. Below is the JSON I am using: [ { "Impressions": "273909", "Clicks": "648", "CPM": 4.6388278388278, "Cost": 1266.4, "CPC": 1.9543209876543, "Campaign": "C ...

Renewed Promises: Exploring Promises in Angular JS

Revised with HTTP and initial code inspired by requests/Refer to the end of the post: Lately, I have been seeking help from the amazing SO community as I navigate through my AngularJS learning journey. I used to be a traditional C programmer but recently ...

Using Cordova plugman to add the initial platform-specific plugin into the project

Here are the system dependencies: cordova: @7.1.0 plugman: @2.0.0 I am trying to use plugman specifically for installing plugins on a particular platform (such as android). Having reviewed the documentation, I find that the workflow and usage is not en ...