I am trying to populate Array asynchronously with data captured from MongoDB. I have a set of functions, which should execute one by one to merge 2 results from different tables into one, but upon execution, error is porduced:
TypeError: Cannot read property 'apply' of undefined
Here is a code of the router:
var Co2 = require("./../models/co2.model"),
Dht = require("./../models/co2.model"),
express = require("express"),
q = require("q"),
router = express.Router();
router.get("/all", function(req, res, next) {
var co2Collector = function() {
Co2.showAll(function(err, results) {
co2Data = [];
if (err) {
res.json(err);
}
for (i = 0; i < results.length; i++) {
co2Data.push(results[i]);
}
return co2Data;
});
};
var dhtCollector = function() {
Dht.showAll(function(err, results) {
dhtData = [];
if (err) {
res.json(err);
}
for (i = 0; i < results.length; i++) {
dhtData.push(results[i]);
}
return dhtData;
});
};
var dataMerge = function(co2Data, dhtData) {
mergedData = [];
mergedData = mergedData.concat(co2Data, dhtData);
res.json({
message: "Done!",
result: mergedData
});
};
q
.fcall(co2Collector())
.then(dhtCollector())
.then(dataMerge())
.done();
});
module.exports = router;
The logic seems to be correct to me, but, then again, I am new to this kind of stuff and documentation is a little bit vague for my understanding. Thanks for the help!
P.S: Can the issue be in the Schema and static method? In return, no matter what adjustments are made to the code, result is either undefined
, either null
.
Here is my mongoose schema:
var CO2Schema = mongoose.Schema(
{
location:{ type: String,required: true },
reading: { type: String, required: true }
},
{
timestamps: { createdAt : 'created_at', updatedAt : 'updated_at' },
}
);
// Get CO2 results
CO2Schema.statics.showAll = function(cb) {
return this.find({}, cb);
};