3

我在申请排行榜时遇到了一些困难。我有一个包含两个集合的数据库。

  • 用户

在我的 Fish 集合中,我也有 user_id。当我获取所有鱼时,我得到了包括 user_id 在内的所有内容。但是,user_id 并没有真正帮助我,我想显示属于该 user_id 的用户名。

这就是我的查询的样子。

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

我觉得我需要进行另一个查询,以获取属于我从第一个查询中获得的 user_ids 的所有用户名。也许以某种方式使用循环?

MongoDb 对我来说很新,我真的不知道要寻找什么。任何建议、提示、链接都非常有用。

4

1 回答 1

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})
于 2015-05-24T17:06:55.083 回答