Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

76
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda