What is the best way to fill in and subsequently find matches using the 'parent' identifier?

I am currently working on associating a populated referenced document with the parent document id. The main objective is to display only the membership permissions related to a specific organization, rather than showing all other permissions that may exist. This means that the 'entity.item', which represents an organization in this case, should be linked to the parent organization id. I am exploring ways to access the parent organization id from a child document.

let userId = '123';
let organizations = await Organization.find().where('members.includes(userId)').populate({
    path: 'members',
    options: { sort: { name: 1 } },
    populate: {
      path: 'permissions',
      match: {
        'entity.kind': 'Organization',
        'entity.item': organization._id  //HERE
      },
      populate: {
        path: 'entity.item'
      }
    }
  });

Answer №1

After experimenting with the lookup operator in the aggregate method, I have found that it is indeed working well in various test scenarios. Credit goes to the following answer for pointing me in the right direction:

"Utilizing the $lookup syntax introduced in mongodb 3.6 and above makes it straightforward to join nested fields without the need for $unwind."

let organizations = await Organization.aggregate([
  { $sort: { name: 1 } },
  { $match: { $expr: { $in: [ user.id, '$members' ] } } },
  {
    $lookup: {
      from: 'user',
      let: { id: '$_id', members: '$members' },
      pipeline: [
        { $match: { $expr: { $in: [ '$_id', '$$members' ] } } },
        { $addFields: { id: '$_id' } },
        {
          $lookup: {
            from: 'permission',
            pipeline: [
              { $match: { $expr: { $and: [
                { $eq: [ '$entity.kind', 'Organization' ] },
                { $eq: [ '$entity.item', '$$id' ] }
              ] } } },
              { $addFields: { id: '$_id' } },
              {
                $lookup: {
                  from: 'organization',
                  pipeline: [
                    { $match: { $expr: { $eq: [ '$_id', '$$id' ] } } },
                    { $addFields: { id: '$_id' } }
                  ],
                  as: 'entity.item'
                }                      
              }
            ],
            as: 'permissions'
          }
        }
      ],
      as: 'members'
    }
  },
  { $addFields: { id: '$_id' } }
]);

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

Using Typescript generics to enhance arrays

I am looking to extend a generic list of Array that has been previously extended from my class. How can I accomplish this in the correct way? export interface DeliveryMethod { readonly id: string; readonly company: string; readonly cost: number; re ...

updating specific keys of nested object in mongoose document

I need to update specific fields of a mongoose document based on provided keys. For example, If we represent a mongoose document in json as: user: { address: { city: "city" country: "country" } } and the update parameters are given as: addre ...

Each instance of the same class receives a unique version

Within my codebase, I have a private package that exports a class called Table. Another package in use also utilizes this class, as does my web application. One of the test cases inside the second package looks like this: if (!(table instanceof Table)) { ...

Adding a UUID to the data.json file using Node.js - A step-by-step guide

Currently, I have a data set stored in the data.json file and I am looking to add a 'uuid' field to each record. The project I am working on is built using Node.js. To read the file, I can utilize the following code snippet: module.exports.api ...

Encountered an abrupt termination of JSON input while implementing Promise.all() alongside the fetch method's put operation

Encountered an issue with JavaScript while attempting to retrieve mail content from an API and update its read status simultaneously. The error message displayed in the console is: SyntaxError: Unexpected end of JSON input at inbox.js:98 The error pro ...

Utilizing Object Arrays in Chart.js for Optimal Performance

I'm struggling with using chart.js to create charts for my admin panel. I'm having trouble figuring out how to properly utilize my JSON array of objects in order to generate the correct dataset. What exactly should I be putting in the data field ...

Choosing a value using Jquery on change is not effective

NOTE: Unnecessary information has been removed I am looking to select the parent element when the value of a select element is changed, and then serialize that parent: jQuery('body').on('change','.shop_table select',function ...

Replacing JS/CSS include sections, the distinction between Debug and Release versions

Can you share how you manage conditional markup in your masterpages for release and debug builds? I am currently using the .Net version of YUI compress to combine multiple css and js files into a single site.css and site.js. One idea I had was to use a u ...

How can I generate cone shape with rectangular base using three.js?

Interested in building a Cone Geometry with a rectangular base in three.js. Any tips on how to get started? I've included an image to help visualize what I'm trying to achieve. ...

Finding values within array elements in mongoose documents

Let's consider a scenario where we have a collection of updates in a database with the following schema: { _id: Number, isRead: [] } Now, let's assume that our data consists of the following information: { _id: 1, isRead: [1,2], ...

Is there a way to display a modal before redirecting to the next page after clicking a submit button in a rails application?

In the scenario where I have two models, Employer and Jobs, consider this situation: an Employer creates an account to post a job and provides their phone number. When they fill out a new job posting and click on the post job button (Submit button), I need ...

Using SignalR 2.0 to connect to a hub without relying on a proxy

By using the HTML/JS code below, I have been able to successfully connect to my SignalR 2.0 hub when both the HTML/JS and hub are on the same server. <!DOCTYPE html> <html> <head> <title>Test SignalR 2.0</title> <style typ ...

Using a try catch within a try catch block along with the Mongoose library and Express

Looking for the most efficient solution here. Can I achieve the desired outcome with just one try catch block, or do I need to nest try catch within try catch? I'm currently working with express and mongoose for mongodb. try { const savedR ...

Which is Better: Lazy Loading, Combining and Minifying, or Using a CDN for Javascript in Angular

When is it advisable to utilize a CDN for loading a JavaScript file? Are there specific files that should be lazy loaded? Additionally, which scripts would benefit from being combined and minified? For instance: jquery + jquery plugins - Should thes ...

Convert this text into HTML code: "Textarea to

I have a basic <textarea> element that I want to transform links (www.google.com, msn.com, etc) and line breaks (\r\n) into HTML code. I found one library for converting links into <a hrefs>. Another library can convert line breaks i ...

I am seeking assistance with incorporating mySQL into my Node.js project with React

Currently, I am working on a web-app utilizing Node.js. The main goal is to retrieve information from my local database in MySQL Workbench. Initially, I decided to focus on building the frontend interface before diving into implementing the functionality s ...

What is returned if Select is an empty string in a Mongoose Model.find() query?

Let's consider a scenario where we have a basic schema set up like this: const phoneRegex = require('./phoneRegex'); const Schema = require('mongoose').Schema; const PersonSchema = new Schema({ firstName: String, lastName: Str ...

What prevents me from displaying the image in the Bootstrap tooltip?

I am currently utilizing the Bootstrap framework v3.3.0 for my website. I'm trying to implement an image as a tool-tip when the user hovers their mouse pointer over an icon. Here is the HTML code I have: <div class="col-sm-5"> <div class= ...

Creating dynamic visual representations of algorithms using JavaScript

I am currently exploring how to create animations for algorithms using JavaScript. I'm curious about the process of creating algorithm animations in other languages, such as Java. Is the animation aspect typically separate from the algorithm logic? Fo ...

Does the onchange function in the dropdown list only work when the first item is changed?

Here is a snippet of my HTML code featuring a list item generated from a database using a foreach loop: <select class="form-control select" id="inventoryitem" name="inventoryitem" onchange="getunit();"> <option>---Select an item---</o ...