Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
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))
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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))
about 4 years ago · Santiago Trujillo Relatório

0

You can define like below:

export enum Props {
  A = 'A',
  B = 'B'
}

in schema:

property: {
     type: String,
     enum: Props
},

for Access:

for (let item in Props) {
  if (isNaN(Number(item))) {
    console.log(item);
    }
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda