Is it possible to add filtering to my MongoDB when using the find() method in express routing? If so, how can

Hey there! I have this GET function that uses async to find a specific "Category" mongoose Schema that the user just clicked on, along with another "Tool" mongoose Schema which fetches all tools from my database and sends them both to a rendered page.

I'm wondering if there’s a way to add filtering to my Tool.find so it only retrieves tools with the same category property (Tool.category) as the Category (Category.name) the user clicked on?

Here's the GET function:

router.get("/catalog/:id", function (req, res, next) {
    let output = {
            category: [],
            tools: []
    };
    async.parallel([
            function (cb) {
                    Category.findById(req.params.id).exec(function (err, foundCategory) {
                            if (err || !foundCategory) {
                                    req.flash("error", "No category found.");
                                    return res.redirect("back");
                            } else {
                                    output.category = foundCategory;
                                    cb(null, foundCategory);
                            }
                    });
            },
            function (cb) {
                    Tool.find({}, function (err, foundTools) {
                            if (err || !foundTools) {
                                    req.flash("error", "No tools were found.");
                                    return res.redirect("back");
                            } else {
                                    output.tools = foundTools;
                                    cb(null, foundTools);
                            }
                    });
            }
    ], function done(err, results) {
            if (err) {
                    res.json(err.message);
            } else {
                    res.render("tools/catalog-items", {
                            category: output.category,
                            tools: output.tools
                    });
            }
    });

});

Answer №1

Achieving your goal is definitely possible. The key is to make the second query depend on the results of the first one.

In this scenario, using async.parallel won't suffice because you need to obtain the result of Category.findById beforehand.

If you have more than two subsequent queries in a sequence, I recommend utilizing the async.waterfall method. You can refer to the documentation here.

However, for this specific case, you can simplify it as follows:

Category.findById(req.params.id, function (err, foundCategory) {
    if (err || !foundCategory) {
        req.flash("error", "No category found.");
        return res.redirect("back");
    }

    Tools.find({
        // Filter by the `name` field based on the question's description
        // Consider creating an ObjectId reference in the future
        category: foundCategory.name
    }, function (err, foundTools) {
        // If filtering results in an empty array of tools, handle it gracefully 
        if (err || !foundTools) {
            req.flash("error", "No tools were found.");
            return res.redirect("back");
        }

        res.render("tools/catalog-items", {
            category: foundCategory,
            tools: foundTools
        });
    });
});

You can also implement sorting by simply adding

.sort({someProperty: 1}).exec(...)
. Refer to examples here.

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

the attempt to send an array of data to the $.ajax function was unsuccessful

let myArray = []; myArray.push(someValue); let requestData = { action: myAction, array: myArray }; $.ajax({ type: "POST", data: requestData, url: requestUrl, success: handleSuccess, error: handleError }); When ...

Issue with ExtJS causing store to not load properly

I have been working on this issue for over a week now and cannot seem to get it resolved. The webservice is returning data, which I can see, but the store is not loading it correctly. The only time I managed to display the entire response in the grid was w ...

Having trouble getting a response when using formidable in Next.js?

I am working on uploading a file from the front end to my GCP workflow, and everything seems to be functioning correctly. However, I am consistently encountering an issue where the API resolved without sending a response message appears. I attempted to r ...

Transferring an array from JavaScript to PHP, encountering an issue with determining the length

I'm having an issue passing an array from my .js file to a PHP file. In JavaScript, the array is structured as follows: theBlock[0 - 79] with color, x, and y values. For example, theBlock[10].color or theBlock[79].x The data is sent using the follow ...

AngularJS: Default value causes dropdown menu text to not display

I am facing an issue with my select menu. <select id="dd" ng-show='data != null' ng-model='search'></select> Initially, I set the filter to display only USA by default. $scope.search = 'United States of America' ...

Updating embedded documents with new information in mongodb

After searching on SO, I couldn't find a satisfactory answer to my question related to working with mongodb and php for the past couple of weeks. So here I am seeking help. I have a database where I need to add new data to one of the embedded/nested d ...

What is the best way to comprehend this asynchronous exercise with async/await?

Currently, I am working on some exercises related to async/await, and I seem to be stuck on the following problem: The function ​​opA​ should be executed before ​opB​, and ​opB​ should be executed before ​opC​. Arrange the function call ...

Ways to insert text at the start and end of JSON data in order to convert it into JSONP format

Currently, I am working on a project where I need to add a prefix "bio(" and a suffix ")" to my JSON data in order to make it callable as JSONP manually. I have around 200 files that require this modification, which is why I am looking for a programmatic ...

The first item in Swiper is incorrectly displayed after the initial cycle, even though the data is accurate

Currently, I am incorporating the slider functionality in Vue using the Swiper framework. Although everything seems to be functioning properly, there is a minor issue that arises when filtering the data and completing the first cycle after scrolling. The f ...

Node.js makes it easy to create and handle POST form submissions efficiently

I've recently started working with Node.js and am having some issues with my express static and nodemailer app that involves a POST form. Essentially, I want to send an email containing all the information from the filled fields, but I'm struggli ...

Front end Forget Password feature of MERN stack is currently not functioning properly, unlike Postman which is working perfectly

Having trouble with the MERN stack Forget Password feature on the frontend (works fine in Postman). After entering the email and clicking send, an error appears - user not found. I've been attempting to troubleshoot this issue without success. Any adv ...

Facing an issue with the format.js not functioning properly in Rails version 6.1.3

styles.css @import url("https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap"); body { font-family: 'Roboto', sans-serif; color: #333; } .wrapper { max-width: 960px; margin: 0 auto; } button { background ...

What is the best way to incorporate raw HTML code into a .jsx file within a NextJS website?

I need to integrate Razorpay code into my NextJS website, but it's currently in pure HTML format. For example, the code looks like this: <form><script src="https://cdn.razorpay.com/static/widget/subscription-button.js" data-subscrip ...

Show the button when the mouse moves over the image

Here is the snippet of code I am working with: <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> <script src="Js/jquery.min.js"></script> <script type="text/javascript"> $(document).r ...

Is it possible to decrease the size of a div by scrolling both vertically and horizontally?

Can a div's height and width both be reduced at the same time while scrolling down a page? Let's say that as the user scrolls, the size of the div changes from 400px by 400px to 200px by 200px, all while remaining centered on the page. I've ...

What is the most efficient method to retrieve and modify data in mongodb?

When working with a collection, I am required to retrieve a document, check its value, and increment the value if it is less than 40. Here is what I currently have: let promise = db.collection('transactions').findOne( { _id: 'myid& ...

Update the package.json file by adding a new command to an existing script

Is it possible to automatically run npm install before starting the application with npm start? Here is what my package.json file currently looks like: . . "scripts": { "test": "echo \"Error: no test specified\ ...

Activate just the show more / show less button on the website that has several buttons with identical ids

Whenever the "show more" button is clicked, additional images are displayed in the gallery and the button text changes to "show less". However, in my ExpressionEngine (CMS) templates and entries, all "show more" buttons share the same id, causing other but ...

Ways to show a component based on a specific condition being met using react and javascript

On every page, the layout component is rendered. My goal is to achieve the following: on /items page *Display Layout component only if user is admin *Do not display Layout component if user is non-admin Below is my code snippet: function Main() { con ...

"Every time ajax is called, it will always generate

function lks() { var groupname = document.getElementById('groupname').value; $.ajax ({ url: 'verifyGroup.php?groupname='+groupname, type: 'get', ...