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