-
Notifications
You must be signed in to change notification settings - Fork 0
/
review.model.js
77 lines (67 loc) · 1.54 KB
/
review.model.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import mongoose from "mongoose";
import Service from "./service.model.js"
const reviewSchema = new mongoose.Schema(
{
service: {
type: mongoose.Types.ObjectId,
ref: "Service",
},
user: {
type: mongoose.Types.ObjectId,
ref: "User",
},
reviewText: {
type: String,
required: true,
},
rating: {
type: Number,
required: true,
min: 0,
max: 5,
default: 0,
},
},
{ timestamps: true }
);
reviewSchema.pre(/^find/, function(next){
this.populate({
path:"user",
select: "username avatar",
});
next();
});
reviewSchema.statics.calcAverageRatings = async function(serviceId){
//this points the current review
const stats = await this.aggregate([
{
$match: { service: serviceId }
},
{
$group: {
_id: "$service",
numOfRating: { $sum: 1 },
avgRating: { $avg: "$rating" }
}
},
{
$project: {
_id: 0,
numOfRating: 1,
avgRating: { $round: ["$avgRating", 1] }
}
}
]);
await Service.findByIdAndUpdate(serviceId, {
totalRating: stats[0].numOfRating,
averageRating:stats[0].avgRating,
});
};
reviewSchema.post('save', async function(){
try {
await this.constructor.calcAverageRatings(this.service);
} catch (error) {
console.error(error);
}
});
export default mongoose.model("Review", reviewSchema);