1

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?

1 Answer 1

1

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);
    }
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.