In one of my Express middleware files, there is a function that calls a new instance of OrderController and utilizes the createOrder method.
import { Router } from "express";
import { OrderController } from "../../controller/orders.controller";
export const orderRouter = Router();
const orderController = new OrderController();
//Create an order
orderRouter.post("/", orderController.createOrder);
The issue lies in the fact that a fresh OrderController is created each time, causing the constructor to run again. Consequently, when accessing this.orderModel within createOrder(), it returns as undefined.
import { OrderModel } from "../database/model/order.model";
export class OrderController {
orderModel: OrderModel;
constructor() {
this.orderModel = new OrderModel();
}
async createOrder(req: Request, res: Response, next: NextFunction) {
const newOrder = ...
...
const order = await this.orderModel.save(newOrder);
res.json(order);
}
}
Any suggestions on how to address this?