node.js - 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); // other things result
and... doesn't work (and know why). how can make works ?
it doesn't work because findone()
call asynchronous. when call console.log()
, execution of findone()
not finished yet. need call console.log()
inside 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 comment. if query in function , want use result of query in caller, need pass callback function. this, need modify function accept callback, example:
function exists(name, callback) { thecollecton.findone({name: name}, function(err,obj) { var result = (err || !obj) ? false : true; callback(result); }); }
and call function callback:
exists('hey', function(result) { if (result) { // something. } });
Comments
Post a Comment