Wednesday, 12 April 2017

Res.send proceed before Function Model.find() Nodejs

I got the problem when trying to find the value throw 2 model

.get(function(req, res) {
        var sellerPosts = [];
        Product.find({seller_id : req.params.seller_id}, function(err, products) {
            if (err) throw err;
            for (var i = 0; i < products.length; i++) {
                console.log("id", products[i].id);
                Post.find({product_id : products[i].id}, function(err, posts) {
                    if (err) throw err;
                    for (var j = 0; j < posts.length; j++) {
                        sellerPosts.push(posts[j]);
                        console.log("in find",sellerPosts);

                    }
                });
                console.log(sellerPosts);
            }
            console.log("test", sellerPosts);

            res.send(sellerPosts);
        });

    })

The first sellerPosts still print out true values but the "test" log is empty. After doing some log. I think it is because after the first for in Product.find(), the program run the res.send and then run the Post.find(). Help me on fixing this problem please!!!!



via Tung Mai

No comments:

Post a Comment