product.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. const mongoose = require('mongoose')
  2. const mongooseAlgolia = require('mongoose-algolia')
  3. const Schema = mongoose.Schema
  4. const ProductSchema = new Schema({
  5. category: { type:Schema.Types.ObjectId, ref: 'Category' },
  6. owner: { type:Schema.Types.ObjectId, ref: 'Owner' },
  7. title: String,
  8. description: String,
  9. photo: String,
  10. price: Number,
  11. stockQuantity: Number,
  12. reviews: [{ type:Schema.Types.ObjectId, ref: 'Review' }]
  13. }, {
  14. toObject: { virtuals: true },
  15. toJSON: { virtuals: true }
  16. })
  17. ProductSchema.virtual('averageRating').get(function () {
  18. if (this.reviews.length > 0) {
  19. let sum = this.reviews.reduce((total, review) => {
  20. // console.log('review', review)
  21. return total + review.rating
  22. }, 0)
  23. return sum / this.reviews.length
  24. }
  25. return 0
  26. })
  27. ProductSchema.plugin(mongooseAlgolia, {
  28. appId: process.env.ALGOLIA_APP_ID,
  29. apiKey: process.env.ALGOLIA_SECRET,
  30. indexName: process.env.ALGOLIA_INDEX,
  31. selector: 'title _id photo description price rating averageRating owner',
  32. populate: {
  33. path: 'owner reviews'
  34. },
  35. debug: true
  36. })
  37. let Model = mongoose.model('Product', ProductSchema)
  38. Model.SyncToAlgolia()
  39. Model.SetAlgoliaSettings({
  40. searchableAttributes: ['title']
  41. })
  42. module.exports = Model
  43. // module.exports = mongoose.model('Product', ProductSchema)