12. mongoose使用populate关联查询

官方文档

在小于3.2版本的MongoDB版本中,没有lookup聚合操作,所以诞生了populate。现如今还是推荐直接aggregate聚合操作

表结构

12. mongoose使用populate关联查询 - 图1

使用populate

需要在定义Schema的时候通过ref指定关联表:

  1. var ArticleSchema = new Schema({
  2. title: { type: String, unique: true },
  3. cid: {
  4. type: Schema.Types.ObjectId,
  5. ref: 'ArticleCate' //model 的名称
  6. },
  7. /*分类 id*/
  8. author_id: {
  9. type: Schema.Types.ObjectId,
  10. ref: 'User'
  11. },
  12. /*用户的 id*/
  13. author_name: { type: String },
  14. descripton: String,
  15. content: String
  16. });

查询:

  1. ArticleModel.find({})
  2. .populate('cid')
  3. .populate('author_id')
  4. .exec(function (err, docs) {
  5. console.log(docs);
  6. });

查询时需要将用到的表对应的model全部引入