我正在使用Node.js循环遍历从Mongoose获得的 Artist
结果数组:
User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
for (var i=0; i < artists.length; i++){
console.log(artists[i]);
}
})
以上代码可以找到并打印出我要求的 Artists
的所有三个属性。
编辑:这是我在控制台中看到的一个例子:
{
_id: 'T8fdSmf0e1ua',
BIO: 'This is Susan's bio...\n',
Firstname: 'Susan',
list_artworks: [
'ID ONE',
'ID TWO',
...
]
}
但是,当我尝试访问属于 Artwork
ID数组的属性时,使用 console.log()
来确定所有内容:
for (var i=0; i < artists.length; i++){
console.log(artists[i].list_artworks);
}
当我访问我的艺术家的其他属性时,例如 BIO
或 Firstname
,它会成功打印到我的控制台:
for (var i=0; i < artists.length; i++){
console.log(artists[i].BIO);
}
为什么会这样?在这种情况下,我不认为它与异步代码有关,因为所有对象都在 then()
链中返回。如果我打印整个 list_artworks
对象,那么 artist
属性显然就在那里,但是当我尝试访问它时为什么它未定义?
这是另一个例子。我打印出每个属性,然后打印出对象本身:
console.log(artist.BIO);
console.log("---------------")
console.log(artist.Firstname);
console.log("---------------")
console.log(artist.list_artworks);
console.log("---------------")
console.log(artist)
这是我的控制台上打印的内容:
---------------
Mike
---------------
undefined // <--- when I access the property itself
---------------
{
_id: '599asdsdasd232d23d2',
Firstname: 'Mike',
BIO: '',
list_artworks: // <-- why does it show up here?
[ '6cohpx7d23asu',
'W4Fgs23X5aXds',...
以下是我的整个代码库:
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);
答案 0 :(得分:2)
在艺术家身上致电toObject
:
artist = artists[i].toObject();
答案 1 :(得分:0)
试试这个
User.find({UserType: "Artist"}, '_id Firstname BIO list_artworks').then((artists) =>{
for (var i=0; i < artists.length; i++){
console.log(artists[i][‘list_artworks’]);
}
}
答案 2 :(得分:0)
试试这个:
User.find({UserType: "Artist"}, '_id Firstname BIOlist_artworks').then((artists) =>{
var index = i.toString();
console.log(artists[index][‘list_artworks’]);
}
}