Question

I'm working with mongojs and I have to retrieve a field from an object taken from mongodb. I can not understand how to return the field:

  function retrieveVertById(id){

  var result = [];
  db.clusters.find({id: id}, function (err, clusters){
  if( err || !clusters) console.log("No cluster found");
  else clusters.forEach( function (cluster) {

    vert = cluster["vertices"];
    result.push(vert);
    console.log(result);


   });
 })
return result;
};

var a = retrieveVertById("001");
console.log(a);

The print inside the 'forEach' prints the correct value: (ex. [ [ [ 8, 2, 2 ], [ 2, 2, 5 ], [ 2, 2, 2 ], [ 5, 2, 2 ] ] ] ) On the contrary the print outside the cycle shows an empty array. what does not work with the return? Thanks in advance for your help.

Was it helpful?

Solution

I've not used mongojs, but any db lookup will almost certainly be asynchronous. This means the function you passed to db.clusters.find will not run immediately, but rather when the asynchronous call returns from mongo. Instead of returning a value from retrieveVertById, try a callback function instead:

function retrieveVertById(id, successCallback) {

  db.clusters.find({
    id: id
  }, function (err, clusters) {
    if (err || !clusters) {
        console.log("No cluster found");
    } else {
        var result = [];
        clusters.forEach(function (cluster) {
            vert = cluster["vertices"];
            result.push(vert);
        });
        successCallback(result);
    }
  });
};

retrieveVertById("001", function(result) {
  console.log(result);
});

OTHER TIPS

oh, i see... you should remember that javascript is async language

return result;

after forEach() will not return result from inside forEach(). you should send result after last value parsed.

var i = 0;
clusters.forEach( function (cluster) {
    vert = cluster["vertices"];
    result.push(vert);
    if (i >= clusters.length)
        return result;
    i++;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top