mongoDBの配列内のオブジェクトにアクセスしようとすると、非常に大きな問題が発生します。
最初に、データベースコレクション「categories」のどこで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を返します!!!
あなたに、配列内のオブジェクトにアクセスする必要があるので、返されたデータは、配列である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"
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加