无法访问数组中的 mongoDB 对象 - 返回未定义

问题描述 投票:0回答:2

当我尝试访问 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 } ]

但是当我尝试使用以下命令获取例如名称或 page_title 时:

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

它返回未定义! ! !

mongodb database
2个回答
1
投票

返回的数据是一个数组,因此需要以

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"
}

0
投票

您可以使用猫鼬模式。 `

const categoriesSchema = new mongoose.Schema({
    categories: {type : Array},
    id: {type : String},
    name: {type : String},
    page_description: {type : String},
    page_title: {type : String},
    parent_category_id: {type : String},
    c_showInMenu: {type : Boolean}  });
const dataTahunAjaran = mongoose.models.categories || mongoose.model('categories', categoriesSchema);

然后你就可以访问

page_title:
甚至可以访问对象内部的对象内部的对象甚至非常深的内部 `

© www.soinside.com 2019 - 2024. All rights reserved.