retrieve the documents that correspond to a specific string in mongoose

Currently, I am working on integrating a search feature into a MERN stack application. The idea is to utilize the searchWord extracted from req.params.searchWord and fetch results containing that specific searchWord.

Although my existing code serves its purpose effectively, I'm curious to know if it's feasible to leverage the functionality of filteredData using mongoose's aggregate function.

const getQuoteAuthorSearchedResult = async (req, res) => {
  try {
    const searchWord = req.params.searchWord

    const uniqueQuoteAuthors = await QuoteModel.aggregate().group({
      _id: "$author",
      count: { $sum: 1 },
    });

    const filteredData = await uniqueQuoteAuthors.filter((value) => {
      return value._id.toLowerCase().includes(searchWord.toLowerCase());
    });

    res.status(200).json({
      results: filteredData
    })
  } catch (error) {
    res.status(401).json({ success: false });
  }
};

This is how my data appears:

[
        {
            "_id": "Martin Luther King Jr",
            "count": 1
        },
        {
            "_id": "Friedrich Nietzsche",
            "count": 1
        },
        {
            "_id": "Marcus Tullius Cicero",
            "count": 1
        },
        {
            "_id": "Andre Gide",
            "count": 1
        },
        ...
]

Answer №1

Utilize the $match pipeline stage and leverage the $regex query operator for filtering grouped data.

Additionally, incorporate $option: 'i'

Implement case insensitivity to match both upper and lower cases

Example:

import mongoose from 'mongoose';
import { config } from '../../config';

mongoose.set('debug', true);

const quoteSchema = new mongoose.Schema({
    author: String,
});
const QuoteModel = mongoose.model('quote', quoteSchema);

(async function main() {
    try {
        await mongoose.connect(config.MONGODB_URI);
        await Promise.all([QuoteModel].map((m) => m.collection.drop()));
        // seed
        await QuoteModel.create([
            { author: 'Nick' },
            { author: 'Nick' },
            { author: 'Jack' },
            { author: 'John' },
            { author: 'Alex' },
        ]);

        const searchWord = 'CK';

        const uniqueQuoteAuthors = await QuoteModel.aggregate()
            .group({
                _id: '$author',
                count: { $sum: 1 },
            })
            .match({ _id: { $regex: searchWord, $options: 'i' } });

        console.log('uniqueQuoteAuthors: ', uniqueQuoteAuthors);
    } catch (error) {
        console.error(error);
    } finally {
        await mongoose.connection.close();
    }
})();

Output:

uniqueQuoteAuthors:  [ { _id: 'Jack', count: 1 }, { _id: 'Nick', count: 2 } ]

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

Using middleware to handle in-app redirection in Express.js

I am currently in the process of creating a middleware to manage URL aliases. My approach at the moment is as follows: // [...] module.exports = function() { return function(req, res, next) { // getAlias would return an object {alias: "alias/path" ...

Can a string be transformed into HTTP POST parameters?

Below is a snippet of code where I've utilized the .serialize() method to convert all form inputs into a string, which is then sent to the server: $.ajax({ type: "post", url: wp_urls.ajax_url, data: { action: "submit_form", ...

Exploring Angular.js: Finding the correct path in a JSON array

Within my Angular application, I have a $scope variable defined as follows. $scope.roleList2 = [ { "roleName" : "User", "roleId" : "role1", "children" : [ { "roleName" : "subUser1", "roleId" : "role11", "collapsed" : true, "children" : [ ...

Express JS form validation using hapi/Joi fails to accurately validate the input data in forms

I am currently facing an issue with my form validation using the hapi/Joi package. The problem is that the schema keys are all taking the value of "undefined", which results in the first validation error being returned. How can I resolve this issue? Additi ...

Verifying internet connectivity and updating content using jQuery and JavaScript

Upon loading the page, the following functionality occurs without triggering a click event: The updated code attempts to determine if the internet connection is active. If the connection is off, the 'link' on the page will be disabled (non-click ...

What could be the reason for the failure of express-ejs-layout to render layout.ejs?

Upon reviewing the setup mentioned, it seems like the content of home.ejs is not being injected into the <%- body %> section of the layout.ejs page. When accessing the default route /, only the content from home.ejs is displayed without any styling o ...

Changing the value of a previous TD element using Javascript

My page features a button that, when clicked, triggers a function to change the value in the previous TD element from "No" to "Yes". Here is the HTML snippet: <tr class="odd"> <td class="">13.00</td> <td class="">DDR</td> ...

What is the best method to determine when 20% of a "<section>" element is within the user's view?

Looking at the layout, I have two sections that take up the entire page. My goal is to detect when the second section is 20% visible while scrolling, and then smoothly scroll to lock that section in place so it occupies the full space. This action should a ...

Using app.get('env') in local development and live production settings

var express = require('express'); var app = express(); var db_url; if(app.get('env') == "development"){ db_url = 'mongodb://127.0.0.1:27017/localhost'; }else{ db_url = 'something else'; } console.log(app.get(&apos ...

Enhance Your Webstorm Experience with Views Folder Autocomplete

My approach involves utilizing server rendering to deliver .html files from the /views directory, along with static assets from folders like /styles and /scripts within the app folder. Within my index.html file, I reference the stylesheet located in the / ...

Dragging elements in Snap.svg with Path element

Currently, I am attempting to drag a Path element using Snap.SVG and the drag method. Initially, the functionality seems to work fine without any parameters. However, when I try to add listeners, it fails to function properly. It appears that changing the ...

What could be causing the issue with res.send not functioning in node js?

I am currently working with node for the backend and angular for the frontend. My issue lies in checking the existence of a file in nodejs and passing the response to angular. Despite my efforts, this process is not functioning correctly. As a novice, I ha ...

Resolving the dilemma of complete form validation in Jquery

I'm currently working on a PHP form that is being validated with jQuery. In this form, there is a radio button list. If the user clicks "Yes," then the textbox related to that radio button should not be validated. However, if the user clicks "No," the ...

Using Typescript with Protractor for Dropdown Menus

As a newcomer to Protractor, I am looking to automate the selection of a dropdown. While I have some knowledge in JavaScript, I am currently working with typescript. Can someone advise me on how to select the dropdown option based on the text provided? Fo ...

Tips for effectively managing loading and partial states during the execution of a GraphQL query with ApolloClient

I am currently developing a backend application that collects data from GraphQL endpoints using ApolloClient: const client = new ApolloClient({ uri: uri, link: new HttpLink({ uri: uri, fetch }), cache: new InMemoryCache({ addTypename: f ...

Analyzing the current time against a user-inputted time using Javascript

Looking at this html and javascript code, the goal is to compare an input time with the current time. If the input time is less than 2 hours, "Less time" should be displayed in the label; if it's more than 2 hours, then "sufficient time" should appear ...

leveraging dependency injection to retrieve a function in JavaScript

I'm exploring a way to obtain a function in JavaScript without executing it, but still defining the parameters. My current project involves creating a basic version of Angular's dependency injection system using Node.js. The inject() method is us ...

A novel way to enhance a class: a decorator that incorporates the “identify” class method, enabling the retrieval

I have been given the task to implement a class decorator that adds an "identify" class method. This method should return the class name along with the information passed in the decorator. Let me provide you with an example: typescript @identity(' ...

Incorporate form checkboxes with the image's title preceding them within every individual div

Is there a way to dynamically add a form checkbox to each of these divs with incrementing id's? My current setup is as follows: <div class="img-wrap"> <img title="1" src="img.jpg" /> </div> <div class="img-wrap"> < ...

Altering the hue of a picture

Looking to alter the color of an image on a webpage, specifically a carport. It's crucial that the texture and shadows remain consistent. Swapping out images with different colors would require an excessive amount of images, so I'm seeking advice ...