0

I have this file that is called from another express middleware, it creates a new OrderController instance that has the function createOrder.

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 problem is that a new OrderController is initiated meaning that the constructor is executed, but when this.orderModel accessed inside of createOrder() its 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 ideas?

Thanos Sakis
  • 91
  • 13

1 Answers1

1

The constructor is executed, but the way you pass createOrder loses its reference to this.

Use one of the following two lines to fix this:

orderRouter.post("/", orderController.createOrder.bind(orderController));
orderRouter.post("/", (...args) => orderController.createOrder(...args));
Evert
  • 93,428
  • 18
  • 118
  • 189