All files / bc-mongodb-implementation-demo/src/features/orders order.model.js

100% Statements 6/6
100% Branches 0/0
100% Functions 1/1
100% Lines 6/6

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 72 73 74 75 76 77 78 79 80 81 824x   4x                   4x                                             6x                                                                                       4x 4x  
const mongoose = require('mongoose')
 
const orderBookSchema = new mongoose.Schema({
  bookId: { type: mongoose.Schema.Types.ObjectId, ref: 'Book', required: true },
  quantity: { type: Number, required: true },
  priceAtPurchase: {
    type: Number,
    required: true,
    min: [0, 'Price at purchase must be a positive number.'],
  },
})
 
const orderSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
    },
    phone: {
      type: String,
      trim: true,
      match: [
        /^(\+420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,
        'Please fill a valid phone number',
      ],
      required: false,
    },
    books: {
      type: [orderBookSchema],
      validate: {
        validator: function (books) {
          return books.length > 0
        },
        message: 'Order must contain at least one book.',
      },
    },
    status: {
      type: String,
      enum: {
        values: [
          'pending',
          'processing',
          'shipped',
          'delivered',
          'completed',
          'canceled',
          'refunded',
        ],
        message: 'Invalid order status: {VALUE}',
      },
      default: 'pending',
      required: [true, 'Order status is required.'],
    },
    shippingAddress: {
      street: { type: String, required: true, trim: true },
      city: { type: String, required: true, trim: true },
      postalCode: {
        type: String,
        required: true,
        trim: true,
        match: /^\d{3} ?\d{2}$/,
      },
      country: {
        type: String,
        required: true,
        trim: true,
        uppercase: true,
        minLength: 2,
        maxLength: 3,
      },
    },
  },
  { timestamps: true },
)
 
const OrderModel = mongoose.model('Order', orderSchema)
module.exports = OrderModel