2

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.

4

2 回答 2

1

我没有使用过 mongojs,但任何数据库查找几乎肯定是异步的。这意味着您传递给的函数db.clusters.find不会立即运行,而是在异步调用从 mongo 返回时运行。不要从 中返回值retrieveVertById,而是尝试使用回调函数:

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);
});
于 2013-04-27T15:50:25.870 回答
0

哦,我明白了……你应该记住 javascript 是异步语言

return result;

forEach() 之后不会从 forEach() 内部返回结果。您应该在解析最后一个值后发送结果。

var i = 0;
clusters.forEach( function (cluster) {
    vert = cluster["vertices"];
    result.push(vert);
    if (i >= clusters.length)
        return result;
    i++;
});
于 2013-04-27T15:46:53.283 回答