MongoDB没有join, 但是有的时候我们需要引用其它collection的documents, 这个时候就需要populate了.

我们可以populate单个document, 多个document, plain object, multiple plain objects或query返回的全部object.

var mongoose = require('mongoose');
var Schema = mongoose.Schema; var personSchema = new Schema({
_id: Number,
name: String,
age: Number,
stories: [{type: Schema.Types.ObjectId, ref: 'story'}]
}); var storySchema = new 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);

目前为止我们创建了两个model. Person model有一个stories字段是以个ObjectId的集合. ref是告诉mongoose哪个model应该被popluate.

Story有一个_creator字段是Number类型的他是personSchema的Id

Saving ref

保存一个ref

var arron = new Person({_id:0, name: 'Aaron', age: 100});

arron.save(function(err){
if(err) return handleError(err); var story1 = new Story({
titile: 'Once upon a timex',
_creator: arron._id //分配person的_id
}); story1.save(function(err){
if(err) return handleError(err);
}); });

Populate

填充story的_creator

Story
.findOne({title: 'Once upon a timex'})
.populate('_creator')
.exec(fucntion(err, story){
if(err) return handleError(err);
console.log(story._creator.name) // Aaron
});

Field selection

如果我们不想为story填充整个_creator 我们只想填充_creator的name怎么搞呢?

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

一次填充多个paths

如果我们想一次填充多个path怎么过搞呢

Story
.find(...)
.populate('fans author') // space delimited path names
.exec()

另一种写法

Story
.find(...)
.populate('fans')
.populate('author')
.exec()

按条件填充

Story
.find(...)
.populate({
path: 'fans',
match: { age: { $gte: 21 }},
select: 'name -_id',
options: { limit: 5 }
})
.exec()

  

[译]Mongoose指南 - Population的更多相关文章

  1. [译]Mongoose指南 - Schema

    定义schema 用mongoose的第一件事情就应该是定义schema. schema是什么呢? 它类似于关系数据库的表结构. var mongoose = require('mongoose'); ...

  2. [译]Mongoose指南 - Connection

    使用mongoose.connect()方法创建连接 mongoose.conect('mongodb://localhost/myapp'); 上面的代码是通过默认端口27017链接到mongodb ...

  3. [译]Mongoose指南 - 验证

    开始前记住下面几点 Validation定义在SchemaType中 Validation是一个内部的中间件 当document要save前会发生验证 验证不会发生在空值上 除非对应的字段加上了 re ...

  4. [译]Mongoose指南 - 查询

    查询有带callback和不带callback两种方式 所有mongoose的callback都是这种格式: callback(err, result) var Person = mongoose.m ...

  5. [译]Mongoose指南 - Model

    编译你的第一个model var xxSchema = new Schema({name: 'string', size: 'string'}); var Tank = mongoose.model( ...

  6. [译]Mongoose指南 - Plugin

    Schema支持插件, 这样你就可以扩展一些额功能了 下面的例子是当document save的时候自定更新最后修改日期的出插件 // lastMod.js module.exports = expo ...

  7. [译]Mongoose指南 - 中间件

    中间件是一些函数, 当document发生init, validate, save和remove方法的时候中间件发生. 中间件都是document级别的不是model级别的. 下面讲讲两种中间件pre ...

  8. [译]Mongoose指南 - Document

    更新 有几种方式更新document. 先看一下传统的更新方法 Tank.findById(id, function(err, tank){ if(err) return handleError(er ...

  9. (译)快速指南:用UIViewPropertyAnimator做动画

    翻译自:QUICK GUIDE: ANIMATIONS WITH UIVIEWPROPERTYANIMATOR 译者:Haley_Wong iOS 10 带来了一大票有意思的新特性,像 UIViewP ...

随机推荐

  1. CCTray配置如何添加远程服务器

    前提: Windows防火墙必须开通的TCP端口 或者直接把防火墙关闭(不建议) 或者直接在防火墙规则增加CCNET的服务进去 总者,只要确保能telnet ip 21234能通即可 建议全部软件都装 ...

  2. CMMI3标准文档模板大全

    链接:http://pan.baidu.com/s/1c2cGX8W 密码:ulns

  3. hdu 5233 离散化

    10^9的大数组显然开不了.所以也算比较裸的离散化了... 令pos[i].pp[j]表示从左到右第j个高度为i的树的位置 (pp是个vector,范围0..now-1) pos[i].num表示有几 ...

  4. c/c++中#和##链接符号的用法

    #include <stdio.h> #include <stdlib.h> /* 英语原文: In function-like macros, a # operator be ...

  5. range和xrange梳理

    一.python2.7 range 用户获取指定范围内的数,range([start,] stop[, step]) >>> range(1,5) #代表从1到5(不包含5) [1, ...

  6. web前端环境搭建

    第一部分:浏览器 浏览器推荐chrome浏览器.FireFox浏览器. 1. chrome浏览器因为集成了Google Developer Tools(谷歌开发者工具),因此大受欢迎. 下载地址:ht ...

  7. webstorm9.3 安装less 编译css教程

    第一步:安装node.js webstrom9.3汉化下载:http://pan.baidu.com/s/1ntGNNiL    密码:1fbh node.js 下载地址:https://nodejs ...

  8. Distinct

    SELECT 指令让我们能够读取表格中一个或数个栏位的所有资料.这将把所有的资料都抓出,无论资料值有无重复.在资料处理中,我们会经常碰到需要找出表格内的不同资料值的情况.换句话说,我们需要知道这个表格 ...

  9. JavaWeb学习笔记——JSP标准标签库JSTL

  10. BigInteger类

    当一个数字非常大时,则肯定无法使用基本类型接受,所以使用了BigInteger类. BigInteger类表示是大整数类,定义在java.math包中,如果在操作时一个整型数据已经超过了整数的最大类型 ...