我有一个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
答案 0 :(得分:1)
从上面的内容来看,它应该可以工作-因此,它更多地是关于如何设置模型的问题-供参考,我已经将其放在可以工作的模型下面,请对照我的示例进行检查,看看您的模型是否在与此相符:
const mongoose = require('mongoose')
const validator = require('validator')
const Task = mongoose.model('Task', {
description: {
type: String,
trim: true,
required: true
},
completed: {
type: Boolean,
default: false
}
})
module.exports = Task
如果这符合您的要求,但仍然存在问题,我可以请您在上面的代码中发布模型吗?
谢谢- W