12. mongoose使用populate关联查询
在小于3.2版本的MongoDB版本中,没有lookup聚合操作,所以诞生了populate。现如今还是推荐直接aggregate聚合操作
表结构
使用populate
需要在定义Schema的时候通过ref指定关联表:
var ArticleSchema = new Schema({
title: { type: String, unique: true },
cid: {
type: Schema.Types.ObjectId,
ref: 'ArticleCate' //model 的名称
},
/*分类 id*/
author_id: {
type: Schema.Types.ObjectId,
ref: 'User'
},
/*用户的 id*/
author_name: { type: String },
descripton: String,
content: String
});
查询:
ArticleModel.find({})
.populate('cid')
.populate('author_id')
.exec(function (err, docs) {
console.log(docs);
});
查询时需要将用到的表对应的model全部引入