我想查找带有最新"sorting_index"字段的文档.我试试这样:
var sorting_index = -1;
this.findOne().sort({'sorting_index': -1}).exec(function(err, doc) {
if (err) return;
sorting_index = doc['sorting_index']; // sorting_index == 10
});
console.log(sorting_index); // sorting_index == -1
Run Code Online (Sandbox Code Playgroud)
问题是回调是异步的.如何同步?
简短的回答 - 你不能.
如果您希望代码是同步的,则应考虑使用其他工具代替node.js.
node.js中的所有I/O操作都是异步的,因此如果您想使用node.js,那么您应该学习如何处理异步代码:
this.findOne().sort({sorting_index: -1}).exec(function(err, doc) {
if (err) throw err;
var sorting_index = doc['sorting_index'];
console.log(sorting_index); // sorting_index == 10
});
Run Code Online (Sandbox Code Playgroud)
还有许多有用的工具来简化异步代码:async.js,promises,ES6生成器(node.js 11.x)等.