Bryan Wheeler
Bryan Wheeler

Reputation: 125

Mongoose query callback return?

This is a general question, but why does the mongoose query function in, for example:

var myFunc = function(username, callback){
    User.findOne({username: username}, 'username name, password', function(err, user){
      callback(user);
    });
};

myFunc('somename', function(userInfo){
    console.log(userInfo);
});

require another function to return user? Why can't I simply:

var myFunc = function(username){
    User.findOne({username: username}, 'username name, password', function(err, user){
      return user;
    });
};

var userInfo = myFunc('somename');
console.log(userInfo);

Upvotes: 1

Views: 1909

Answers (2)

Bryan Wheeler
Bryan Wheeler

Reputation: 125

You are working with an async operation, which means you cannot return the value because no value exists when the Node environment reaches your return statement.

The database operation takes time, during that time your DB lookup code has finished execution and Node is either finishing code in the current call stack, working on another task it gets from the Node event queue, or sitting idle.

Once your db value is returned, your callback is placed on the Node event queue ready to be consumed by the Node environment and printed to console.

If there is say, another url request that comes in between your database lookup call and the database value being returned, Node will set a worker thread to handle your database request and another to handle the database operation. When the workers finish their tasks (the URL request and the database lookup), it pushes the callback to the event queue. When there is no code for Node to read (the stack is empty) it goes to the event queue and executes those tasks in order.

Upvotes: 1

abdulbari
abdulbari

Reputation: 6242

As Node.js is executed in an asynchronous way sometimes it fails to get the result in userInfo if your query gets a long time.

Then for making sure that the userInfo value, you have to use callback or Promise.

For more details about Node.js asynchronous nature you can see here

http://www.sohamkamani.com/blog/2016/03/14/wrapping-your-head-around-async-programming/] 1

https://blog.risingstack.com/node-hero-async-programming-in-node-js/

Upvotes: 2

Related Questions