Node.js Mongoose-为字段的每个唯一值计算文档数

Node.js Mongoose-为字段的每个唯一值计算文档数,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,这是我的模式 位置模式 const reviewSchema = mongoose.Schema({ rating: {type: Number, require: true, min: 1, max: 5}, review: {type: String, require: true}, userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true }, locationId: { type

这是我的模式

位置模式

const reviewSchema = mongoose.Schema({
  rating: {type: Number, require: true, min: 1, max: 5},
  review: {type: String, require: true},
  userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true },
  locationId: { type: mongoose.Schema.Types.ObjectId, ref: 'Location' ,required: true }
})
reviewSchema.index({ user: 1, location: 1 }, { unique: true });
const locationSchema=mongoose.Schema({
名称:{type:String,必需:true},
描述:{type:String,必需:true},
封面图片:{type:String},
地址:{
第1行:{type:String,必需:true},
第2行:{type:String},
城市:{type:String,必需:true},
state_ut:{type:String,required:true},
zipcode:{type:Number,必需:true}
},
loc:{
类型:{type:String},
坐标:[]
},
电话号码:{type:number},
位置\u类型:{type:String},
位置\u网站:{type:String}
})
查看架构

const reviewSchema = mongoose.Schema({
  rating: {type: Number, require: true, min: 1, max: 5},
  review: {type: String, require: true},
  userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true },
  locationId: { type: mongoose.Schema.Types.ObjectId, ref: 'Location' ,required: true }
})
reviewSchema.index({ user: 1, location: 1 }, { unique: true });
如何获取特定位置每颗星的总计数?
例如,我想从
Review
集合中获取有关
\u id
位置的评级,所需的输出如下:

{
  "5 stars": 10,
  "4 stars": 15,
  "3 stars": 8,
  "2 stars": 7,
  "1 stars": 8
}

您可以使用MongoDB的聚合API,尤其是

var评级={};
综述([
{
$match:
{
locationId:mongoose.Types.ObjectId(loc_id)
}
},
{
$group:
{
_id:“$rating”,
计数:{$sum:1}
}
}
],
功能(err、arr){
arr.map(p=>ratings[p._id+“star”]=p.count)
控制台日志(评级);
})
此解决方案的灵感来自MongoDB文档中的