Node.js | 对象属性可用但返回“undefined”

3

我已经尝试解决这个问题大约两个小时了。我在Nodejs中返回一个对象。这个对象有3个属性。我可以访问前两个属性,但是当我尝试访问第三个属性时,我得到了“undefined”警告。我快要疯了,请你帮帮我好吗?

请求:

  const categories = await Categories.find({}); //mongoose query
  console.log(categories[0]); //its returning Object
  console.log(categories[0].category); //its returning  []
  console.log(categories[0]._id); //its returning  new ObjectId("6257233b897c3b8785ff625b")
  console.log(categories[0].mainCategories); //its returning  undefined ?? wtf?!
  console.log(categories[0].hasOwnProperty("category")); //its returning false
  console.log(categories[0].hasOwnProperty("_id")); //its returning false
  console.log(categories[0].hasOwnProperty("mainCategories")); //its returning false

对象结果:

{
  category: [],
  _id: new ObjectId("6257233b897c3b8785ff625b"),
  mainCategories: [
    { id: 1000010100, name: 'Konut', subCategories: [Array] },
    { id: 1000010200, name: 'Devremülk', subCategories: [Array] },
    { id: 1000020100, name: 'İşyeri', subCategories: [Array] },
    { id: 1000020200, name: 'Arazi', subCategories: [Array] },
    {
      id: 1000020300,
      name: 'Turistik İşletme',
      subCategories: [Array]
    }
  ]
}

enter image description here


1
请将相关代码作为文本放入问题中,而不是作为图像。出于许多原因,这在此处是必需的。 - jfriend00
1
我猜这也涉及到原型。看起来像是属性遮蔽的情况,可能是原型链中更高层次的属性遮蔽了你在第一个 console.log 中看到的内容。你可以尝试使用 categories[0].__proto__.mainCategoriescategories[0].__proto__.__proto__.mainCategories - Christian Vincenzo Traina
@jfriend00,我更新了问题,抱歉。 - firstlord
1
我曾经遇到过类似的问题:链接,也许这可以帮助你。 - VebDav
@VebDav 我认为不需要,截图已经很清楚了。 - Christian Vincenzo Traina
显示剩余5条评论
1个回答

0
Cristian Traìna和VebDav提供的答案在我的脑海中引起了闪电。我在互联网上找不到确切的解决方案,但是不同的问题指引着我。问题源于我的愚蠢。我忘记在mongoose类别模式中输入mainCategories字段。我添加了这个字段,问题得到了解决。非常感谢大家的回答。

enter image description here

现在它正在返回主要类别 :)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接