All files / bc-mongodb-implementation-demo/src/features/books book.model.js

100% Statements 7/7
100% Branches 0/0
100% Functions 0/0
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 725x   5x                         5x                                                                                                 5x     5x   5x 5x  
const mongoose = require('mongoose')
 
const reviewSchema = new mongoose.Schema({
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
  description: {
    type: String,
    trim: true,
  },
  rating: {
    type: Number,
    min: [1, 'Rating must be at least 1.'],
    max: [5, 'Rating cannot exceed 5.'],
  },
})
 
const bookSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: [true, 'Title is required.'],
      trim: true,
      minLength: [3, 'Title must be at least 3 characters long.'],
    },
    description: {
      type: String,
      required: true,
    },
    author: {
      type: String,
      required: [true, 'Author is required.'],
    },
    categories: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category',
        required: true,
      },
    ],
    trending: {
      type: Boolean,
      required: true,
    },
    coverImage: {
      type: String,
    },
    price: {
      type: Number,
      required: [true, 'Price is required.'],
      min: [0, 'Price cannot be negative.'],
    },
    quantityInStock: {
      type: Number,
      required: [true, 'Stock quantity is required.'],
      min: [0, 'Stock quantity cannot be negative.'],
      default: 0,
    },
    review: [reviewSchema],
  },
  {
    timestamps: true,
  },
)
 
// Compound index for price and creation date (useful for sorting/filtering)
bookSchema.index({ price: 1, createdAt: -1 })
 
// Text index for searching in title and description
bookSchema.index({ title: 'text' })
 
const BookModel = mongoose.model('Book', bookSchema)
module.exports = BookModel