product.js 794 B

12345678910111213141516171819202122232425262728293031
  1. const mongoose = require('mongoose')
  2. const Schema = mongoose.Schema
  3. const ProductSchema = new Schema({
  4. category: { type:Schema.Types.ObjectId, ref: 'Category' },
  5. owner: { type:Schema.Types.ObjectId, ref: 'Owner' },
  6. title: String,
  7. description: String,
  8. photo: String,
  9. price: Number,
  10. stockQuantity: Number,
  11. reviews: [{ type:Schema.Types.ObjectId, ref: 'Review' }]
  12. }, {
  13. toObject: { virtuals: true },
  14. toJSON: { virtuals: true }
  15. })
  16. ProductSchema.virtual('averageRating').get(function () {
  17. if (this.reviews.length > 0) {
  18. let sum = this.reviews.reduce((total, review) => {
  19. console.log('review', review)
  20. return total + review.rating
  21. }, 0)
  22. return sum / this.reviews.length
  23. }
  24. return 0
  25. })
  26. module.exports = mongoose.model('Product', ProductSchema)