Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

598
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!