Mongoose在主代码中找到使用结果

时间:2014-05-29 16:41:31

标签: node.js mongodb mongoose

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

而且......它不起作用(我知道为什么)。 我怎样才能使它有效?

1 个答案:

答案 0 :(得分:2)

它不起作用,因为findOne()调用是异步的。当您致电console.log()时,findOne()的执行尚未完成。您需要在异步函数中调用console.log()

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

修改:回复评论。如果此查询位于函数中并且您希望在调用者中使用查询结果,则需要将回调传递给该函数。为此,您需要修改函数以接受回调,例如:

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

然后使用回调调用此函数:

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