How to combine the results of two different queries with mongoose?

P-S

I have 3 models (Project, Organization, User) with the schema show below. I am using mongo version 4.2.0 and Moongoose version 5.1.1.

Question

Given a specific user, how do I query all the projects they have access to:

  • either via a direct role in the project itself

  • or via a direct role in the organization that the project belongs to

A user could have a role in an Organization, but maybe not in one of its projects. Still, the query should be able to fetch these projects (the user has upper level access).

Example

Projects
[
    {    
        "_id" : ObjectId("1184f3c454b1fd6926c324fd"),
        "organizationId" : ObjectId("1284f3c454b1fd6926c324fd"),
        "roles" : [
            {
                user: ObjectId("1314f3c454b1fd6926c324fd"),
                role: 'Bar'
            }
        ]
    },
    {    
        "_id" : ObjectId("1172f3c454b1fd6926c324fd"),
        "organizationId" : ObjectId("1284f3c454b1fd6926c324fd"),
        "roles" : [
            {
                user: ObjectId("1313f4c584b1fd6926c324fd"),
                role: 'Bar'
            }
        ]
    }
]

Organizations
{    
    "_id" : ObjectId("1284f3c454b1fd6926c324fd"),
    "roles" : [
        {
            user: ObjectId("1314f3c454b1fd6926c324fd"),
            role: 'Bar'
        }
    ]
}

Users
{    
    "_id" : ObjectId("1314f3c454b1fd6926c324fd"),
    "name": "Foo"
}

Notes

  • These two projects belong to the same organization.

  • The user "Foo" belongs to this organization, but has direct access to only one of its projects.

  • The query in question should return both projects for the user "Foo".

Should two different queries be combined?

user7364588

Using an aggregation pipeline, you may use this :

db.Projects.aggregate([
  {
    $lookup: {
      from: "Organizations",
      localField: "organizationId",
      foreignField: "_id",
      as: "organization"
    }
  },
  {
    $match: {
      $or: [
        {
          "roles.user": varSpecificUserId
        },
        {
          "organization.roles.user": varSpecificUserId
        }
      ]
    }
  }
]);

Here are EXPLANATIONS from following database data :

Projects
[{
    "_id": "pro0",
    "organizationId": "org0",
    "roles": []
}, {
    "_id": "pro2",
    "organizationId": "org1",
    "roles": []
}, {
    "_id": "pro3",
    "organizationId": "org0",
    "roles": [
      {
        user: "usr2",
        role: "Foo"
      }
    ]
  }
]

Organizations
[{
    "_id": "org0",
    "roles": [
      {
        user: "usr0",
        role: "Foo"
      }
    ]
}, {
    "_id": "org1",
    "roles": [
      {
        user: "usr1",
        role: "Bar"
      }
    ]
  }
]

Users
[{
    "_id": "usr0",
    "name": "User0"
}, {
    "_id": "usr1",
    "name": "User1"
}, {
   "_id": "usr2",
   "name": "User2"
}, {
    "_id": "usr3",
    "name": "User3"
}]
  • Let's call varSpecificUserId the specific user' _id.
  • $lookup query an other collection using localField from Projects collection matching with a foreignField from Organizations collection.
  • The result of $lookup is an array of all Organizationsthat match the organizationId if each Project. This array is stored at organisation using the as keyword of the $lookup object. Here is an ex. of query object at this step:
{
    "_id": "pro0",
    "organization": [
      {
        "_id": "org0",
        "roles": [
          {
            "role": "Foo",
            "user": "usr0"
          }
        ]
      }
    ],
    "organizationId": "org0",
    "roles": []
  },
  • The organization now attached to the Project, we have all informations to perform a query :

    • either via a direct role in the project itself
    • or via a direct role in the organization that the project belongs to
  • The $match step keeps Projects that have a matching user in roles array with the varSpecificUserId variable OR a matching user in organization's roles array. Here is the final query result with varSpecificUserId = "usr0":

[
  {
    "_id": "pro0",
    "organization": [
      {
        "_id": "org0",
        "roles": [
          {
            "role": "Foo",
            "user": "usr0"
          }
        ]
      }
    ],
    "organizationId": "org0",
    "roles": []
  },
  {
    "_id": "pro3",
    "organization": [
      {
        "_id": "org0",
        "roles": [
          {
            "role": "Foo",
            "user": "usr0"
          }
        ]
      }
    ],
    "organizationId": "org0",
    "roles": [
      {
        "role": "Foo",
        "user": "usr2"
      }
    ]
  }
]

You can use https://mongoplayground.net/ to play around with mongo querys or the new aggregation tool from MongoDB Compass if you alreadyhave data in DB.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

combine two different queries into one

분류에서Dev

Combine two queries in Oracle

분류에서Dev

Combine results of multiple queries in Oracle Sql

분류에서Dev

How to combine two tables in R?

분류에서Dev

How to combine two selects or two querys?

분류에서Dev

Using two different templates for search results - Haystack

분류에서Dev

How to dynamically combine two interfaces to pass to RealProxy

분류에서Dev

How can I combine these two statements?

분류에서Dev

How can I combine two files on Windows?

분류에서Dev

mean of non zero elements - why are these two attempt returning different results?

분류에서Dev

How to select different users filtering of certain results?

분류에서Dev

How to change results to display a different name SQL

분류에서Dev

How to install two different compilers?

분류에서Dev

How can I do this in Knex without two queries

분류에서Dev

Looping MySQL Results With Additional Queries

분류에서Dev

How to query two fields (different) into one field

분류에서Dev

how to display dates from two different tables?

분류에서Dev

How to iterate a command with two different variables?

분류에서Dev

How to compare two different values of different functions or same function?

분류에서Dev

How to make a query using Mongoose that gets N results, but combines any documents it finds that meet certain criteria?

분류에서Dev

What causes different search results for same elastic search query on two nodes

분류에서Dev

How to merge two facebook graph api Data results (JSON)

분류에서Dev

create php function for different queries

분류에서Dev

Two SQL Queries - Performance difference?

분류에서Dev

Different results for same numbers

분류에서Dev

mysqli queries not returning results inside function

분류에서Dev

Add to Dictionary Query Results of Multiple Linq Queries

분류에서Dev

Combine/Mix two lists of words

분류에서Dev

Combine two lists of tuples by key

Related 관련 기사

  1. 1

    combine two different queries into one

  2. 2

    Combine two queries in Oracle

  3. 3

    Combine results of multiple queries in Oracle Sql

  4. 4

    How to combine two tables in R?

  5. 5

    How to combine two selects or two querys?

  6. 6

    Using two different templates for search results - Haystack

  7. 7

    How to dynamically combine two interfaces to pass to RealProxy

  8. 8

    How can I combine these two statements?

  9. 9

    How can I combine two files on Windows?

  10. 10

    mean of non zero elements - why are these two attempt returning different results?

  11. 11

    How to select different users filtering of certain results?

  12. 12

    How to change results to display a different name SQL

  13. 13

    How to install two different compilers?

  14. 14

    How can I do this in Knex without two queries

  15. 15

    Looping MySQL Results With Additional Queries

  16. 16

    How to query two fields (different) into one field

  17. 17

    how to display dates from two different tables?

  18. 18

    How to iterate a command with two different variables?

  19. 19

    How to compare two different values of different functions or same function?

  20. 20

    How to make a query using Mongoose that gets N results, but combines any documents it finds that meet certain criteria?

  21. 21

    What causes different search results for same elastic search query on two nodes

  22. 22

    How to merge two facebook graph api Data results (JSON)

  23. 23

    create php function for different queries

  24. 24

    Two SQL Queries - Performance difference?

  25. 25

    Different results for same numbers

  26. 26

    mysqli queries not returning results inside function

  27. 27

    Add to Dictionary Query Results of Multiple Linq Queries

  28. 28

    Combine/Mix two lists of words

  29. 29

    Combine two lists of tuples by key

뜨겁다태그

보관