【问题标题】:Object's array property from Mongo is undefined来自 Mongodb 的对象数组属性未定义
【发布时间】:2021-01-01 22:50:47
【问题描述】:

我成功地从我的 Mongo DB 中获取了一个文档,但是该文档中的所有内容都显示为未定义。这是一个例子:

...
  const user = await UserModel.findById(user_id).exec(); //Getting user normally

  console.log(user); // Shows the object normally with the "push_subscriptions" property
  console.log(user.push_subscriptions); // Shows undefined
  console.log(user.email); //Shows the email normally
...

控制台截图如下:

这是用户架构的“push_subscriptions”部分:

...
  push_subscriptions: {
    type: Array,
  },
...

【问题讨论】:

  • push_subscriptions 可以是 gets added later,在 console.log(user) 之后吗?
  • @T.J.Crowder 不,它在我的数据库中
  • 很费解....
  • 非常不寻常,你能给我们看看Shema吗?
  • @JohnRC 是的,我同意:D。也许它与异步操作或其他什么有关?

标签: javascript node.js mongodb


【解决方案1】:

登录 user.toJSON() 并查看是否存在任何 push_subscription 密钥。 尝试user.toJSON().push_subscriptions,因为用户是猫鼬文档,您可以尝试toJSONtoObject

正如Mongoose creating empty arrays?中已经讨论过的那样

【讨论】:

    【解决方案2】:

    您可以使用 .lean() 方法将用户转换为普通对象:

    const user = await UserModel.findById(user_id).exec().lean();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 2020-11-01
      • 2020-10-27
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多