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.
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"
}
}
});
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();
});