Help with mongoose

1

Not understanding what happened:

ready = function() {
  groups = mongoose.model('groups', schemas.group);
  groups.find({}, function(err, docs){
    for(i in docs){
      console.log(docs[i].name);
    }
    return docs;
  });
}

console.log(ready());

OUTPUT:

undefined
Grupo A
Grupo B
Grupo C

was not it for him to print as in function? If someone can help me, I appreciate it.

    
asked by anonymous 19.03.2016 / 05:28

1 answer

1

As far as I can tell from your code, the .find() method is asynchronous. So you have to use a callback to get those results. The logic may look like this:

var ready = function(callback) {
  groups = mongoose.model('groups', schemas.group);
  groups.find({}, callback);
}

and then you call the function ready passing as an argument the function that will be called when the data is ready:

ready(function(err, docs){
    for(i in docs){
      console.log(docs[i].name);
    }
    // fazer algo com os dados aqui...
});

That is, you can not use the usual sequence logic JavaScript sync, but a callback logic. You can read more about this here (link) .

    
19.03.2016 / 21:37