[英]Node js Mongodb collection.find() query result outside scope
I wane collection.find() query result outside the queryfunctin 我在queryfunctin之外希望collection.find()查询结果
var fol; var fol;
Folder
.find({'parentid':id,'stats.archive':'0'})
.lean()
.exec(function(err, f_folder) {
if(!err) {
fol = f_folder;
}
});
console.log(fol); // I want query result here
Please, give me solutions why query does not return result outside function 请给我解决方案,为什么查询不会在函数外部返回结果
The console.log()
called outside the callback passed to the exec()
will be executed before the exec()
function return. 在传递给
exec()
的回调之外调用的console.log()
将在exec()
函数返回之前exec()
。
What you need to do, as @VsevolodGoloviznin said, is to call the console.log()
inside the callback, like: 正如@VsevolodGoloviznin所说,您需要做的是在回调内部调用
console.log()
,例如:
Folder
.find({'parentid':id,'stats.archive':'0'})
.lean()
.exec(function(err, f_folder) {
if(!err) {
fol = f_folder;
console.log(fol);
}
});
That will guarantee that your fol
var will not be undefined
. 这将确保您的
fol
var不会被undefined
。
What you could also do is to wrap the logic inside functions: 您还可以做的是将逻辑包装在函数内部:
function findFolder(callback) {
Folder
.find({'parentid':id,'stats.archive':'0'})
.lean()
.exec(function(err, f_folder) {
if(!err) {
fol = f_folder;
callback(fol);
}
});
}
function logResult(result) {
console.log(result);
}
findFolder(logResult);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.