為了讓使用者能評價bootcamp的好壞
藉此作為他們挑選課程的依據
我們要建立review model並reference bootcamp&user model
讓已註冊的使用者能對review進行CRUD functionality
新增'./models/Review'
建立title, text, rating這三個type
const ReviewSchema = new mongoose.Schema({
title: {
type: String,
trim: true,
required: [true, 'Please add a title for the review'],
maxlength: 100
},
text: {
type: String,
required: [true, 'Please add some text']
},
rating: {
type: Number,
min: 1,
max: 10,
required: [true, 'Please add a rating between 1 and 10']
},
createdAt: {
type: Date,
default: Date.now
},
bootcamp: {
type: mongoose.Schema.ObjectId,
ref: 'Bootcamp',
required: true
},
user: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true
}
});
新增reviews controller
這邊要完成三種GET request:
第一種情況下,如果有輸入bootcampId, 回傳該bootcamp對應的reviews
第二種情況是回傳所有的reviews, 透過advancedResults middleware, 打包回傳的reviews(包含filtering, pagination等功能)
if (req.params.bootcampId) {
const reviews = await Review.find({ bootcamp: req.params.bootcampId});
return res.status(200).json({
success: true,
count: reviews.length,
data: reviews
});
} else {
res.status(200).json(res.advancedResults);
}
第三種情況是直接透過個別review的id從db尋找對應到的review
const review = await Review.findById(req.params.id).populate({
path: 'bootcamp',
select: 'name description'
});