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

600
Vistas
Mongoose, right way for create random string on a value

I want to create an model for my project and Im new for JS.

I want to generate a randomly string between 6 and 10 digits for my key value.

const objectSchema = mongoose.Schema({
_id : mongoose.Schema.Types.ObjectId,
userId : {type: String, required: true},
randomGeneratedString: ???
});

How can I do this with right way.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You can use default value from Schema to generate a random value.

const objectSchema = mongoose.Schema({
_id : mongoose.Schema.Types.ObjectId,
userId : {type: String, required: true},
randomGeneratedString: {
    type: String,
    default: generateRandom = () => {
      // Here your function to generate random string
      return "yourRandomString"
    }
}
});
over 4 years ago · Santiago Trujillo Denunciar

0

you should use mongoose midleware to implement schema that you want it use code below to define your schema

 const schema = new mongoose.Schema({
  randomGeneratedString: {
    type: String,
    minlength: 6,
    maxlength: 10,
  },
});

schema.pre('save', async function (next) {
  const randomInteger = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  };
  this.randomGeneratedString = Math.random()
    .toString(36)
    .substr(2, randomInteger(6, 10));
  next();
});
over 4 years ago · Santiago Trujillo 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