user3491456
user3491456

Reputation: 377

Mongoose find use result in the main code

var mongoose = require('mongoose');

var result = false;

thecollecton.findOne({name: "hey"}, function(err,obj) { 
    if(err) console.log(err);
    if(obj) result=true;
});

 console.log(result);
 // do other things with result

And... it doesn't work (and I know why). How can I make it works ?

Upvotes: 0

Views: 83

Answers (1)

Gergo Erdosi
Gergo Erdosi

Reputation: 42028

It doesn't work because the findOne() call is asynchronous. When you call console.log(), the execution of findOne() is not finished yet. You need to call console.log() inside the asynchronous function:

var mongoose = require('mongoose');

var result = false;

thecollecton.findOne({name: "hey"}, function(err,obj) { 
    if(err) console.log(err);
    if(obj) result=true;
    console.log(result);
});

Edit: Replying to the comment. If this query is in a function and you want to use the result of the query in the caller, then you need to pass a callback to the function. For this, you need to modify the function to accept a callback, for example:

function exists(name, callback) {
  thecollecton.findOne({name: name}, function(err,obj) {
    var result = (err || !obj) ? false : true;
    callback(result);
  });
}

And then call this function with a callback:

exists('hey', function(result) {
  if (result) {
    // Do something.
  }
});

Upvotes: 2

Related Questions