Exploring Nested Data in MongoDB Aggregation using $match and $project

Struggling with crafting a Mongoose Aggregate Query to extract the permissions object of a specific member within a deeply nested structure of business data. MongoDB's documentation on this topic is lacking, making it hard for me to progress.

Sample Collection:

const business = [
    {
      b_id: ObjectId("a"),
      locations: [ 
        {
           l_id: ObjectId("b"),
           teams: [ 
               {
                  t_id: ObjectId("c"),
                  members: [ 
                        {
                            m_id: ObjectId("d"),
                            permissions: { 
                              p1: {
                                a: true,
                                b: false,
                                c: true,
                                d: false,
                              },
                              p2: {
                                a: true,
                                b: false,
                                c: true,
                                d: false,
                              }
                            }
                        }
                  ]
               } 
            ]
        }
      ]
    },
  ]

Expected outcome:

const permissions = {
  p1: {
    a: true,
    b: false,
    c: true,
    d: false,
  },
  p2: {
    a: true,
    b: false,
    c: true,
    d: false,
  }
}

Path:

router.post("/", authUser, (req, res) => {
  const _ids = {
    b_id: req.body.b_id,
    l_id: req.body.l_id,
    t_id: req.body.t_id,
    m_id: req.body.m_id,
  }
  Business.aggregate([
    {
      $match: {
        b_id: ObjectId(_ids.b_id),
      },
    },
    {
      $project: {
      //stuck on projecting the permissions object for the specified member
      },
    },
  ]).then((perms) => {
    console.log(perms);
  });
});

Any guidance would be greatly valued, thank you!

Answer №1

After some trial and error, I managed to come up with a solution that may not be the most elegant, but it does get the job done. Is there perhaps a more efficient way to approach this problem?

router.post("/", authUser, (req, res) => {
  const _ids = {
    b_id: req.body.b_id, //business _id === "a"
    l_id: req.body.l_id, //locations _id === "b"
    t_id: req.body.t_id, //teams _id === "c"
    m_id: req.body.m_id, //members _id === "d"
  }
  Business.aggregate([
    {
      $match: {
        b_id: ObjectId(_ids.b_id),
      },
    },
    {
      $unwind: "$locations",
    },
    {
      $match: {
        "locations.l_id": ObjectId(_ids.l_id),
      },
    },
    {
      $unwind: "$locations.teams",
    },
    {
      $match: {
        "locations.teams.t_id": ObjectId(_ids.t_id),
      },
    },
    {
      $unwind: "$locations.teams.members",
    },
    {
      $match: {
        "locations.teams.members.m_id": ObjectId(_ids.m_id),
      },
    },
    {
      $project: {
        permissions: ["$locations.teams.members.permissions"],
      },
    },
  ]).then((perms) => {
    res.status(200).send(perms[0].permissions[0]);
  });
});

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 react-router-dom seems to be malfunctioning, so let's simply render the "/"

Struggling to render multiple pages in React, I am a newbie and have been exploring various tutorials and pages. My stack includes React, Webpack, Babel, and ESLint with Airbnb configuration. When I render my React app, it appears like this. View of the ...

Storing Data in Arrays with Node.js and Express: The Guide to Preventing Rendering in a Web Browser's DOM

My Node.js route in Express is functioning properly by retrieving data from a database. app.get('/getdata/:key', function(req, res){ console.log("Search key(s):", req.originalUrl.split("/")[2]); keys = req.originalUrl.split("/")[2] Keys ...

Difficulties encountered when adjusting the size or reducing the images in a Cycle2 slideshow

Greetings to all fellow coders! Thank you for taking the time to read this post. I am currently facing a challenge in my web development project where I am trying to make my Cycle 2 slideshow images resize and reposition alongside other divs when the wind ...

The functionality of Router.push() seems to vary depending on the timing

I'm attempting to utilize router.push() to modify the URL when the Search button is clicked. However, I've encountered a situation where this function only works sporadically. Ideally, after clicking the button, the user should be directed to the ...

Sorting Vue.js properties based on object keys

Currently, I am dealing with a complex object that contains multiple network interfaces. Each interface is represented by a key-value pair in the object: https://i.stack.imgur.com/klkhH.png My goal is to create a Vue.js computed property that filters thi ...

Implementing a FadeOut effect for the clicked link

When clicking on each link, I want the same link to fadeOut() after clicking on the ok button in the myalert() function. If clicked on cancel, it should not fadeOut(). How can I achieve this using the myalert() function? For example: http://jsfiddle.net/M ...

Is ASP.NET capable of displaying an expandable grid view?

After searching online, I have yet to find a solution that meets my requirements. Currently, my DB view generates the following data: --------------------------------------------------- Company | Code | Total | Available | Used | Needed ---------------- ...

Discovering the method for retrieving post parameters in Node.js

I am currently utilizing Node.js with Express and the httpAsyncClient library in Android. I have sent a request to Express using Post, including parameters. The request goes through successfully, but I am unable to retrieve the parameter in Post. I have ...

Tabulator: the process of loading an extensive amount of data requires a significant amount of time

Currently, I am encountering an issue with loading data using a tabulator on my webpage. There are 38 tables that need to be populated, each containing approximately 2000 rows of data. The problem lies in the fact that it is taking an excessive amount of t ...

Unable to locate module using absolute import in a Next.js + TypeScript + Jest setup

Currently in my NextJS project, I am utilizing absolute imports and testing a component with Context Provider. The setup follows the instructions provided in this jest setup guide TEST: import { render, screen } from 'test-util'; import { Sideb ...

Retrieve all elements from the array using mongoose query

Is there a way to query mongoose for every element in an array, which is itself a result of a mongoose query, append the results to each array element, and return the updated array? Service.find(query) .then((servicesList) => { const result = ...

Can you explain the functionality of that snippet of JavaScript code?

Can you figure out the value of r? How does it relate to Boolean operators and objects? var data = {x:123, y:456}; var r = data && data.x || 0; Update: Upon running the code snippet, I noticed that r consistently equals x. However, the reason behind thi ...

JavaScript Execution Sequence: Demystifying the Order of Operations

I am struggling to comprehend the order of execution in the following code snippet. It is a portion of a larger script, but it all begins with $( "#select-overlay" ). function findSelectedMap(mapID) { $.getJSON('maps.json', function (json) { ...

Creating a dynamic CSS height for a div in Angular CLI V12 with variables

Exploring Angular development is a new venture for me, and I could use some guidance on how to achieve a variable CSS height in Angular CLI V12. Let me simplify my query by presenting it as follows: I have three boxes displayed below. Visual representatio ...

Utilize the power of jQuery to make an ajax request to a PHP backend, expecting a response in JSON format. Then,

Having some trouble with my jQuery code when trying to parse a JSON object returned by PHP and create a list of hyperlinks. Despite receiving the JSON object, my list turns out empty. Can anyone assist me? Below is the jQuery code snippet and the JSON resp ...

If the option is 'Gel', use an if statement to console log

I'm trying to console.log the option from the data() function that is equal to 'Gel'. I attempted to use an if statement, but it doesn't seem to be working. Anyone have any ideas on how to make this work? data(){ return { ...

Headers and data organization in Angular 2

I'm searching for a simple Angular 2 example that demonstrates how to fetch both the headers and data from a JSON API feed. While there are plenty of examples available for fetching data only, I haven't been able to find any that show how to retr ...

Saving form blueprints and operations in a Data Repository

My team and I are working on a sophisticated web application with a complex back end. We have hundreds of form schemas paired with their corresponding return functions, which are triggered upon form submission. These JSON objects dynamically generate forms ...

Using the window.prompt function to send information to specific fields in a MySQL database is not functioning correctly. I am looking for assistance with this issue

Currently, I am attempting to send some data to a server that is MySQL-based. After running the code below, it seems like there are no errors showing up in the console. Can you please review this code and let me know if you spot any issues? I would really ...

What is the process of overriding methods in a function-based component in React?

Overriding in a parent component works when it is a class-based component // Parent Button Class class Button extends React.Component { createLabel = () => { return <span>{this.props.label}</span>; }; render() { return <butt ...