Two database queries in Mongoose with Express

2020-07-26 11:39发布

问题:

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?

example code:

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);
                  }
                });
          }
    });
});

回答1:

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:

  • deal with 1 or 2 nesting levels with small amounts of code. It's not that bad.
  • Extract things to top-level named functions and call them (most node.js core code tries not to get beyond this point)
  • use a library (either custom API or based on the promises pattern)

There is a long list of flow control modules on the node wiki. You could also search npm