Node.js 通过对唯一id进行分组,计算五星评级的平均值
我试图计算当用户点击任意数量的星星时,我传递给数据库的平均5星评级Node.js 通过对唯一id进行分组,计算五星评级的平均值,node.js,mongodb,express,mongoose,mongodb-query,Node.js,Mongodb,Express,Mongoose,Mongodb Query,我试图计算当用户点击任意数量的星星时,我传递给数据库的平均5星评级 const mongoose = require('mongoose'); const Schema = mongoose.Schema; const ratingSchema = mongoose.Schema({ userId: { type: Schema.Types.ObjectId, ref: 'User' }, productId: { typ
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ratingSchema = mongoose.Schema({
userId: {
type: Schema.Types.ObjectId,
ref: 'User'
},
productId: {
type: Schema.Types.ObjectId,
ref: 'Product'
},
noOfStars: {
type: Number,
default: 0
}
},{timestamp: true})
const Rating = mongoose.model('Rating', ratingSchema);
module.exports = {Rating}
这是我创建的用于发送特定产品评级的模型。当用户单击星号时,星号值、producID和userID被插入到数据库中
import React,{useEffect,useState} from 'react';
const aggregate = require("../models/rating").Rating.aggregate;
const{Rating}=require('../models/rating');
exports.RatingAdd=(req,res) =>{
aggregate(
[
{
$group:
{
_id: "$productId"
}
}
]
)
}
这是我创建的控制器,用于检索特定产品的平均星号值并在前端显示。我不明白如何得到相同产品id的计数,然后用产品id计数除以星星总数值。我无法获得每个产品的正确平均值。我应该如何编辑代码以显示每个产品的平均星号值,并将平均星号值和产品id传递到前端
db.products.aggregate({$group:{_id:'$productId',count:{$sum:1},avg:{$avg:'$noOfStars'}}},{$project:{_id:1,count:1,avg:{$round:['$avg',1]}}})
这是你需要的吗
{
"_id" : ObjectId("5ec40ff1ce367b3630df8f13"),
"userId" : "A",
"productId" : "C",
"rating" : 1
}
{
"_id" : ObjectId("5ec40ff3ce367b3630df8f14"),
"userId" : "A",
"productId" : "C",
"rating" : 2
}
{
"_id" : ObjectId("5ec40ff5ce367b3630df8f15"),
"userId" : "A",
"productId" : "C",
"rating" : 3
}
{
"_id" : ObjectId("5ec40ff6ce367b3630df8f16"),
"userId" : "A",
"productId" : "C",
"rating" : 4
}
{
"_id" : ObjectId("5ec40ffdce367b3630df8f17"),
"userId" : "A",
"productId" : "A",
"rating" : 4
}
{
"_id" : ObjectId("5ec40ffece367b3630df8f18"),
"userId" : "A",
"productId" : "A",
"rating" : 5
}
{
"_id" : ObjectId("5ec41001ce367b3630df8f19"),
"userId" : "A",
"productId" : "A",
"rating" : 4.5
}
{
"_id" : ObjectId("5ec41003ce367b3630df8f1a"),
"userId" : "A",
"productId" : "A",
"rating" : 4.2
}
{
"_id" : ObjectId("5ec41009ce367b3630df8f1b"),
"userId" : "A",
"productId" : "B",
"rating" : 3.2
}
{
"_id" : ObjectId("5ec4100bce367b3630df8f1c"),
"userId" : "A",
"productId" : "B",
"rating" : 2.2
}
{
"_id" : ObjectId("5ec4100ece367b3630df8f1d"),
"userId" : "A",
"productId" : "B",
"rating" : 1.2
}
结果:
{ "_id" : "C", "count" : 4, "avg" : 2.5 }
{ "_id" : "A", "count" : 4, "avg" : 4.4 }
{ "_id" : "B", "count" : 3, "avg" : 2.2 }
编辑测试数据并包含$round 是的,这就是我要找的,谢谢,我的下一个问题是如何将平均值转换为小于5的值,因为我的前端只有5颗星,如果mongoDB中的NoofStar都小于5,我将无法展示平均值。调用$avg肯定会得到少于5。我编辑了我使用的测试数据。。。如果您需要的话,我已经包括了一个最接近小数点后1位的四舍五入。如果你担心你的noOfStars中有超过5个,只需在$group之前进行$match,尽管这不符合评级系统的目的,因为你应该在插入DB之前对此进行验证。