我是node js和mongoose的新手。我正在尝试从以下答案的执行的猫鼬查询中检索用户:stack-overflow-answer
这是我的控制器代码(它同时包含:回调和promises方法)
exports.getUser = (req, res, next) => {
var searchQuery = {...};
var result = [];
User.find(searchQuery, function (err, found) {
console.log(" >>>> inside", found)
result = found;
}
)
console.log(" >>>> outside ", result)
var result2 = [];
User.find(searchQuery)
.exec()
.then(function(found){
console.log(" >>>> inside", found)
result2 = found
return found
}
)
console.log(" >>>> outside ", result2)
res.status(200).json(result)
}
在这两种情况下,在控制台中都是在回调内部打印查询结果,而在外部则保持空白,为什么?
感谢帮助:)
答案 0 :(得分:1)
如果您的环境支持异步/等待,则还可以执行以下操作:
exports.getUser = async (req, res, next) => {
const searchQuery = {...}
const result = await User.find(searchQuery)
res.status(200).json(result)
}
答案 1 :(得分:0)
我无法真正理解您要执行的操作,但是您的代码应类似于:
exports.getUser = (req, res, next) => {
// 1: first query
var searchQuery = {...};
User.find(searchQuery, function (err, foundX) {
// 2: second query
var searchQuery = {...};
User.find(searchQuery, function (err, foundY) {
// 3: send response
res.status(200).json(foundY);
});
});
}
您需要等待异步代码被执行。