Get all usernames from user_id elements? (Mongodb query)

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

  • Users
  • A fish

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

This is what my request looks like.

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);
    })

      

It seems to me that I need to make another request to get all the usernames belonging to user_id that I get from the first request. Perhaps some way to use a loop?

MongoDb is pretty new to me and has no idea what to look for. Any advice, advice, links are very much appreciated.

+3


source to share


1 answer


You can find useful information on MongoDB Database documentation .

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

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

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



If that is not an option, you can use the "References" or loop over the user_ids provided by the Collect fish request.

With the second option, you can use a query to get the corresponding usernames from the user collection, for example:

Users.find({user_id:<USER_ID>},{username:1})

      

+2


source







All Articles