I am facing unexpected results while trying to search for a string array object using elemMatch in Mongoose

I am encountering an issue that I can't seem to resolve. I need to utilize a query search to match the data of one job with user data, but I'm facing some obstacles. The primary challenge is within my query search for the job where the data looks like this.

The problem arises in the searchFilterSkills.searchSkillsOffer where I have an array of objects and I aim to match the name of each one if it exists. However, I'm struggling to iterate through them because I receive an array of Strings with .map() which cannot be iterated upon.

After receiving responses from Fabian, if all elements match, it returns the elements as expected. However, I aim for it to return the object if at least one element matches. I attempted using $in, but it didn't work. Is there another query I can use instead of $all?

Below are the data I am trying to search:

"skillsOffer":[
      {
         "name":"Max",
         "rate":0
      },
      {
         "name":"Test",
         "rate":0
      },
      {
         "name":"Javascript",
         "rate":0
      }
   ],
"country":"DEU",
"postalCode":12345

And here are the user data they possess:

"searchFilter" : {
        "remote" : 0,
        "data" : [
            {
                "region" : [
                    "1"
                ],
                "country" : "DEU",
                "searchActive" : false,
                "postalCode" : "123",
                "available" : {
                    "$date" : 1664955924380
                }
            }
        ]
    },
"searchFilterSkills" : {
    "searchSkillsOffer" : [
    {
        "name" : "Javascript",
        "rate" : 100
    },
    {
        "name" : "Test",
        "rate" : 60
    },
    {
        "name" : "Client",
        "rate" : 0
    }
],

}

In skillsOffer, I aim to only search if the name matches without considering the rate. Furthermore, if remote is set to 1, then conduct the above query without the postal code along with remote or the aforementioned one alongside remote.

async searchUsers(req, res, next) {
        const jobID = req.query.jobID;
        let job = await Job.findById(jobID);
        let postalCode = job.postalCode;
        postalCode = postalCode.toString().slice(0, 1);
        let postalCode2 = job.postalCode;
        postalCode2 = postalCode2.toString().slice(0, 2);
        let postalCode3 =  job.postalCode;
        postalCode3 = postalCode3.toString().slice(0, 3);
        let postalCode4 = job.postalCode;
        postalCode4 = postalCode4.toString().slice(0, 4);
        let postalCode5 =  job.postalCode;
        postalCode5 = postalCode5.toString().slice(0, 0);
        let userIds = job.skillsOffer.map(user => user.name).join(", ");
        let users = await User.find({
            "searchFilter.data": {
                $elemMatch: {
                    "$or": [
                        {
                            postalCode: postalCode,
                            
                        },
                        {
                            postalCode: postalCode2,
                        },
                        {
                            postalCode: postalCode3,
                        },
                        {
                            postalCode: postalCode4,
                        },
                        {
                            postalCode: postalCode,
                        },
                        {
                            postalCode: postalCode5,
                        },
        
                    ]
                }
        },
        "searchFilter.data": {
            $elemMatch: {
                country: job.country
            }
        },
    
                    'searchFilterSkills.searchSkillsOffer': {
                    $elemMatch: {
                        name: {
                            $regex: new RegExp(`^${job.skillsOffer.map(jt => jt.name)}`, 'i') 
                        },
                    },

        },
        }); 
        if (job.remote.toString() === "1") {
            users = await User.find({
                "searchFilter.data": {
                    $elemMatch: {
                        "$or": [
                            {
                                postalCode: postalCode,
                                
                            },
                            {
                                postalCode: postalCode2,
                            },
                            {
                                postalCode: postalCode3,
                            },
                            {
                                postalCode: postalCode4,
                            },
                            {
                                postalCode: postalCode,
                            },
                            {
                                postalCode: postalCode5,
                            },
            
                        ]
                    }
            },
            "searchFilter.data": {
                $elemMatch: {
                    country: job.country
                }
            },
    
                "searchFilter.remote": job.remote,
            });
        }

    

        if (!users) {

            res.status(204).json({ error: "No Data" });
            return;
        }
        return res.status(200).send({
            user: users.map(t => 
                t._id
            )
        });
    

    },

Answer №1

If you are looking to match each individual name from the array skillsOffer, you will need to create an $elemMatch object for each name.

The following query can be used in your code to verify if all names are present in the array

searchFilterSkills.searchSkillsOffer
:

{
  'searchFilterSkills.searchSkillsOffer': {
    $all: job.skillsOffer
      .map((user) => user.name)
      .map((name) => ({
        $elemMatch: {
          name: {
            $regex: new RegExp(`^${name}$`, 'i'),
          },
        },
      })),
  },
}

If you want to match any of the names instead, you can use the following code:

{
  $or: job.skillsOffer
    .map((user) => user.name)
    .map((name) => ({
      'searchFilterSkills.searchSkillsOffer': {
        $elemMatch: {
          name: {
            $regex: new RegExp(`^${name}$`, 'i'),
          },
        },
      },
    })),
}

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

Comparable to LINQ SingleOrDefault()

I frequently utilize this particular pattern in my Typescript coding: class Vegetable { constructor(public id: number, public name: string) { } } var vegetableArray = new Array<Vegetable>(); vegetableArray.push(new Vegetable(1, "Carrot")); ...

Preventing the occurrence of [ { "description": null } ] in PostgreSQL with a React application running on http://localhost:3000

While working on my localhost project at port 3000 in the Pern Todo List, I encountered a bug. When I type something and click "Add" using a POST request from my React app, the data should be added successfully. However, when I use Postman to make a GET re ...

Heroku deployment causing React App Axios route to become unresponsive

I'm facing an issue with my application that's built on React and Express. Despite specifying to run on the Heroku port or a local port if running locally, I keep getting an error when using axios.post('/',...) saying: POST http://loc ...

Asynchronous operations in Node.js with Express

Hey, I'm still pretty new to using async functions and I could really use some help understanding how to pass callbacks in async.each for each item to the next level (middleware). Here's the logic: I want to iterate through all items, and if an ...

Sort through various table columns

I am currently utilizing a data table component from Framework7, which is being generated dynamically with JSON data. My goal is to make the column filter input functional within the table. So far, I have succeeded in implementing the filter for the first ...

Issue with inline Javascript not functioning correctly when partial is rerendered in Ruby on Rails version 3.1

I am facing an issue in my project where inline JavaScript in a partial, using some instance variables, does not run when the partial is rerendered after a successful ajax call. Could someone please provide guidance on how to solve this problem? For exam ...

Anchor checkboxes

I am dealing with a large number of checkboxes that are linked to anchors. Whenever a checkbox is clicked, it navigates to the corresponding anchor on the same page. Is there a more efficient way to implement this? With around 50 checkboxes, my current cod ...

When the JS function 'postMessage()' is invoked on an HTML object tag, what specific action does it perform?

Not too long ago, I found myself on a quest to figure out how to trigger the print function on a PDF that I was displaying in Adobe AIR. With a bit of guidance from a helpful individual and by utilizing postMessage, I successfully tackled this issue: // H ...

intl-tel-input's getExtension function is returning a value of 'null'

I've been attempting to retrieve the extension of the mobile number that has been input. All other variables are functioning correctly, but the extension variable is returning a null value. It appears that it is sending a null value to the POST method ...

Is there a discrepancy in the JSON algorithm?

While using google chrome, I encountered the following scenario: I had an object in javascript that looked like this: var b = { text: 'hello world, you "cool"' }; I then used JSON.stringify to convert it to a string and sent it to the dat ...

retrieve a reply from a PHP script and incorporate it into JavaScript following an AJAX request

I've been working with an ajax call and everything seems to be running smoothly thanks to this script: $(document).ready(function() { $('.sortable').sortable({ stop: function(event, ui) { $(ui.item).effect("highlight"); ...

Express.js allows users to define a parent root folder domain

My Express Node.js application is structured as follows: app.get('/', page.index); //Add new, edit and delete form app.get('/approval', page.approval); //Task to approve/reject the subordinate form app.get('/task', page.task ...

Attaching identical class and event handlers to numerous dynamically created elements

I am facing a challenge with the following HTML structure: <a href="#" @click.prevent="toggleClass">Show/Hide</a><br> <li :class="{myClass: showItems}">Item 1</li> <a href="#" @click.prevent="toggleClass">Show/Hide< ...

Using Promises Across Multiple Files in NodeJs

Initially, I had a file containing a promise that worked perfectly. However, realizing the need to reuse these functions frequently, I decided to create a new file to hold the function and used module.export for universal access. When I log crop_inventory ...

"The JQuery .validate method is not compatible with this property or method" - error message displayed

I seem to be facing a problem that I can't seem to solve. I keep getting an error message that says "Object doesn't support this property or method" while using jquery-1.10.4. The .validate method is not functioning properly for me. Any assistanc ...

Ensuring a dependable detection of WebSocket connection status

I've been researching how to create a dependable method for recovering a WebSocket connection. After exploring various options, I discovered that one approach involves sending heartbeats (ping/pong) to the server and monitoring if the entire pong is ...

Having trouble getting a div to slide to the left on hover and collapse on mouseout using Jquery?

Hey there! I need some assistance in completing this code snippet. I have a div with overflow:hidden and a margin-left of 82px. Inside it, there is a share link and a ul list containing three external links. When I hover over the share link, everything w ...

Updating local variable value in Node.js from an event listener

How can I modify a local variable within an event handler, listener, or function? export async function mis() { let result; // <--------- LOCAL VARIABLE I WANT TO MODIFY (currently undefined) const m = await spawn(`/cmd`); m.stdout.on('data ...

What is the process of invoking a node module in an express-rendered view?

Struggling to comprehend how to pass data to my view. Currently integrating the Mozscape node module into an application and unsure of how to send the information to the view. My assumption is that I should create the object in the router, call the functio ...

If the cursor hovers over an image, the onmouseover function does not work properly

Currently, I am developing a PHP page to display data from a database in a tabular format. Each column in the table represents an 'ATC Station'. When active, additional data is displayed upon hovering over the cell. Everything was running smooth ...