[英]How to handle the inner query in nodejs?
在nodeJS中創建了一個Rest Post類型的API,其中:我在這里執行兩個查詢。 1.首先在答案表上執行查詢,以獲取該表中的用戶ID和答案詳細信息。 //我已經在我的控制台中檢查了它們向我顯示的兩個用戶ID。第二,對用戶表執行查詢以根據我傳入的find函數的用戶ID獲取用戶詳細信息。 //檢查我的控制台,因為我有兩個用戶ID,所以它們向我顯示了兩個答案對象。 ------------------上面的程序工作正常---------------------現在,我被卡住了,因為我有兩個合並兩個結果到一個對象。 我正在執行此操作,但效果並不理想。請在這里幫助我!
我的代碼:-
app.post('/getTopAns', function(req, res) {
console.log("inside getTopAns ");
var questionId=req.body.questionId;
mongoose.model('answers').find({
questionId:questionId,
compliance:"Y"
}, function(err, ansResult){
for (var i = 0;i<ansResult.length;i++) {
mongoose.model('users').findOne({
userId:ansResult[i].userId,
}, function(err,usrResult){
var obj = {
followerLength : usrResult.follower.length,
upvote : ansResult[i].upvote
}
})
console.log(obj);
}
});
})
也許您應該首先登錄ansResult來查看db是否正在返回此結果。 如果是,則檢查usrResult。 如果兩個都返回,我通常使用lodash的assign或merge將兩個對象合並為一個
我建議使用promise而不是回調,以便通過node.js更輕松地處理異步。 流程是獲取第一個調用結果,將結果數組映射到Promise.all
列表中,我們可以使用Promise.all
等待結果。 最后將第二個結果映射到第一個列表中。
app.post("/getTopAns", function(req, res) {
console.log("inside getTopAns ");
var questionId = req.body.questionId;
mongoose.model("answers")
.find({
questionId: questionId,
compliance: "Y"
})
.then(ansResult => {
const promises = ansResult.map(ans => {
return mongoose.model("users")
.findOne({ userId: ansResult[i].userId })
})
return Promise.all(promises)
.then(usrResults => {
return usrResults.map((usrResult, i) => {
followerLength: usrResult.follower.length,
upvote: ansResult[i].upvote
})
})
})
.then(results => {
console.log('got all results here', results)
})
});
使用async/await
可能會更好。
app.post("/getTopAns", async (req, res) => {
console.log("inside getTopAns ");
var questionId = req.body.questionId;
const ansResult = mongoose.model("answers")
.find({
questionId: questionId,
compliance: "Y"
})
const promises = ansResult.map(ans => {
return mongoose.model("users")
.findOne({ userId: ansResult[i].userId })
})
const usrResults = await Promise.all(promises)
const results = usrResults.map((usrResult, i) => {
followerLength: usrResult.follower.length,
upvote: ansResult[i].upvote
})
console.log('got all results here', results)
});
可以在這里找到更多信息: https : //medium.com/@ThatGuyTinus/callbacks-vs-promises-vs-async-await-f65ed7c2b9b4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.