This repository has been archived by the owner on Jul 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReview.js
70 lines (63 loc) · 1.53 KB
/
Review.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
const mongoose = require('mongoose');
const ReviewSchema = new mongoose.Schema({
title: {
type: String,
trim: true,
required: [true, 'Please add a title for the review'],
maxlength: 100
},
content: {
type: String,
required: [true, 'Please add the review content']
},
rating: {
type: Number,
min: 1,
max: 10,
required: [true, 'Please add a rating between 1 to 10']
},
createdAt: {
type: Date,
default: Date.now
},
food: {
type: mongoose.Schema.ObjectId,
ref: 'Food',
required: true
},
user: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true
}
});
// Prevent user from submitting more than one review per food
ReviewSchema.index({ food: 1, user: 1 }, { unique: true });
// Static method to get the average rating & save
ReviewSchema.statics.getAverageRating = async function(foodId) {
const obj = await this.aggregate([
{ $match: { food: foodId } },
{
$group: {
_id: '$food',
averageRating: { $avg: '$rating' }
}
}
])
try {
await this.model('Food').findByIdAndUpdate(foodId, {
averageRating: obj[+[]].averageRating.toFixed(2)
})
} catch (error) {
console.log(error);
}
}
// Call getAverageRating after save
ReviewSchema.post('save', function() {
this.constructor.getAverageRating(this.food);
});
// Call getAverageRating after remove
ReviewSchema.post('remove', function() {
this.constructor.getAverageRating(this.food);
});
module.exports = mongoose.model('Review', ReviewSchema);