Return only the documents in MongoDB where the user in one document does not match a specific field in another document

JS Function:

function findUsersWithoutProject(req, res, next) {
      try {
        let benchUser = [];
        const project = await Project.find({})
        const users = await User.find({}, {
          email: 1,
          _id: 0
         })
  
        for (let i = 0; i < users.length; i++) {
          for (let j = 0; j < project.length; j++) {
            for (let k = 0; k < project[j].seats.length; k++) {
              if (users[i].email !== project[j].seats[k].employee && project[j].seats[k].employee === undefined) {
                benchUser.push(users[i].email)
              }
            }
          }
        }
  
        const uniq = [...new Set(benchUser)];
  
        return res.json({
          users: uniq
        })
      } catch (error) {
        next(error)
      }
    }
    

User Emails:

[{ 
     email: 'example1@example.com',
   }, { 
     email: 'example2@example.com',
   }, {
     email: 'example3@example.com' 
   }]
  

Projects Information:

{ _id: 5cc2dd2eb3eea7004c9a7240,
      name: 'Project One',
      description: 'Lorem Ipsum',
      start: '2018-06-01T09:45:00.000Z',
      end: '2019-12-31T09:45:00.000Z',
      seats:
       [ 
         { 
           skills: [Array],
           _id: 5cc2e3cab3eea7004c9a724a,
           start: '2018-06-01T09:45:00.000Z',
           end: '2019-12-31T09:45:00.000Z',
           potentialExtension: '2020-06-31T09:45:00.000Z',
           role: 'Dev',
           approved: true,
           workload: 10,
           employee: 'employee1@example.com' 
         },
         { 
           skills: [Array],
           _id: 5cc2e3cab3eea7004c9a7241,
           start: '2018-06-01T09:45:00.000Z',
           end: '2019-12-31T09:45:00.000Z',
           potentialExtension: '2020-06-31T09:45:00.000Z',
           role: 'PM',
           approved: true,
           workload: 20,
           employee: 'employee2@example.com' 
         }
       ]
    }
    

Objective:

In this scenario, the goal is to retrieve all users who are not assigned to any project seat.

The function iterates through each user and project's seats to check for a match in the email field.

The returned list of users without projects includes 'employee1@example.com' but erroneously also lists 'employee2@example.com'.

Answer №1

To meet your needs, utilize: Array.prototype.filter along with Array.prototype.includes

let users = [{ 
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2d7d1c7d093e2c7cfc3cbce8cc1cdcf">[email protected]</a>',
}, { 
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86f3f5e3f4b4c6e3ebe7efeaa8e5e9eb">[email protected]</a>',
}, {
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="66131503145526030b070f0a4805090b">[email protected]</a>' 
}];

let projects = [{ _id: '5cc2dd2eb3eea7004c9a7240',
  name: 'Project One',
  description:
   'Lorem Ipsum',
  start: '2018-06-01T09:45:00.000Z',
  end: '2019-12-31T09:45:00.000Z',
  seats:
   [ 
     { 
       skills: [Array],
       _id: '5cc2e3cab3eea7004c9a724a',
       start: '2018-06-01T09:45:00.000Z',
       end: '2019-12-31T09:45:00.000Z',
       potentialExtension: '2020-06-31T09:45:00.000Z',
       role: 'Dev',
       approved: true,
       workload: 10,
       employee: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6a3a5b3a4e796b3bbb7bfbaf8b5b9bb">[email protected]</a>' 
     },
     { 
       skills: [Array],
       _id: '5cc2e3cab3eea7004c9a7241',
       start: '2018-06-01T09:45:00.000Z',
       end: '2019-12-31T09:45:00.000Z',
       potentialExtension: '2020-06-31T09:45:00.000Z',
       role: 'PM',
       approved: true,
       workload: 20,
       employee: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f88d8b9d8acbb89d95999194d69b9795">[email protected]</a>' 
     }
   ]
}];

let projectUsers = new Set();
projects.forEach(({seats}) => {
seats.forEach(({employee}) => projectUsers.add(employee));
});

let out = users.filter(({email}) => !Array.from(projectUsers).includes(email));
console.log(out)

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

REGEX: All characters that appear between two specified words

Is it possible to use Regex to select all characters within the designated words "Word1 :" and "Word2 :"? I am looking to extract any character located between these two specific phrases. Word1 : Lorem ipsum dolor sit amet consectetur adipiscing elit ...

Creating an object in real-time

Is there a way to dynamically create objects in JavaScript? My Expectation var tree_data = { 'for-sale': {name: 'For Sale', type: 'folder'}, 'vehicles': {name: 'Vehicles', type: 'folder' ...

Dealing with TypeScript and the Mongoose loadClass problem

Working with Mongoose's class schemas has been very beneficial for me. Incorporating TypeScript into my Node project has enhanced the development process. I made sure to refer to Mongoose the Typescript way...? in order to ensure that my Model align ...

Chrome hanging after AJAX delete operation has been executed

After conducting a same-origin AJAX delete using jQuery, any subsequent calls made by the same client to the server are getting stuck. The specific issue is outlined below. Can you please review and let me know if there's something incorrect, as this ...

What causes the e.preventDefault function to override all subsequent lines of code?

Placing the e.preventDefault() after the code allows it to work, but results in a page refresh. If I keep it at the beginning of the code, it prevents the other lines from executing and doesn't send the request. function loadPhoto(e){ e.prevent ...

reduce input to 2 characters using jQuery

Is there a way to trim the input text down to just the first two characters when a button is clicked? For example, if I enter "BT2J43" into the input field, can it be automatically shortened to "BT" upon clicking the button? I'm new to learning jQue ...

encountering validation error during transmission of data through POST request

Creating a Mongoose Model const mongoose=require('mongoose'); const validator=require('validator'); const employeeSchema=new mongoose.Schema({ name:{ type:String, required:true, trim:true }, email ...

Ways to transfer information among Angular's services and components?

Exploring the Real-Time Binding of Data Between Services and Components. Consider the scenario where isAuthenticated is a public variable within an Authentication service affecting a component's view. How can one subscribe to the changes in the isAut ...

The jade code is causing an error to be displayed

The following Jade code seems to be malfunctioning. head script(src='http://d3js.org/d3.v3.min.js') script(src='http://dimplejs.org/dist/dimple.v2.1.0.min.js') body script(type='text/javascript') var svg ...

Transferring data from one of the three submitted forms by utilizing jQuery's AJAX function

Currently, I am facing a challenge with three forms on a website, where two of them are located in modal windows. My goal is to use ajax to send input values such as name, phone, email, and radio button selections (which vary in each form). However, I have ...

Achieve text length that does not exceed the specified limit dynamically

Is it possible to determine the length of the visible portion of text that overflows (or calculate the size of the overflow for further processing) using CSS or JavaScript? If so, can this calculation be done dynamically (such as on window resize)? The g ...

Efficiently storing multiple nested struct values in MongoDB using Go

I am attempting to add multiple values with nested struct in MongoDB using Golang ... For example { "_id" : ObjectId("56b879528d04effa4ae2de2c"), "task_content" : "Some text", "priority" : "2", "deadline" : { "start_time" : ISODate("20 ...

Tips for resetting the mapbox geocoder

Using the Mapbox Geocoder along with multiple select menus to customize a map has been my latest project. I am currently working on resetting the geocoder once a user selects an option from the menu, clearing the input field and removing the marker in the ...

Is Asp.net 4 resetting the array with every new run?

I have developed a basic asp.net web page to generate HTML content. The concept is to store previous user inputs in an array each time they click a button, and display them along with the most recent input. However, I encountered an issue where the array a ...

Guide to showcasing console output on a Web Server

Apologies if this question is not the most suitable for this platform. I recently set up Pure-FTPd service on a CentOS server. To check current connections, I use the command pure-ftpwho, which gives me the following output: +------+---------+-------+---- ...

An unexpected 'undefined' value is being added to a particular Web API request

I am encountering an issue in my Angular application where the word 'Undefined' is being appended to a specific WebAPI call, causing both registerUser and login requests to fail. Here are the problematic request URLs: Request URL: http://localho ...

After props have been passed, the ReactJS ComponentWillMount() function is triggered

Can anyone explain why the child component is only rendered once, even though I pass props to it every time I click a button? Whenever I click a button that passes props to the child, the ComponentWillMount() method of the child component doesn't tri ...

Adding query parameters dynamically in Vue without refreshing the component

I'm attempting to update the Query Parameters in Vue without refreshing the component using Vue-Router. However, when I use the code below, it forces a component reload: this.$router.replace({query: this.filters}); Is there a way to prevent the comp ...

Enhance the current model in backbone.js by incorporating additional data

When a user selects an item on the webpage, more details need to be fetched and displayed. The API function /api/full_details has been implemented to return the additional data for that item. Challenge: How can I retrieve the additional data and append it ...

What is the best way to dynamically load a view within a modal based on the clicked link?

I'm looking to optimize the loading of views inside a modal for various operations. Instead of having three separate modals, I want to dynamically load the views based on the link that is clicked. How can I achieve this? Or should I create individual ...