Mongoose 文档以点表示法返回“未定义”

我有一个 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 或未定义。


例如,如果我返回的文档存储在 中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


HUX布斯
浏览 118回答 1
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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript