Home > Software engineering >  Mongoose Schema Getter
Mongoose Schema Getter

Time:11-16

I'm new to Mongoose and MongoDB, and I'd like to understand the following code a little more:

const userSchema: Schema = new Schema(
    {
        password: {
            type: String,
            required: true,
            get: (): undefined => undefined
        }
    },
    {
        toJSON: {
            getters: true
        }
    }
);

What does the line get: (): undefined => undefined mean? And what is the purpose of adding toJSON: { getters: true }? I'm assuming they are to enable getters, but I'd like to know more in detail.

CodePudding user response:

Lets assume you have a user schema.

import { model, Schema } from 'mongoose'

const userSchema = new Schema(
  {
    name: {
      type: String,
      required: true,
      get: toUpper
    }
  },
  { toJSON: { getters: true } } // if this is false, toUpper getter will not execute
)

function toUpper(name: string) {
  return name.toUpperCase()
}

const User = model('user', userSchema)

export default User

Let's assume you want to change the name property to uppercase every time, so you will define the toUpper getter function and set this to get.

Now if you have not enabled { toJSON: { getters: true } }, the toUpper getter function will never execute, and the name property will never be transformed to uppercase.

Now comes your question, if you've set get: (): undefined => undefined and { toJSON: { getters: true } } means it will execute the getter function and return undefined instead of a password, hence password key will be removed from the result.

I hope this helps you to understand the getters.

References Getters Setters, toJSON options

  • Related