vendredi 23 juin 2023

how to avoid circular dependency in requiring files

I am making a inventory management system. I have two models sales and orders. Sales contain bill data and each product purchased is in orders model. I want to use pre update hook to update orders and vice versa

// fileName sale.model.js

const ordersModel = require("./orders.model")
const connection = require("./database/connection")

const SaleSchema = new mongoose.Schema(
  {
    store: { type: mongoose.Types.ObjectId, required: true, ref: "stores" },
    customerName: { type: String, required: true },
    customerPhone: { type: String, required: true },
    totalDiscount: { type: Number },
    orders: [{ type: mongoose.Types.ObjectId, ref: "orders" }],
   
  },
  {
    timestamps: true,
  }
);

saleSchema.post("save",async function(doc){
 //some actions on order model
 const order = await ordersModel.findOne({doc.orders[0],{})
})

module.exports = connection.model(saleSchema)

//file name : orders.model.js

const salesModel = require("./sales.model")
const connection = require("./database/connection")

const ordersSchema = new mongoose.Schema(
  {
    orderNumber : {type : String}
   
  },
  {
    timestamps: true,
  }
);

ordersSchema.post("save",async function(doc){
 //some actions on sales model
 const sale = await sales.findOne({order : doc._id},{})
 //send email for this sale
})

module.exports = connection.model(saleSchema)

Now since sale.model is requiring orders.model file and orders.model file is requiring sales.model file I am getting a circular dependency error and my question is what pattern can I use to avoid that

Aucun commentaire:

Enregistrer un commentaire