Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array property in Javascript object is undefined

I'm using Node.js to loop through an array of Artist results I obtain from Mongoose:

User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
    for (var i=0; i < artists.length; i++){
        console.log(artists[i]);
    }
})

The above code works find and prints out all three properties of Artists that I asked for.

EDIT: Here's an example of what I see in console:

{
    _id: 'T8fdSmf0e1ua',
    BIO: 'This is Susan's bio...\n',
    Firstname: 'Susan',
    list_artworks: [
        'ID ONE',
        'ID TWO', 
        ...
    ]
}

However, when I try to access a property that is an array of Artwork ids, everything is undefined using console.log():

for (var i=0; i < artists.length; i++){
    console.log(artists[i].list_artworks);
}

When I access the other properties of my Artist, like BIO or Firstname, it prints successfully to my console:

for (var i=0; i < artists.length; i++){
    console.log(artists[i].BIO);
}

Why is this the case? I don't think it has to do with async code in this case given that all objects are return in the then() chain. The list_artworks property is clearly there if I print the entire artist object, but why is it undefined when I attempt to access it?

Here's another example. I print out each property, and then the object itself:

console.log(artist.BIO);
console.log("---------------")
console.log(artist.Firstname);
console.log("---------------")
console.log(artist.list_artworks);
console.log("---------------")
console.log(artist)

And here's what is printed on my console:

 
---------------
Mike
---------------
undefined // <--- when I access the property itself
---------------
{
  _id: '599asdsdasd232d23d2',
  Firstname: 'Mike',
  BIO: '',
  list_artworks: // <-- why does it show up here?
   [ '6cohpx7d23asu',
     'W4Fgs23X5aXds',...

Here is my entire code base:

setTimeout(function(){

     User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
         console.log(artists.length);

        for (var i=0; i < artists.length; i++){
            artist = artists[i];
             console.log(artist.BIO);
             console.log("---------------")
             console.log(artist.Firstname);
             console.log("---------------")
            console.log(artist['list_artworks']);
             console.log("---------------")
             console.log(artist)
            }
        }

     ).catch((err)=>{console.log(err)});
}, constants.NLP_TRAINING_INTERVAL);
like image 717
Yu Chen Avatar asked Jul 08 '17 17:07

Yu Chen


1 Answers

Call toObject on the artist:

artist = artists[i].toObject();
like image 79
Andy Gaskell Avatar answered Sep 25 '22 01:09

Andy Gaskell