Prasanth Bendra
Prasanth Bendra

Reputation: 32740

Loop is not working in node.js

Here is my code :

for (var j in albums){
    var album_images   = albums[j].images
    var l = album_images.length
    for ( var i = 0; i < l; i++ ) {
        var image  = album_images[i]
        Like.findOne({imageID : image._id, userIDs:user._id}, function(err,like){
            if(like){
                console.log(i)
                //console.log(albums[j].images[i])
                //albums[j].images[0].userLike = true;
            }
        })
     }
}

Here I have albums, and I am populating images of album So album variable contains all the albums and inside them their images will also be there in a array

I want to add a extra field (userLike) in each images.

Problem here is all the time the value of the i is 3 (that is the number of images in a album (album_images.length) - for the time being I have only one album)

I think the problem could be because the callback of Like.findOne calls only when all the loops has finished executing (just a guess).

How can I make it work so that I will get all the loop values in console.log(i) ?

Thanks in advance

Upvotes: 0

Views: 72

Answers (2)

Tim Brown
Tim Brown

Reputation: 3241

Alternatively you could define a function in order to have a scope where the variable doesn't change.

...
handle_album_image = function(image, i, j) {
    Like.findOne({imageID : image._id, userIDs:user._id}, function(err, like){
        if(like){
            console.log(i)
            //console.log(albums[j].images[i])
            //albums[j].images[0].userLike = true;
        }
    })
}

for ( var i = 0; i < l; i++ ) {
    var image  = album_images[i]
    handle_album_image(image, i, j)
 }

Upvotes: 0

robertklep
robertklep

Reputation: 203304

I prefer using forEach:

albums.forEach(function(album, j) {
  var album_images = album.images;
  album_images.forEach(function(image, i) {
    Like.findOne(...);
  });
});

Just a tip: instead of performing a findOne for each image, you may consider using $in.

Upvotes: 2

Related Questions