首页 > 解决方案 > 来自 Mongo 的对象的数组属性未定义

问题描述

我成功地从我的 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,
  },
...

标签: javascriptnode.jsmongodb

解决方案


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

正如在Mongoose 创建空数组中已经讨论过的那样?


推荐阅读