0
votes

I am trying to make one rather basic code to work but receive a browser error. expressjs logs shows an error as well.

TypeError: Cannot read property 'myDate' of undefined at getReportTable (XXX\dist\controllers\crm\uploadHealthTable.js:18:70) at Layer.handle [as handle_request] (XXX\node_modules\express\lib\router\layer.js:95:5) at next (XXX\node_modules\express\lib\router\route.js:137:13)

import { Request, Response } from "express";
import * as mongoose from "mongoose";
import { uploadHealthTableSchema } from "../../models/crm/uploadHealthTableModel";

const reportTable = mongoose.model("USER_UPLOAD", uploadHealthTableSchema);

export class UploadHealthTable {

private myDate = new Date() ;

    public getReportTable(req: Request, res: Response) {
    reportTable.find({companyId: "18", uploadTime: { $gte: this.myDate.setDate(this.myDate.getDate() - 5) } },
    "_id fileName status uploadTime", { sort: {uploadTime: -1} }, (err, report) => {
        if (err) {
        res.send(err);
        }
        res.json(report);
    });
    }
}

Call to this function -

export class CRMRoutes {
    public uploadHealthTable: UploadHealthTable = new UploadHealthTable() ;

    public routes(app: any): void {

        app.route("/support/reporttable/1/all")
        .get(this.uploadHealthTable.getReportTable) ;
    }
}
1
how are you calling getReportTable?WayneC
I am using expressjs (MEAN stack) and in the routes.ts file, calling below line - app.route("/support/reporttable/1/all") .get(this.uploadHealthTable.getReportTable) ;Dhaval Chokshi

1 Answers

1
votes

You need to convert this function to an arrow function

public getReportTable = (req: Request, res: Response) => {}

Explanation: Because you passed the function as an argument, the this value is still at the previous function context