I have a function below within the back-end of my application, and the aim is to return all Sensors associated with a specific thingID.
I was approaching this by populating a new array allSensors, however when logged below
console.log(allSensors); res.send(allSensors) it is an empty array []
I should also note that individual elements of sensor log correctly
I've moved the
console.log(allSensors) Into the sensor.findOne loop, and it prints out the elements correctly.
existingThing.sensors.forEach(function (element) { Sensor.findOne({_id: element._id}, function (err, sensor) { if(sensor){ // console.log(sensor); allSensors.push(sensor); console.log(allSensors); // this works.... } }) }); Any ideas as to this behaviour? Thanks
//get all sensors associated with thingid app.get('/api/things/:thingid/sensor', function (req, res) { var allSensors = []; Thing.findOne({ thingID: req.params.thingid }, function (err, existingThing) { if (!existingThing) return res.status(409).send({ message: 'Thing doesnt exist' }); if (existingThing.sensors.length < 0) return res.status(409).send({ message: 'No sensors' }); existingThing.sensors.forEach(function (element) { Sensor.findOne({_id: element._id}, function (err, sensor) { if(sensor){ // console.log(sensor); allSensors.push(sensor); } }) }); }) console.log(allSensors); //empty res.send(allSensors); //empty })
forEachcompletes – you must also make sure eachfindOnecall completes too. You'll probably want the async library for this.