简体   繁体   English

分别获取它们之后加入MongoDB集合

[英]Joining MongoDB collections after fetching them separately

We have a one-to-many relationship stored as two separate collections in MongoDB. 我们将一对多关系存储为两个单独的集合在MongoDB中。 The relationship is: 1 Team has many People. 关系是:1团队有很多人。 We are intentionally saving these as separate collections because we want to be able to query them separately. 我们有意将它们保存为单独的集合,因为我们希望能够单独查询它们。 We decided on this design after doing bunch of research - I hope it makes sense. 经过大量研究后,我们决定采用这种设计-我希望这样做是有意义的。 Here are the simplified Mongoose schemas: 以下是简化的猫鼬模式:

var TeamSchema = new Mongoose.Schema({
    name: String
});

var PersonSchema = new Mongoose.Schema({
    name: String
    teamId: {
        type: Mongoose.Schema.ObjectId,
        ref: 'Team',
    }
});

I would like to join the two collections as follows before sending them to the front-end: 在将它们发送到前端之前,我想按如下方式加入这两个集合:

[
     { "name": "John Doe",   "Team": "Orange" },
     { "name": "Jane Smith", "Team": "Orange" },
     { "name": "Doug White", "Team": "Blue"   }
]

I don't mind doing two separate queries to get each collection into memory. 我不介意进行两个单独的查询以将每个集合都存储到内存中。 The question is what's the most efficient way to join the collections once I have them in memory? 问题是,一旦我将它们存储在内存中,最有效的方式加入这些集合是什么?

This is what I started doing, but the join code is not there: 这是我开始做的,但是联接代码不存在:

Person.find(function(err, people) {
    Team.find(function(err, teams) {
        // Now I have people and teams
        // How to join them?
    });
});

I would opt for using population , which is the common method of 'joining' in Mongoose. 我会选择使用人口 ,这是猫鼬中“加入”的常见方法。

Your schema is already set up for this, so you just have to adjust your query: 您的模式已经为此设置,因此您只需要调整查询即可:

Person.find().populate('teamId').exec(function(err, people) {
  ...
});

The people array will look something like this: people数组将如下所示:

[ { name: 'John Doe',
    teamId: { name: 'Orange', _id: ..., __v: 0 },
    _id: ...,
    __v: 0 },
  { name: 'Jane Smith',
    teamId: { name: 'Orange', _id: ..., __v: 0 },
    _id: ...,
    __v: 0 },
  { name: 'Doug White',
    teamId: { name: 'Blue', _id: ..., __v: 0 },
    _id: ...,
    __v: 0 } ]

To get the results you want, it's simple a matter of running a map on it: 要获得所需的结果,只需在其上运行map

var results = people.map(function(person) {
  return { name : person.name, Team : person.teamId.name };
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM