0

I'm facing some issue in calling a function in my Nodejs application. The main code is this one:

var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var app = express();

//------------------------------------
//Configuration
//------------------------------------
var config = require('./config.js');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//CORS Fixing
var cors = require('cors');
app.use(cors());

//------------------------------------
//Routes
//------------------------------------
app.use('/machine',     require('./app/routes/machine.js'));

//------------------------------------
//Server Start
//------------------------------------
mongoose.connect(config.DATABASE, { useNewUrlParser : true });
app.listen(config.SERVICE_PORT,config.SERVICE_IP);

Briefly my app uses routes like this:

var express = require('express');
var router = express.Router();
var MachineManager = require("../managers/MachineManager");

router.route('/:id/addInsurance').post(function(req,res){
    MachineManager.addInsurance(req.machine,req.body.emission,req.body.annual_fee,req.body.num_installment,req.body.company,function(err,data){
        if(err || !data){
            res.json({
                success: false,
                message: 703,
                data: data
            });
        }else{
            res.json({
                success: true,
                message: 803,
                data: data
            });
        }
    });
});

The logic is in the Manager where there are all my queries for the mongoDB.

I'm not able to call refreshExpInsurance in the other functions of the manager:

var Machine = require('../models/machine.js');
var config = require('../../config.js');
var _ = require('lodash');

var Manager = {
addInsurance: function(machine, emission, annual_fee, num_installment, company, callback){
        machine.update({
            $push: {
                "insurance":{
                    $each: [{
                        "emission": emission,
                        "annual_fee": annual_fee,
                        "num_installment": num_installment,
                        "freeze" : false,
                        "company": company
                    }], $position : 0
                }
            }
        }, function(err,data){
            if (err || !data) callback(err, null);
            else this.refreshExpInsurance(machine, callback);
        });

    },
....

    refreshExpInsurance(machine, callback){
        c = new Date(machine.insurance[0].emission);
        installments = 12 / machine.insurance[0].num_installment;
        if(machine.insurance[0].payed_installment) installments = installments * machine.insurance[0].payed_installment;
        c = new Date(c.getFullYear(), c.getMonth() + installments, c.getDate()+1);
        from = new Date(machine.insurance[0].freeze_from);
        to = new Date(machine.insurance[0].freeze_to);

        diffTime = Math.abs(from - to);
        diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

        delta = new Date(
            c.getFullYear(),
            c.getMonth(),
            c.getDate() + diffDays
        );

        date = delta.toISOString().substr(0,10);
        machine.updateOne({ "exp_insurance": date },callback);
    }

In this way, the refreshExpInsurance can't be found and the following error is raised:

TypeError: this.refreshExpInsurance is not a function

pittuzzo
  • 452
  • 6
  • 23
  • Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Yury Tarabanko Oct 16 '19 at 07:46
  • 1
    TL;DR; Use arrow function when you want to have correct context in callback. `(err, data) => {.... this.refresExpInsurance...}` – Yury Tarabanko Oct 16 '19 at 07:47
  • Thank you Yury, this was solving my issue... But I saw that the $push did not have effect on the machine that is passed to the refresh function, while in the database it is correctly updated. How should I handle it? – pittuzzo Oct 16 '19 at 08:09
  • What is your `MachineManager`? Is that a class? A module? A plain JavaScript object ? – Jérémie L Oct 16 '19 at 09:07
  • I updated the post in order to better show my code – pittuzzo Oct 16 '19 at 10:10

0 Answers0