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

79
Visualizações
Mongoose automatically change the type of the value

In mongoose.model, I have chosen the type of name to be a string and the type of age to be a number, but when I enter a number as the value of name, I don't get an error and the same thing happens when I use something like '18' as the value of age.

Here is the code:

const User = mongoose.model('User', {
  name: { type: String },
  age: { type: Number }
});

const me = new User({
  name: 12,
  age: '18'
});

me.save().then(() => console.log(me)).catch(error => console.log(error));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Mongoose casts the values to the corresponding type, if it fails a CastError is thrown, from the doc:

Before running validators, Mongoose attempts to coerce values to the correct type. This process is called casting the document. If casting fails for a given path, the error.errors object will contain a CastError object.

You can try this by given age the value 'aa' for example.

If you want to override this behavior you can use one of the following options:

  1. Disable casting globally: mongoose.Number.cast(false)
  2. Disable casting just for a given path:
age: {
  type: Number, 
  cast: false // Disable casting just for this path
},
  1. Use a custom function:
age: {
    type: Number,
    cast: v => { return typeof v === 'number' && !isNaN(v) ? Number(v) : v; } // Override casting just for this path
  }
about 4 years ago · Juan Pablo Isaza 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