Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js loop over array of objects asynchronously

Sorry if the title itself is a contradiction :) JS beginner here..

I get an array of MongoDB documents and I want to extend each one with another object (from another table) so that I can pass this array of extended objects to my view. I want to achieve something like this:

exports.myFunction = function(req, res) {
    Book.find({'good': true}).exec(function(err, docs) { // find good books
        // add authors to each book (?):
        for (var i = 0, i < docs.length; i++) {
            docs[i].author = Author.findOne({'_id': docs[i].author_id}); 
        }
        // render books:
        res.render('/books.ejs', {books: docs});
    });
}

I think this is not the JavaScript-way to do it :) So how can I achieve this?

Thanks,

like image 921
jeff Avatar asked Jan 01 '26 16:01

jeff


1 Answers

Use the $lookup function as found in the aggregation framework. The following example demonstrates how you can apply that in your case:

exports.myFunction = function(req, res) {
    Book.aggregate([
        { "$match": { "good": true } },
        {
            "$lookup": {
                "from": "authors"
                "localField": "author_id",
                "foreignField": "_id",
                "as": "author"
            }
        },
        { "$unwind": "author" }
    ]).exec(function(err, docs) { 
        res.render('/books.ejs', {books: docs});
    });
}
like image 113
chridam Avatar answered Jan 03 '26 09:01

chridam



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!