Saturday, 15 April 2017

asynchronous function call the loop, loop call another asynchronous function call

I am using mLab for database and mongoose in node js.I am using swagger which should not cause any problem. I have following schemas. when user request, I need to return movie and review together if (review = true) in query. One movie may have multiple reviews. first, I have to find all the movies in the database. when I find movies, I have to go through each of them, look for any reviews in another database and somehow attach them in movie. I need to return all the movies in one package because it will be used in getAll fucntion. No matter what I do it only returning movies without reviews.

var mongoose = require('mongoose');

var reviewSchema = new mongoose.Schema({
    movie:      {type: String, required: true},
    reviewer:   {type: String, required: true},
    rating:     {type: Number, required:true, min: 1, max: 5},
    text:       {type: String, required: true},
})


var movieSchema = new mongoose.Schema({
    Title:          {type: String, required: true, unique: true},
    YearReleased:   {type: Number, required: true},
    Actors:         [{
                        Name: {type: String, required: true}
    }]
})

.

function getAll(req,res,next){
    db.Movies.find({},function(err,movies){
        if(err) throw {err:err};
        if(req.swagger.params.review.value === false)
            res.send({Movielist: movie});
        else {
            movies.forEach(function(movie, index){
                db.Reviews.find({movie:movies[index].Title}, function (err, review) {
                    if(err) throw {err:err}
                    movies[index].Review = review    // I am trying to populate each movie with reviews
                });
            });
            res.send({Movielist: movies});
        }

    });
}


via LostCoder

No comments:

Post a Comment