[英]Mongoose document returns “undefined” in dot notation
I have a MongoDB document that returns certain values as undefined
or null
when referred to in dot notation.我有一个 MongoDB 文档,当以点表示法引用时,该文档将某些值返回为undefined
或null
。
Here is the structure of the document:这是文档的结构:
{
"id": "1",
"version": "1.0.0",
"categories": [], // Array of Category Objects
"bypass": [] // Array of Strings
}
I'm using Mongoose as follows: Model.findOne({ id: "1" }, { _id: 0 })
which returns the document with success, however, using dot notation to extract specific elements or assign them to variables causes certain ones to respond as null or undefined.我正在使用 Mongoose 如下: Model.findOne({ id: "1" }, { _id: 0 })
成功返回文档,但是,使用点符号提取特定元素或将它们分配给变量会导致某些元素响应为 null 或未定义。
For example, if my returned document was stored in doc
, doc.categories
will return the full array, []
, of Category Objects I have created.例如,如果我返回的文档存储在doc
中, doc.categories
将返回我创建的类别对象的完整数组[]
。 doc.version
returns 1.0.0
. doc.version
返回1.0.0
。
However, when I attempt doc.bypass
, I get undefined
.但是,当我尝试doc.bypass
时,我得到undefined
。 If I attempt doc.id
I get null
.如果我尝试doc.id
我得到null
。
Anyone know what is happening?有谁知道发生了什么?
CODE EDIT:代码编辑:
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
RETURN:返回:
{
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
Looking at the above then it should be working - so its more a question of how you have set up your model - for reference I've put below a working model, please check it against my example to see if yours is in line with that:看看上面的内容,它应该可以工作 - 所以它更多的是关于你如何设置你的 model 的问题 - 作为参考,我已经把工作的 model 放在下面,请对照我的例子检查它,看看你的是否符合:
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
If it is in line with this and you're still having the issue could I ask you to post your model in your code above?如果它符合这个并且您仍然遇到问题,我可以要求您在上面的代码中发布您的 model 吗?
Thanks - W谢谢-W
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.