我正在尝试计算当用户点击任意数量的星时,我传递给数据库的平均5星评级。
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传递到我的前端?
发布于 2020-05-20 00:42:18
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。
https://stackoverflow.com/questions/61892324
复制相似问题