I created a dashboard that uses CanvasJS graphs to show data collected by embedded devices. My problem is to get the last ten documents from a cloudant DB for each one of the devices. I've already made a question to solve this problem by using a view, but looks like it isn't possible to do so.
The function getDeviceList()
uses a cloudant view to get the device list and then calls init()
to make a query for each one of the devices, then push the data to an object that stores all the device data. The code works with 10 devices, but I don't know if it will for more devices.
function getDeviceList() {
//first, get the device names
sensordb.view("name", "countDevice?group=true", function(err, body) {
if (err) {
console.log(err);
return;
}
//clear device array before pushing new values
let devices = [];
body.rows.forEach(function(id) {
devices.push(id.key);
});
console.log("Device list:" + JSON.stringify(devices));
init(devices);
});
}
function init(deviceArray) {
//for each device, make a cloudant query to retrieve the last ten docs
for (let i = 0; i < deviceArray.length; i++) {
sensordb.find({
"selector": {
"deviceID": deviceArray[i],
"timestamp": { "$gt": 0 }
},
"limit": 10,
"sort": [{ "timestamp": "desc" }]
},
function(err, data) {
if (err) {
console.log("Error while fetching data");
console.log(err);
return;
} else {
console.log("Done fetching data for " + deviceArray[i]);
//revert array for CanvasJS graph
data.docs.reverse();
var key = deviceArray[i];
var obj = {};
deviceData[key] = data.docs;
// deviceData.push(obj);
}
});
}
}
What could be done better about this code? It looks very costly and unstable, even if it works with 10 devices.
This is how the object that stores all the data looks like:
{"firstDevice":[{first doc},{second doc}... {tenth doc}],
"secondDevice":[{first doc},{second doc}... {tenth doc}],
...
"tenthDevice":[{first doc},{second doc}... {tenth doc}]}
And the device data is accessed using deviceDataArray[deviceName]
.