Querying with mongodb using the $or operator yields a single result

I need help querying my MongoDB using JavaScript as I am only getting one result when I should be utilizing the $or operator.

The frontend sends a string, which I then split by spaces to search for matches in the database based on skills, location, and name. For instance, if a user searches for "PHP", it should return all users with PHP as a skill, even if they have other skills. Here is an example of the data:

Data:

{
    "_id":"1",
    "skills": ["PHP"],
    "name":"You"
}
{
    "_id":"2",
    "skills": ["PHP", "Javascript"],
    "name":"Me"
}

The code:

exports.search = async (req, res, next) => {
  try {
    const escapeChar = escapeString(req.body.query);
    const searchQueries = escapeChar.split(' ');
    let result;
    for (let i in searchQueries) {
      const ret = async () => {
        const pattern = new RegExp(searchQueries[i], 'gi');
        const user = await User.find({
          $or: [{ name: pattern }, { skills: pattern }],
        });
        return user;
      };
      result = await ret();
    }
    if (result.length > 0) {
      return res.json(sendResponse(httpStatus.OK, 'User found', result));
    }
    return res.json(sendResponse(httpStatus.NOT_FOUND, 'User not found'));
  } catch (error) {
      next(error);
  }  
};

Searching for PHP correctly returns both users. However, searching for 'PHP Me' only returns:

{
    "_id":"2",
    "skills ["PHP", "Javascript"],
    "name":"Me"
}

This is due to the issue that needs resolving. Please advise on how to address this problem.

Answer №1

Have you considered incorporating the $regex feature into your query?

db.getCollection('tests').find({
    $or: [{
        name: {
            $regex: /Me$/
        }
    }, {
        skills: {
            $regex: /PHP$/
        }
    }]
});

This particular query can lead to the desired outcome.

Answer №2

When reassigning your result within the loop, only the outcome of the final query will be present.

To address this issue in a more efficient manner, you can utilize regex with just one query:

exports.search = async (req, res, next) => {
  try {
    const escapeChar = escapeString(req.body.query);
    const searchQueries = escapeChar.split(' ');

    const pattern = new RegExp(`(${searchQueries.join("|")}`, 'i');
    const users = await User.find({
      $or: [{ name: pattern }, { skills: pattern }],
    });

    // If the above approach does not yield results
    const pattern = new RegExp(`(${searchQueries.join("|")})`);
    const users = await User.find({
      $or: [
        {name: {$regex: pattern, $options: "i" }}, 
        {skills: {$regex: pattern, $options: "i" }}
      ],
    });

    if (users.length > 0) {
      return res.json(sendResponse(httpStatus.OK, 'User found', users));
    }
    return res.json(sendResponse(httpStatus.NOT_FOUND, 'User not found'));
  } catch (error) {
    next(error);
  }  
};

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

Issue with sending data to the server via API using AngularJS controller

I am a beginner in angular js and I am attempting to POST data to the server using an API that I have created: function addmovie_post() { { $genre = $this->post('genre'); $cast = $this->post('cast'); $director ...

Exploring the world of unit testing with Jest in Strapi version 4

In my quest to conduct unit tests using Jest for the recently released version 4 of Strapi, I have encountered some challenges. The previous guide for unit testing no longer functions as expected following the latest documentation updates. Despite my effor ...

MongoDB allows for nested comments, where children comments are stored within the parent comment

Query: Is it better to nest child comments within a single parent comment or keep them separate? Overview: Setting up a comment system Child comments are allowed Currently, each comment (child or parent) is stored as a single record in a collectio ...

What could be the reason that NGINX is failing to forward my get request to the express server?

Currently, I am in the final stages of setting up my website and encountering issues with getting nginx to work properly. The setup includes a simple crud app with a React frontend, an Express backend, and nginx serving as a reverse proxy. All server rou ...

creating dynamic navigation tabs with scroll functionality

Utilizing Bootstrap Nav Tabs and Tab panes on my website has been a smooth process. However, I am encountering some difficulty in adding extra links that not only activate the Tab Panes but also scroll to them. The issue seems to be related to a specific l ...

Only displaying sub items upon clicking the parent item in VueJS

I'm in the process of designing a navigation sidebar with main items and corresponding sub-items. I want the sub-item to be visible only when its parent item is clicked, and when a sub-item is clicked, I aim for it to stand out with a different color. ...

Enforcing object keys in Typescript based on object values

I'm looking to design a structure where the keys of an object are based on values from other parts of the object. For example: type AreaChartData = { xAxis: string; yAxis: string; data: { [Key in AreaChartData['xAxis'] | AreaChart ...

No matter the method used for sending, the request body from post always returns as undefined

I have encountered a problem where none of the existing answers have helped me resolve it. I am attempting to pass a variable through ajax in the following manner: var myData = "Hi Og"; $.ajax({ type: 'POST', data: myData, url: &a ...

What is the process of calculating the average of JSON data and looping through it multiple times using Javascript?

I've encountered a JSON data set that has the following structure: { name: "Evelyn", assignment: "SCRUM", difficulty: 3, fun: 4 } And so on. My goal is to calculate the average value of both difficulty and fun for e ...

Iterate through all elements in Javascript/jQuery while excluding any nested children elements

Looking to retrieve all elements in the document: $("*").each(function(){ var el = $(this); }); I want to target only parent elements, excluding their children. For example: <div> <!--TARGET--> <div></div> <!--IGNORE--&g ...

Increase and decrease a counter in Javascript by clicking on two separate image tags, with increments and decrements between 1 and 10

Hello! I really appreciate your help. I am currently facing the following issue: <div id="thumb1"> <img class="img-responsive" id="prova" src="img/thumb-up-dark.png" alt=""> <div id="pinline">0</div> ...

Sort through the JSON data and showcase it in a gridded format

I need assistance with displaying data from a JSON object in a grid based on user selections. The user should be able to select a year and make from a dropdown menu, and the corresponding data should then be filtered and displayed in a grid. For example, i ...

My form does not receive the Bootstrap classes when using the jQuery script

**Why isn't my jQuery script coloring the rows as expected when certain conditions are met (I italicized the specific part of the code)?** Here is the HTML CODE for the POLL: <form id="pollForm" class="mb-4"> <d ...

Checkbox selection causing Bootstrap accordion to collapse

Hey everyone, I'm currently working with Bootstrap 5 accordion and facing an issue where the input checkbox is triggering the "collapse" event of the accordion. I attempted to relocate the checkbox outside the scope of the accordion button but that so ...

Angular cookies may expire, but using the back button always revives them

Utilizing angular's cookie library, I have successfully set a cookie to store the id and passcode of a shopping cart on the backend. However, despite setting the expiration date to a past time in order to expire the cookie once the cart is purchased, ...

Utilizing Mongoose populate to effortlessly generate sub documents

I am working with two mongoose schemas, Schema A: { field1 : { type : [String] } } Schema B: { field2 : { type : ObjectId, ref : 'A' } } My goal is to use Mongoose populate in order to achieve the following output: { field2 : ...

Switching between Custom tooltips and default tooltips in Chart.js and Angular

I need to show a tooltip based on certain conditions options: { tooltips: if (tooltipCondition === true) { { mode: 'index', position: 'nearest' } } else { { enabled: false, custom: function (tooltipMo ...

Ways to terminate all AJAX requests within a for loop

Is there a way to cancel all AJAX requests that are being handled by a for loop? var url = ["www.example.com","www.example2.com",....]; for (var i = 0; i < url.length; i++) { var XHR = $.get(url[i], function(data) { //do something }); } I attemp ...

What is the necessity of explicitly requesting certain core modules in Node.js?

The documentation explains that certain core modules are included in the Node.js platform itself and are specified within the source code. The terminology can get a bit confusing when it comes to details. The term "global objects" (or standard built-in obj ...

Mastering the art of building a datepicker: A comprehensive guide

Looking for advice on how to create a datepicker in HTML without relying on bootstrap or pre-built JavaScript and CSS. I am interested in learning the process from the ground up and understanding how developers have designed these tools. I am specifically ...