Search code examples
mongodbmodelmongoose-schemamongoose-modelsmongodb-schema

MongoDB/mongoose schema-model behaviours return undefined


In my mongodb/mongoose schema model, I set a user roles document entry like:

const mongoose = require('mongoose')
const {Schema} = mongoose

const userSchema = new Schema({
  username: {type: String, required: true},
  password: {type: String, required: true},
  roles: {
    User: {type: Number, default: 1234},
    Editor: Number, 
    Admin: Number,
  },
  refreshToken: [String],
})
//
module.exports = mongoose.model('User', userSchema)

No role is required and by default, all new registered user start with User role (code 1234).

When I access a user in db with mongoose :

const handleLogin = async (req, res) => {
...
    const foundUser = await User.findOne({username: user}).exec()
    console.log(foundUser.roles)
    console.log(Object.values(foundUser.roles))
...
}

Console.log sent me these outputs:

{ User: 2023 }
[ 2023, undefined, undefined ]

First one is ok for me and reflect the document state as I created it and as it appears in my db, with just user, but the second one is more obscure and make unused model entries reappears as undefined.

It's not really disturbing at this point for my api and verifyRole middleware and routes, everything works, but I like to understand and control and at the moment this is not 100% the case.

How can I avoid this undefined to appear?

Thanks


Solution

  • The reason you're getting undefined values in the second console.log is because Object.values() returns an array of all enumerable property values of the object, including the ones that are not explicitly set (i.e., Editor and Admin in your case).

    See MDN documentation.

    If you want to see only set values, log Object.values(foundUser.roles).filter(r => r !== undefined).

    This will return an array of values that are not undefined, e.g., [2023].

    See it for yourself:

    var user = {a:1,b:undefined,c:undefined};
    console.log(Object.values(user));
    console.log(Object.values(user).filter(r => r !== undefined));