Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple async mongo request in nodejs

How to write multiple queries in a row?

Like a

Space.findOne({ _id: id }, function(err, space) {
    User.findOne({ user_id: userid }, function(err, user) {
        res.json({ space: space, user: user});
    });
});

does not look good with more requests and logic

How is it done correctly?

I heard something about the promise, but I do not know.

Thanks

like image 312
AHOYAHOY Avatar asked Aug 06 '26 17:08

AHOYAHOY


1 Answers

When I've had a similar issue, I've used the async library.

async.parallel([
    function(callback){
       Space.findOne({ _id: id }, callback);
    },
    function(callback){
        User.findOne({ user_id: userid },callback);
    }
],
function(err, results){
    res.json({space:results[0],user:results[1]});
});

You can also use async.series if you want sequential execution.

like image 132
Benjamin Gruenbaum Avatar answered Aug 08 '26 09:08

Benjamin Gruenbaum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!