0

I have a collection with organizations. Each organization has members. I want to run query to check if a user is a member of that organization.

I tried this:

mongoose.model('organization').find({orgId: paramOrgId}, function(err, organization){
      organization.find({'members.user':req.user._id}, function(err, user){
        if(!user) res.send(401) //The user is not a member in organization

        if(user) res.send(200);

      });

    }
    return res.send(401);
  });

Apparently you don't have 'find' on callback. How should I do this instead?

Example of organization doc:

> db.organizations.find().forEach(printjson);
{
    "_id" : ObjectId("5381d5d11409f125475fcc90"),
    "orgId" : 5,
    "title" : "ExampleCorp",
    "members" : [
        {
            "tier" : 1,
            "user" : ObjectId("5381d5d11409f125475fcc8c")
        },
        {
            "tier" : 2,
            "user" : ObjectId("5381d5d11409f125475fcc8d")
        },
        {
            "tier" : 3,
            "user" : ObjectId("5381d5d11409f125475fcc8e")
        }
    ]
}
Foreever
  • 7,099
  • 8
  • 53
  • 55
Joe
  • 4,274
  • 32
  • 95
  • 175
  • Can you edit your question to include an example `organization` document? – JohnnyHK May 25 '14 at 14:47
  • I think this can only be done in single query. See this http://stackoverflow.com/questions/3985214/mongodb-extract-only-the-selected-item-in-array/12241733#12241733 – Foreever May 25 '14 at 18:31

1 Answers1

0

Here it is in one query if you just want to check if a user is a member of an organization.

// Use findOne so that it returns one document instead of a collection
mongoose.model('organization').findOne({
    // Instead of querying twice, just set both conditions
    'orgId': paramOrgId,
    'members.user':req.user._id
}, 
'_id', // We'll just select the _id field. We don't need the whole organization document
function (err, org) {
    if (err)  
        return res.send(500); // Error!

    if (org) 
        return res.send(200);
    else
        return res.send(401);
});
hyubs
  • 737
  • 6
  • 18