简体   繁体   中英

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.

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.

For example, if my returned document was stored in doc , doc.categories will return the full array, [] , of Category Objects I have created. doc.version returns 1.0.0 .

However, when I attempt doc.bypass , I get undefined . If I attempt doc.id I get 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:

 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?

Thanks - W

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM