无法访问数组中的mongoDB对象 - 返回undefined

时间:2015-09-11 19:54:50

标签: mongodb database

当我试图在mongoDB中访问数组中的对象时,我遇到了一个非常大的问题。

首先,我发现id键的值为" mens"在我的数据库集合"类别":

mongodb.db().collection("categories").find({id: "mens"}).toArray(function(err, data) {
    console.log(data);
}

当我尝试在控制台中输出结果时,它显示了这个:

[ { _id: 5172d1daffdd81f3234d5f88,
    categories: [ [Object], [Object] ],
    id: 'mens',
    name: 'Mens',
    page_description: 'Men\'s range. Hard-wearing boots, jackets and clothing for unbeatable comfort day in, day out.
 headed.',
    page_title: 'Men\'s Footwear, Outerwear, Clothing & Accessories',
    parent_category_id: 'root',
    c_showInMenu: true } ]

但是当我尝试用例如name或page_title获取时:

mongodb.db().collection("categories").find({id: "mens"}).toArray(function(err, data) {
    console.log(data.page_title);
}

它返回UNDEFINED! ! !

1 个答案:

答案 0 :(得分:0)

返回的数据是一个数组,因此您需要以data[0].page_title的形式访问数组中的对象,即

mongodb.db().collection("categories").find({id: "mens"}).toArray(function(err, data) {
    console.log(data[0].page_title); // prints "Men's Footwear, Outerwear, Clothing & Accessories"
}
相关问题