What is the best way to set up a .find() method that accepts an array of values and outputs an Object containing key-value pairs?

Is there a more efficient method to fetch multiple key-value pairs in an array of objects from MongoDB?

I aim to create a function that takes an array of values to search for (e.g. an _id) and returns an Object with key-value pairs where the key is the original search term.

The data structure could be like this:

'users': [
        {
          _id: '123',
          displayName: 'John Doe',
          timezone: 'America/New_York',
        },
        {
          _id: '456',
          displayName: 'Jane Doe',
          timezone: 'America/New_York',
        },
        {
          _id: '789',
          displayName: 'Ken Watanabe',
          timezone: 'America/New_York',
        }
       ]

An example input: ['123','789']

The desired output:

{
  '123':{
          _id: '123',
          displayName: 'John Doe',
          timezone: 'America/New_York',
        },
  '789':{
          _id: '789',
          displayName: 'Ken Watanabe',
          timezone: 'America/New_York',
        }
}

The retrieved data matches the search parameters and the searched value becomes the new corresponding key.

Currently, I am using:

let data = await db.collection(collection).find( { _id : { $in : _ids }  }).toArray();

However, this stores the data in an array of Objects:

[
        {
          _id: '123',
          displayName: 'John Doe',
          timezone: 'America/New_York',
        },
        {
          _id: '789',
          displayName: 'Ken Watanabe',
          timezone: 'America/New_York',
        }
       ]

This can be parsed using Object.entries(), but perhaps there is a more effective way to retrieve the data.

Edit: Marcus has provided a great solution below if you need to solve this issue server-side. Make sure to check it out.

To clarify, I seek a solution that obtains the desired output directly from the database without post-arrival modifications.

Sergio suggested using .aggregate(), which I will explore now. If I find a solution before others do, I will update with an answer.

Answer №1

Here's a simple solution:

let output = {};
people.forEach((person) => {
  output[person.id] = person;
});

Answer №2

Utilize the reduce() method for iteration along with the spread {...} syntax to build up a new array of objects

let users = data.users.reduce((b, a) => 
   (search.includes(a._id) ? // check if user id is in search array
   { ...b, ...{[a._id]: a}} : b) // merge current object with new user object
   , {})

let data = {
  users: [{ _id: '123',displayName: 'John Doe',timezone: 'America/New_York'},
    {_id: '456',displayName: 'Jane Doe',timezone: 'America/New_York'},
    {_id: '789',displayName: 'Ken Watanabe',timezone: 'America/New_York'}]}
let search = ['123', '789'];
let users = data.users.reduce((b, a) => 
   (search.includes(a._id) ? 
   { ...b, ...{[a._id]: a}} : b)
   , {})

console.log(users)

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

The session feature in Express is malfunctioning

Incorporating express-session into my app, I attempted the following proof of concept (POC):. server.js app.use(session({ secret: 'pal!lap789', // create new redis store. store: new redisStore({ host: 'localhost ...

Retrieve the position with respect to the browser viewport

My current scenario involves two divs, with one nested within the other. The task at hand is to determine the position of the child div in relation to the browser window. Specifically, I aim to detect when the user scrolls down and have the child div fade ...

Nodejs controller unable to successfully pass variables to the view

I'm facing an issue with passing a variable from a controller to a view in Nodejs. Currently, I am using Express for my routing: app.get('/search/:id', function(req,res){ searchController.findByName(req, res); // console.log(res); ...

Preventing Further Navigation When an Incorrect Password is Entered

I am struggling with preventing navigation when a user enters the wrong password in my app. Despite trying to implement an If condition, the redirection still occurs after catching the error. Here is the code snippet I have been working with: login = (em ...

The time zones between Node 8 and Node 11 are not the same

Executing a basic new Date().toString() command produces different results on Node 11 compared to Node 8. In Node 11, the output includes the full timezone abbreviation like this: 'Fri May 10 2019 10:44:44 GMT-0700 (Pacific Daylight Time)' On t ...

The rate at which the MongoDB replica set OpLog Gb/Hour is surging has sparked a quest to pinpoint the

ISSUE The MongoDB (v 2.6.6) three node replica set OpLog Gb/Hour has been steadily increasing over the course of several days, starting from 20mb per hour which was maintained for months. I am currently investigating the root cause behind this sudden spik ...

Struggling to populate dropdown with values from array of objects

My issue is related to displaying mock data in a dropdown using the SUIR dropdown component. mock.onGet("/slotIds").reply(200, { data: { slotIds: [{ id: 1 }, { id: 2 }, { id: 3 }] } }); I'm fetching and updating state with the data: const ...

Using NodeJS to fetch external page data and return Javascript variable information

I need to retrieve the entire DOM of a specific page by sending a request, essentially crawling the website. The HTML directly includes a variable with some data, instead of it being in a separate script file. With my NodeJS backend, I am utilizing request ...

What is the best way to showcase a JSON object in an attractive format on a webpage?

Similar Question: JavaScript data formatting/pretty printer var theobject_string = '{...}'; // I have a JSON object as a string. Is there a way to present this string in a visually appealing manner on an HTML webpage? I would like the ...

JavaScript Language Conversion Templating

I'm currently revamping the frontend for Facebook's internationalization XFBML tag, which has been nonfunctional for a while. I'm almost done with the updates but I have hit a roadblock: swapping out tokenized translations without losing dat ...

What is the best way to implement external routes.js files in order to avoid defining all routes within app.js?

Looking to create a basic link in Express? Follow these steps: a(href='/test', title='View test page') Test First, add a new file named test.js under the /routes directory with the following code: /* * GET test page. */ exports.test ...

Formatting parameters for a SOAP client in Node.js

I am struggling with formatting a specific soap parameter correctly using the node-soap module in node.js as a client, for a SOAP service from a third-party. According to the client.describe() method, this particular input should follow this structure: p ...

Setting overflow sizes manually for parent containers when child elements are transformed using CSS can be done by following these steps

It has come to my understanding that CSS transforms do not impact the actual size of an element, rather its visual representation. There have been discussions on this topic: CSS Scale transform on child not affecting parent size CSS transform: scale does ...

AngularJS $http.delete encountered an error with the message "An error occurred while trying to assign a value to a read-only property 'method'."

Hello, I am diving into the world of JavaScript and AngularJS. Currently, I am working on building a simple CRUD application. Below is the code snippet from my controller: (function() { var app = angular.module('form.user', []); app.dir ...

Converting MySQL tables into JSON files

Currently, I am working on a remote CentOS machine without graphical access, relying solely on the terminal. On this machine, there is a MySQL database with a table from which I am fetching the first 10 entries using the command SELECT * FROM MY_TABLE LIMI ...

Enhance Parameter Typing with Swagger and NSwag

We have integrated swagger/nswag for documenting a webapi project. When defining BodyParameters for the ActionMethods, we use classes with the suffix Command that include parameters for tasks such as creating a Domain-Object that is persisted in a databas ...

Effectively eliminating elements from the DOM

I have a minor question about efficiency in regard to implementing an overlay and spinner over an element. Initially, I am adding the overlay and spinner, and then later I am removing them. I can approach this in two ways: addSpinner: function() { ...

Utilizing jQuery for validating latitude and longitude coordinates with regular expressions

I implemented jQuery validation in the following way: $("#register-form").validate({ rules: { latitude: { required: true, strongCoord: true }, longitude: { required: true, strongCoord: true } }, messages: { yrAr: { required: &a ...

Following the execution of an AJAX request, the jquery script fails to run

I've encountered an issue with my website that utilizes pagination, filtering with jQuery and AJAX. Everything was functioning smoothly until I decided to switch my links to JavaScript links. When on the homepage without any filtering or pagination a ...

Guide on embedding a map inside a popover using Bootstrap

I am trying to create a popover that displays a map inside it. I attempted this simple example: <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" c ...