3

I am having some difficulty with my leaderboard for my application. I have a database with two collections.

  • Users
  • Fish

In my Fish collection I also have user_id. When I fetch all fish, I get everything including user_id. However, the user_id doesn't really help me, I want to display the username belonging to that user_id.

This is how my query looks.

Fish.find().sort({weight: -1}).limit(10).exec(function(err, leaderboard) {
        if(err) return res.json(500, {errorMsg: 'Could not get leaderboard'});

        res.json(leaderboard);
    })

I feel like I need to make another query, to get all the usernames belonging to the user_ids I get from the first query. Perhaps use a loop somehow?

MongoDb is pretty new to me and don't really know what to look for. Any advice, tips, link are much appriecated.

Moe Far
  • 2,742
  • 2
  • 23
  • 41
Cheese Puffs
  • 955
  • 3
  • 10
  • 19
  • 1
    If this is using Mongoose, you can use its support for [population](http://mongoosejs.com/docs/populate.html) to do this. – JohnnyHK May 24 '15 at 15:55

1 Answers1

2

You may find useful information on MongoDB's Database References documentation.

The first thing to consider on using fields from different collections in MongoDB is:

MongoDB does not support joins. In MongoDB some data is denormalized, or stored with related data in documents to remove the need for joins. However, in some cases it makes sense to store related information in separate documents, typically in different collections or databases.

In your case, you might want to consider storing the information from the Fish collection as embedded documents within the users from the User collection.

If this is not an option, then you might want to use Manual References or loop over the user_ids provided in the result from your query over the Fish collection.

With the second option you may use a query to obtain the corresponding usernames from the User collection such as:

Users.find({user_id:<USER_ID>},{username:1})
Ana C.
  • 43
  • 5