const postSchema = mongoose.Schema({
title: String,
visit: {
type: Number,
default: 0
},
imagesrc: String,
tags: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'tag'
}
],
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'category'
},
createTime: {
type: Date,
default: Date.now
},
lastEditTime: {
type: Date,
default: Date.now
},
hidden: Boolean,
excerpt: String,
content: String,
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'comment'
}
]
}
const categorySchema = mongoose.Schema({
name: String
}
文章和分类两个模型定义如上,文章schema有一个分类的外键,请问如何最高效率的查询出所有分类以及分类下的文章总数,返回一个集合
大概思路:
1、aggreate -- $group
2、forEach去关联到Category表
效率需要查看执行计划具体分析。供参考