使用Express在Mongoose中进行两次数据库查询 [英] Two database queries in Mongoose with Express
问题描述
有很多实例我必须进行两个相互依赖的数据库查询。但是由于js的异步性质,我无法设置这些查询请求的顺序。我一直在使用的工作是将其中一个查询放在另一个的回调中。我的方法似乎有效,但我只是想知道是否有更好的方法来做到这一点?
There are a lot instances where I have to make two database queries that depend on each other .. But because of the asynchronous nature of js, I can't set the order of these query requests. The work around I have been using is put one of the queries in the callback of the other one. My approach seems like its working but I just want to know if there are better ways of doing this?
示例代码:
app.get('/tweet', function(req,res){
User.findOne({ twitterID: req.user.id },
function(err, user) {
if (user){
var votedPosts = user.votedPosts;
Post.find(function (err, posts) {
if(posts){
for (var i = 0; i < posts.length; i++){
for (var j = 0; j < votedPosts.length; j++){
if(votedPosts[j]._id == posts[i]._id){
posts[i].votetype = votedPosts[j].votetype;
}
else{
console.log("this is getting called");
posts[i].votetype = 0;
}
}
}
res.send(posts);
}
});
}
});
});
推荐答案
是的,有很多流量控制库需要解决深层嵌套的回调问题。我建议 async 或灵活,但承诺是解决此问题的另一种流行模式。
Yes, there are many many flow control libraries to solve the deeply nested callback problem. I recommend async or nimble, but promises is another popular pattern that solves this problem.
添加代码时的基本进程随着时间的推移变得越来越长并且嵌套得越来越深:
The basic progression as you add code and it gets longer and more deeply nested over time is:
- 使用少量代码处理1或2个嵌套级别。它并没有那么糟糕。
- 将东西提取到顶级命名函数并调用它们(大多数node.js核心代码试图不超出这一点)
- 使用库(自定义API或基于promises模式)
有一个节点维基上的流程控制模块的长列表。你也可以搜索 npm
这篇关于使用Express在Mongoose中进行两次数据库查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!