File size: 1,262 Bytes
8b8b6f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import mongoose from "mongoose";
import { STOCK_STATUS } from "../constants.enums.js";

const ProductSchema = new mongoose.Schema(
  {
    name: { type: String, required: true, trim: true, unique: true, index: true },
    unit: { type: String, required: true, trim: true },
    category: { type: String, required: true, trim: true, index: true },
    brand: { type: String, trim: true, default: "" },
    stock: { type: Number, required: true, min: 0, default: 0 },
    status: { type: String, enum: Object.values(STOCK_STATUS), default: STOCK_STATUS.OUT_OF_STOCK, index: true },
    image: { type: String, default: "" },
  },
  { timestamps: true }
);

// Automatically update status based on stock before saving
ProductSchema.pre("save", function (next) {
  if (typeof this.stock === "number") {
    this.status = this.stock > 0 ? STOCK_STATUS.IN_STOCK : STOCK_STATUS.OUT_OF_STOCK;
  }
  next();
});

// Same logic for updates
ProductSchema.pre("findOneAndUpdate", function (next) {
  const update = this.getUpdate() || {};
  if (typeof update.stock === "number") {
    update.status = update.stock > 0 ? STOCK_STATUS.IN_STOCK : STOCK_STATUS.OUT_OF_STOCK;
    this.setUpdate(update);
  }
  next();
});

export default mongoose.model("Product", ProductSchema);