Search code examples
javascriptnode.jsexpressmongoosemongoose-schema

Accessing schema default values


I have defined and exported a schema with some default values for my DB. How do I access default values of the schema from another module?

const mySchema = new Schema({
    property: {
         type: String,
         enum: ['a', 'b', 'c', ...]
    },
    ...
});

module.exports = mongoose.model('Alpha', mySchema);

As an example, I would like to loop over the enum array values and console.log(array[i]).

let alphabet = mySchema.property.enum
alphabet.forEach(letter => console.log(letter))

Solution

  • It is not possible to access default enum values from the mongoose schema itself. You will need to store the enums in a separate variable and use it in you model. Then export that variable and use it where it's needed.

    export enum PropertyEnums {
      a = "a", // set value of enum a to "a" else it will default to 0
      b = "b",
      c = "c",
      ...
    }
    
    const mySchema = new Schema({
        property: {
             type: String,
             enum: Object.values(PropertyEnums), // equivalent to ["a", "b", "c", ...]
             default: PropertyEnums.a // if you want to set a default value for this field
        },
        ...
    });
    
    module.exports = mongoose.model('Alpha', mySchema);
    

    Then just import the enum where it's needed like so:

    import { PropertyEnums } from "./yourSchemaFile.js"
    
    let alphabet = Object.values(PropertyEnums)
    alphabet.forEach(letter => console.log(letter))