【发布时间】:2020-10-12 18:57:31
【问题描述】:
我有一个 MongoDB 文档,当以点表示法引用时,它返回某些值作为 undefined 或 null。
这是文档的结构:
{
"id": "1",
"version": "1.0.0",
"categories": [], // Array of Category Objects
"bypass": [] // Array of Strings
}
我使用 Mongoose 如下:Model.findOne({ id: "1" }, { _id: 0 }) 成功返回文档,但是,使用点符号提取特定元素或将它们分配给变量会导致某些元素响应为 null 或 undefined。
例如,如果我返回的文档存储在doc 中,doc.categories 将返回我创建的类别对象的完整数组[]。 doc.version 返回1.0.0。
但是,当我尝试doc.bypass 时,我得到undefined。如果我尝试doc.id,我会得到null。
有人知道发生了什么吗?
代码编辑:
const doc = await Model.findOne({ id: "1" }, { _id: 0 });
console.log(doc); // Contains all document data including bypass with its Array of Strings
console.log(doc.bypass); // undefined
返回:
{
id: '1',
version: '1.0.0',
categories: [
{
name: 'Category 1',
id: '1111',
active: true,
children: [Array]
},
{
name: 'Category 2',
id: '2222',
active: true,
children: [Array]
},
{
name: 'Category 3',
id: '3333',
active: true,
children: [Array]
},
{
name: 'Category 4',
id: '4444',
active: true,
children: [Array]
}
],
bypass: [ '123', '456', '78', '90' ]
}
undefined
【问题讨论】:
-
我不太确定您是如何处理这个问题的,因为没有代码示例说明您如何尝试检索数据 - 例如,如果您在承诺中运行这些数据请求,或者如果它们在异步函数中运行或回调,这可能会影响数据被回调的天气(因为取决于代码运行的时间......数据可能不存在) - 您添加代码的任何机会什么时候运行和什么时候不运行的例子?
-
@Wally 我很抱歉。代码已编辑。
-
能否请您打印console.log(doc)的返回代码 // 另附注-第二个返回有_id:0
-
@Wally 是的。包括上述代码的输出。另外,我添加了
{ _id: 0 }以避免包含分配的MongoDB_id。 -
这能回答你的问题吗? Can't access object property of a Mongoose response 您需要使用
.lean()并确保您尝试访问的字段列在架构中..
标签: javascript node.js mongodb mongoose