Retrieving data from various schemas using Node.js

I am managing two schemas, one for employees (parent) and the other for assessments (child). Each assessment is linked to an employee ID with a pass percentage.

Here are some sample data:

employees : [
  {
    "_id": 12345,
    "name": "David",
    "evaluated": false
  },
  {
    "_id": 12346,
    "name": "Miller",
    "evaluated": false
  }
]

Second Schema

assessments: [
  {
    "assessment_type": "basic",
    "employee_id": 12345,
    "qualified": true
  },
  {
    "assessment_type": "advanced",
    "employee_id": 12345,
    "qualified": false
  },
  {
    "assessment_type": "basic",
    "employee_id": 12346,
    "qualified": true
  },
  {
    "assessment_type": "advanced",
    "employee_id": 12346,
    "qualified": true
  }
]

I am trying to retrieve a list of evaluated employees based on their assessments where qualification status is true.

Could you suggest the best approach for achieving this?

Answer №1

Here's an illustration of how we can organize employees based on their assessment results.

const employees = [{
  _id: 12345,
  name: 'David',
  evaluated: false,
}, {
  _id: 12346,
  name: 'Miller',
  evaluated: false,
}];

const assessments = [{
  assessment_type: 'basic',
  employee_id: 12345,
  qualified: true,
}, {
  assessment_type: 'advanced',
  employee_id: 12345,
  qualified: false,
}, {
  assessment_type: 'basic',
  employee_id: 12346,
  qualified: true,
}, {
  assessment_type: 'advanced',
  employee_id: 12346,
  qualified: true,
}];

// Loop through the employees
const sortByAssessment = employees.reduce((tmp, x) => {
  // Retrieve all assessments related to the employee
  const employeeAssessment = assessments.filter(y => y.employee_id === x._id);
  
  // Handle each assessment
  employeeAssessment.forEach((y) => {
    // Process only successful assessments
    if (y.qualified) {
      // Check if this is the first encounter with the assessment_type
      // create an array to store employee information
      tmp[y.assessment_type] = tmp[y.assessment_type] || [];
      
      // Add the employee's name to the assessment type array
      tmp[y.assessment_type].push(x.name);
    }
  });
  
  return tmp;
}, {});

console.log(sortByAssessment);

Answer №2

There are two methods to achieve this: you can either join with $look up or populate with the employee id.

assessments.aggregate([
        {
            '$lookup': {
                'from': 'employees',
                'localField': 'employee_id',
                'foreignField': '_id',
                'as': 'datas'
            }
        },
     { "$unwind": "$datas" },


].exec(function(err,result){
   console.log(result)
});

Second approach

// Replace 'assessments' with your model name

      assessments.populate('employee_id').exec(function(err,result){
           console.log(result); 
     });

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

Unable to upload gathered email to Mailchimp mailing list through Nodejs and express API

Seeking guidance on integrating data collection with Mailchimp in a Nodejs backend project. I am currently working on an email signup list page where users input their first name, last name, and email. The HTML file contains fields named firstName, lastN ...

Node generates parallel instances of mysql connections and fails to terminate them afterwards

I am currently working on a project that involves using loopback, node, and MySQL to make parallel database calls. Even though there is already a persistent connection established between node and MySQL, when these parallel calls are executed, new connecti ...

Passing the socket.io instance to an express route

I am currently working on developing a nodejs application that will utilize various web APIs to search for information. The goal is to send the results to the client in real-time using socket.io, with jQuery handling the front end display of the data. Wha ...

Managing multiple NodeJS applications simultaneously

Is it feasible to execute 3 or more nodeJS Applications using a single command through a shell script? The concept involves having a shell script that navigates into the app directories and runs the npm command. Using the npm package concurrently is not ...

What could be the reason for my Express server returning a 404 error for all files other than index.html?

Currently, I am delving into Node.js with Express in order to set up a small server for educational purposes. Strangely, every request made to files linked within my index.html file, such as the .css, .js, and image files, results in a response code 404. ...

npm audit failing to detect resolved issues at a lower level

Currently facing a challenge with resolving a warning flagged by npm audit. After tracing the path to the dependent package causing the issue, I executed the recommended fix command to update the problematic dependency package. The directory structure app ...

Guide on routing a websocket connection through a proxy server

Encountering an issue with github.com/facebook/create-react-app, particularly when proxying the webpack-dev-server with a custom server. While HTTP requests work fine, WebSocket requests fail with this specific error: WebSocket connection to 'ws://l ...

Expanding WebSocket functionality on Heroku with Node.js

Imagine a scenario where I have a substantial application managing numerous websocket connections on Heroku. To handle this high demand, the number of dynos is increased to N. How does Heroku's router distribute these new incoming websockets connecti ...

When sending a form with a POST request in NODE, the data can be missing

I'm having trouble with setting up routes in an API and getting data from simple forms. Take a look at this basic HTML form: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>test form</titl ...

Webduino successfully accepts POST parameters from curl, but is unable to receive them from Node

Check out the code snippet below to see the Arduino in action using the Webduino library: void handleConfigRequest(WebServer &server, WebServer::ConnectionType type, char *, bool) { // Processing POST request for new configuration if (type == WebServ ...

Having trouble accessing environment variable in NodeJS with ExpressJS

In my Express.js project, I have set a variable like this: app.set('HOST', 'demo.sample.com');. However, when I try to access this variable, I am getting undefined as the result. I am trying to retrieve the value using process.env.HOST. ...

Having trouble locating the web element within a div popup while utilizing Node.js and WebdriverIO

I need assistance with a seemingly simple task. I am currently learning webdriverjs and attempted to write a short code to register for an account on the FitBit website at URL: www.fitbit.com/signup. After entering my email and password, a popup appears as ...

Browsing data privacy is crucial, which is why I have decided to operate both servers on the same port to ensure that cookies are

In my project, the front end is built with Next.js and the backend uses Express and Node.js. These projects are currently running on different ports - the frontend on port 3000 and the backend on port 8080. While everything works fine locally and cookies a ...

There is no compatible version available for @typescript-eslint/[email protected]

I am encountering the following issue when trying to create a new app or running npm install. I need assistance in resolving this error. I have also attempted using the command below but the error persists. npm install -g create-react-ap Installing packa ...

The React application is experiencing delays in launching the development server

I have implemented a react dashboard template that I purchased from a themeforest. Here is the snapshot of the package.json: { "name": "acorn-react", "version": "1.0.1", "private": true, "proxy&quo ...

Error encountered during deployment of Cloud Functions due to missing dependencies in monorepository

I am facing an issue with my monorepo setup where my cloud functions are importing from another package within the workspace. The imported package is listed in the package.json under devDependencies as shown below: // stuff "dependencies": { &q ...

Authentic edition of link with node v0.8.1

Seeking advice on compatibility between connect v2.3.5 and Node 0.8.1, has anyone tested this combination for stability? I am currently working with express v2.5.11 on Ubuntu 11 and open to using an older version of connect that is compatible with node 0 ...

Develop an extensive Typescript and React shared library

Trying to develop a shared React and Typescript library has been quite challenging. Configuring the project workspace to work on both the library and application simultaneously has proven to be more difficult than anticipated. project ├─ app │ ├ ...

The Node.js application is having trouble connecting to the Angular application on port 3000 when the Angular app is hosted on a remote machine

I'm facing an issue with my Nodejs app not being able to connect with the Angular app on port 3000 when the Angular app is hosted on a remote machine. However, everything works fine when both apps (Nodejs and Angular) are hosted on the same machine. C ...

Using NodeJS to initiate a file opening operation

Can someone please guide me on how to open a file using nodejs without using exec? Specifically, I need to run a nodejs file that will automatically open a specific file stored on my local hard drive. I want to ensure that this process is secure and reliab ...