Lukas Lukac
Lukas Lukac

Reputation: 8376

mongoDB select from collection with relation

I need to select users for corresponding data from query.

I have this collection in my DB (two or more rows are output of my query as well)

> db.Friends.find()
{ "userId" : "k3XCWdN5M2pbzBiFD", "followeeId" : "3MTmHcJNEzaaS8hrd","_id" :  "aiRD.." }
{ "userId" : "k3XCWdN5M2pbzBiFD", "followeeId" : "SoTozuZ4nWooRBeFz","_id" :  "QingX.."    }

When it would be just one result as findOne(...) the second query would looks like this:

users.findOne({ _id: firstQueryResult.followeeId })

But now the problem is... how can i select the users from users collection when i dont have only one followeeId but more of them?

Please someone show me an example of code.

My research: Is this a good solution?

friendsData.forEach(function(relationShip) {
    followeeIds.push(relationShip.followeeId);
});
console.log(followeeIds);

Upvotes: 2

Views: 3431

Answers (2)

Lukas Lukac
Lukas Lukac

Reputation: 8376

Ok i finalllly figure out the problem.For next readers:

  1. Check if autopublish is enabled or disabled.
  2. If is disabled you need to publish the collection from the DB

    Meteor.publish("userData", function () {
        return Meteor.users.find({},
                       {fields: {'username': 1}});
    });
    

    PS: i want to publish only username field and thats all!

  3. You need to subscribe the data as well!

    Meteor.subscribe("userData");
    
  4. Now you can access other users data this way:

    users= Meteor.users.findOne({username: "Nolifer"});
    
  5. To my original problem ... i will probably use this function for iterate over more then one row result(its more a SQL term but i am not sure what term use in mongoDb maybe a document? whatever):

    users.forEach(function(user) {
        console.log(user);
    });
    

Thats it!

P.S.: I think there is nothing wrong on this but what i know right? :) So if someone know a better way please leave a comment. If not give me know if it was useful for you :)

Upvotes: 1

Elad Meidar
Elad Meidar

Reputation: 814

According to the mongo manual, use the $in operand: http://docs.mongodb.org/manual/reference/operator/in/#op._S_in

db.inventory.find( { qty: { $in: [ 5, 15 ] } } )

Upvotes: 0

Related Questions