2

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 }) 
3

1 Answer 1

1

Install the async library. (It's a seriously useful library, and if you do not use it, you will probably have to reinvent it). Then use this code:

async.each(existingThing.sensors, function(element, _cb) { Sensor.findOne({ _id: element._id }, function(err, sensor) { if(sensor) { allSensors.push(sensor); } _cb(); }); }, function() { console.log(allSensors); res.send(allSensors); }); 
Sign up to request clarification or add additional context in comments.

1 Comment

Great thank you, fairly new to JS so keep missing little things like this..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.