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);