Joe
Joe

Reputation: 4234

Mongo, query a collection with a array

I have this colleciton called organization:

[
  {
    "_id": "53a58a02f1001e7fd28f5aec",
    "orgId": 5,
    "title": "Org A",
    "members": [
      {
        "tier": 1,
        "user": "53a58a02f1001e7fd28f5ae8"
      },
      {
        "tier": 2,
        "user": "53a58a02f1001e7fd28f5ae9"
      },
      {
        "tier": 3,
        "user": "53a58a02f1001e7fd28f5aea"
      }
    ]
  },
  {
    "_id": "53a58a02f1001e7fd28f5aed",
    "orgId": 6,
    "title": "Org B",
    "members": [
      {
        "tier": 1,
        "user": "53a58a02f1001e7fd28f5ae9"
      },
      {
        "tier": 3,
        "user": "53a58a02f1001e7fd28f5aea"
      }
    ]
  }
]

I want to run a query which returns all organizations that a given user is a member of.

I tried this:

mongoose.model('organization').find({}, function(err, organizations){
    var usersOrganization = [];

    for(var i=0;i<organizations.length;i++){
      for(var f = 0;f<organizations[i].members.length;f++){
        if(String(organizations[i].members[f].user) === user){
          usersOrganization.push(organizations[i]);
        }
      }
    }

    callback.send(200, usersOrganization);
  })

First get all organizations then loop through them and all members. Match the members with the given user and push it in to an array.

It works, but I wonder if there is any smart query to do this more pretty?

Upvotes: 1

Views: 68

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You can match against fields within an array using dot-notation, so you can simplify your query to:

mongoose.model('organization')
    .find({'members.user': user}, function(err, usersOrganizations){
        callback.send(200, usersOrganization);
    }
);

Upvotes: 1

Related Questions