# 聯表(population)
> 原文:[Population](http://mongoosejs.com/docs/populate.html)
## Population
在MongoDB沒有join聯表操作但有時我們還想引用其他集合中文檔。這是population的出現的緣由。
Population是在文檔中自動更換其他集合的文檔指定路徑的過程。我們可以填充一個單一的文檔,多個文檔,普通對象,多個簡單的對象,或從查詢返回的所有對象。讓我們看看一些例子。
```
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var personSchema = Schema({
_id : Number,
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
_creator : { type: Number, ref: 'Person' },
title : String,
fans : [{ type: Number, ref: 'Person' }]
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
```
到目前為止,我們已經創建了兩個[模型](http://mongoosejs.com/docs/models.html)。我們的Person 模型有stories字段設置為ObjectIds數組。ref 選項告訴Mongoose哪個模型中中使用 population,在我們的案例 Story 模型。所有的\_ids我們存儲的必須是 Story 模型的\_ids。我們還聲明 Story 的\_creator屬性作為數字型,和 \_id類型相同用在personSchema中。這是非常重要的匹配 \_id類型到 ref 類型。
> 注:ObjectId,Number,String,和Buffer都是作為refs有效的類型。
### Saving refs
引用其他文件保存的工作方式相同,通常保存屬性,只是分配的\_id值:
```
var aaron = new Person({ _id: 0, name: 'Aaron', age: 100 });
aaron.save(function (err) {
if (err) return handleError(err);
var story1 = new Story({
title: "Once upon a timex.",
_creator: aaron._id // assign the _id from the person
});
story1.save(function (err) {
if (err) return handleError(err);
// thats it!
});
});
```
### Population
到目前為止,我們還沒有做任何不同的事情。我們只是創造了一個 Person 和一個 Story 。現在讓我們使用查詢生成器看一下填充story的\_creator。
```
Story
.findOne({ title: 'Once upon a timex.' })
.populate('_creator')
.exec(function (err, story) {
if (err) return handleError(err);
console.log('The creator is %s', story._creator.name);
// prints "The creator is Aaron"
});
```
陣列的refs工作方式相同。在查詢時調用populate方法和文檔數組將在返回在原來的\_ids的地方。
> 注:mongoose > = 3.6 在使用population暴露原始的`_ids`通過[document#populated()](http://mongoosejs.com/docs/api.html#document_Document-populated)方法。
### 設置Populated字段
在Mongoose > = 4,你也可以手動填充字段。
```
Story.findOne({ title: 'Once upon a timex.' }, function(error, story) {
if (error) {
return handleError(error);
}
story._creator = aaron;
console.log(story._creator.name); // prints "Aaron"
});
```
注意,這只工作在單個refs。你現在不能手動填充數組refs。
### 字段選擇
如果我們只想要一些特定的字段返回填充的文檔呢?這可以通過將常用的[字段名語法](http://mongoosejs.com/docs/api.html#query_Query-select)作為填充方法的第二個參數來完成:
```
Story
.findOne({ title: /timex/i })
.populate('_creator', 'name') // only return the Persons name
.exec(function (err, story) {
if (err) return handleError(err);
console.log('The creator is %s', story._creator.name);
// prints "The creator is Aaron"
console.log('The creators age is %s', story._creator.age);
// prints "The creators age is null'
})
`
```
### Populating multiple paths
如果我們想在同一時間填充多個路徑呢?
```
Story
.find(...)
.populate('fans _creator') // space delimited path names
.exec()
```
> 在 mongoose > = 3.6,我們可以把一個空格分隔的路徑名來填充字符串。3.6之前,您必須執行`populate()`方法多次。
```
Story
.find(...)
.populate('fans')
.populate('_creator')
.exec()
```
### 查詢條件和其他選項
如果我們想根據他們的年齡來填充我們的球迷數組,選擇只是他們的名字,并返回最多,其中5個?
```
Story
.find(...)
.populate({
path: 'fans',
match: { age: { $gte: 21 }},
select: 'name -_id',
options: { limit: 5 }
})
.exec()
```
### Refs to children
我們可能會發現,如果我們使用aaron對象,我們無法得到一個列表的stories。這是因為沒有story的對象都“推”到`aaron.stories`。
這里有兩個觀點。首先,很高興aaron知道哪些stories是他的。
```
aaron.stories.push(story1);
aaron.save(callback);
```
這使我們能夠執行一個查找和填充組合:
```
Person
.findOne({ name: 'Aaron' })
.populate('stories') // only works if we pushed refs to children
.exec(function (err, person) {
if (err) return handleError(err);
console.log(person);
})
```
> 這是值得商榷的,我們真的要兩套指針作為他們可能不同步。相反,我們可以跳過,直接填充并`find()`我們感興趣的故事。
```
Story
.find({ _creator: aaron._id })
.exec(function (err, stories) {
if (err) return handleError(err);
console.log('The stories are an array: ', stories);
})
```
### 更新refs
現在我們有一個故事,我們意識到`_creator`是錯誤的。我們可以通過更新refs通過Mongoose的鑄件內部任何其他屬性一樣:
```
var guille = new Person({ name: 'Guillermo' });
guille.save(function (err) {
if (err) return handleError(err);
story._creator = guille;
console.log(story._creator.name);
// prints "Guillermo" in mongoose >= 3.6
// see https://github.com/Automattic/mongoose/wiki/3.6-release-notes
story.save(function (err) {
if (err) return handleError(err);
Story
.findOne({ title: /timex/i })
.populate({ path: '_creator', select: 'name' })
.exec(function (err, story) {
if (err) return handleError(err);
console.log('The creator is %s', story._creator.name)
// prints "The creator is Guillermo"
})
})
})
```
> 返回的文檔查詢population成為功能齊全,可保存文件,除非指定了精益選項。不與子文檔混淆。請注意,當調用它的刪除方法,因為你會從數據庫中刪除它,不僅僅是數組。
### Populating 一個存在的文檔
如果我們有一個現有的mongoose文檔并且想要填充的一些它的路徑。mongoose > = 3.6支持[document#populate()](http://mongoosejs.com/docs/api.html#document_Document-populate)方法。
### Populating 多個存在的文檔
如果我們有一個或多個mongoose文檔,甚至是簡單的對象(像mapReduce輸出),我們可以讓他們使用[Model.populate()](http://mongoosejs.com/docs/api.html#model_Model.populate)方法 mongoose > = 3.6。這是為什么使用`document#populate()` 和`query#populate()`來populate文檔。
### Populating在多個層面
說你有一個用戶模式,跟蹤用戶的朋友。
```
var userSchema = new Schema({
name: String,
friends: [{ type: ObjectId, ref: 'User' }]
});
```
Populate可以讓你得到一個用戶的朋友的列表,但如果你也想要一個用戶的朋友的朋友呢?指定populate選項告訴mongoose來populate所有用戶的朋友的朋友的數組:
```
User.
findOne({ name: 'Val' }).
populate({
path: 'friends',
// Get friends of friends - populate the 'friends' array for every friend
populate: { path: 'friends' }
});
```
### Populating整個數據庫
讓我們說,你有一個代表事件的模式,和一個代表對話的模式。每個事件都有一個相應的會話線程。
```
var eventSchema = new Schema({
name: String,
// The id of the corresponding conversation
// Notice there's no ref here!
conversation: ObjectId
});
var conversationSchema = new Schema({
numMessages: Number
});
```
同時,假設事件和對話都存儲在單獨的MongoDB實例。
```
var db1 = mongoose.createConnection('localhost:27000/db1');
var db2 = mongoose.createConnection('localhost:27001/db2');
var Event = db1.model('Event', eventSchema);
var Conversation = db2.model('Conversation', conversationSchema);
```
在這種情況下,您將無法正常`populate()`。conversation字段永遠是空的,因為`populate()`不知道使用哪種模式。然而,您可以[顯式指定模型](http://mongoosejs.com/docs/api.html#model_Model.populate)。
```
Event.
find().
populate({ path: 'conversation', model: Conversation }).
exec(function(error, docs) { /* ... */ });
```
這是一個被稱為“跨數據庫的populate“,因為它使你populate在MongoDB數據庫和通過MongoDB實例。
### 動態參考
Mongoose也可以同是populate從多個集合。讓我們說,你有一個用戶模式,有一個“連接”的數組-用戶可以連接到其他用戶或組織。
```
var userSchema = new Schema({
name: String,
connections: [{
kind: String,
item: { type: ObjectId, refPath: 'connections.kind' }
}]
});
var organizationSchema = new Schema({ name: String, kind: String });
var User = mongoose.model('User', userSchema);
var Organization = mongoose.model('Organization', organizationSchema);
```
以上的refpath屬性意味著mongoose會看`connections.kind`路徑確定模型用于`populate()`。換句話說,這`refpath`屬性使您能夠ref屬性的動態。
```
// Say we have one organization:
// `{ _id: ObjectId('000000000000000000000001'), name: "Guns N' Roses", kind: 'Band' }`
// And two users:
// {
// _id: ObjectId('000000000000000000000002')
// name: 'Axl Rose',
// connections: [
// { kind: 'User', item: ObjectId('000000000000000000000003') },
// { kind: 'Organization', item: ObjectId('000000000000000000000001') }
// ]
// },
// {
// _id: ObjectId('000000000000000000000003')
// name: 'Slash',
// connections: []
// }
User.
findOne({ name: 'Axl Rose' }).
populate('connections.item').
exec(function(error, doc) {
// doc.connections[0].item is a User doc
// doc.connections[1].item is an Organization doc
});
```
### Populate虛函數
新的4.5.0中
到目前為止,你只有稀少的基于\_id字段。然而,這有時不是正確的選擇。特別是,數組,無束縛成長是MongoDB的反模式。用mongoose鼬虛函數,您可以定義文檔之間更復雜的關系。
```
var PersonSchema = new Schema({
name: String,
band: String
});
var BandSchema = new Schema({
name: String
});
BandSchema.virtual('members', {
ref: 'Person', // The model to use
localField: 'name', // Find people where `localField`
foreignField: 'band' // is equal to `foreignField`
});
var Person = mongoose.model('Person', personSchema);
var Band = mongoose.model('Band', bandSchema);
/**
* Suppose you have 2 bands: "Guns N' Roses" and "Motley Crue"
* And 4 people: "Axl Rose" and "Slash" with "Guns N' Roses", and
* "Vince Neil" and "Nikki Sixx" with "Motley Crue"
*/
Band.find({}).populate('members').exec(function(error, bands) {
/* `bands.members` is now an array of instances of `Person` */
});
`
```
### 下一步
現在我們已經掌握了population,讓我來看一下[連接](http://mongoosejs.com/docs/connections.html)。