Help with the Mongoosis

Asked

Viewed 112 times

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());

EXIT:

undefined
Grupo A
Grupo B
Grupo C

within the ready() function it brings everything normally, but in the "console.log(ready())" it prints "Undefined"

Wasn’t he supposed to print it out? If anyone can help me I appreciate

  • People discover the problem. what’s happening is that the "ready" function returns before the callback "groups.find()" is called. anyone has any suggestions what I can do to resolve this?

  • Explain what you want to do so that we can give a concrete example. You have an asynchronous proplema, very commun in the Node. What do you want to do with this ready? do you want to have a variable that tells you if the query has already been made?

  • this. A ready has the function to read all the records of the database and return them

1 answer

1


I understand from your code the method .find() is asynchronous. So you have to use a callback to get these results. Logic can be like this:

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

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

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

That is, you cannot use the usual sequential logic of synchronous Javascript, but a callback logic. You can read more about it here (link).

  • 1

    That’s right, problem solved, obg Sergio helped me a lot

Browser other questions tagged

You are not signed in. Login or sign up in order to post.