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);
Call toObject
on the artist:
artist = artists[i].toObject();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With