How to make Mongoose Schema id generate a 16 digits random number

Viewed 1405

I'm new to mongoose. I'm creating a model (creditnote) that consists of a 16 digits unique reference (serves as primary key) and an integer that represents the number of credits.

I want the reference to be the model's id and to be an auto-generated 16 digits number. How can I achieve this?

Right now I have the following code:

var mongoose = require('mongoose');
// Setup schema
var creditnoteSchema = mongoose.Schema({
reference: {
    type: mongoose.ObjectId,
    required: true,
    default: function(){
        // Generate 16 digits random number
        number = (Math.random()+' ').substring(2,10)+(Math.random()+' ').substring(2,10);

    }
},
amount: {
    type: Number,
    required: true,
    validate: {
        validator: Number.isInteger,
        message: '{VALUE} is not an integer value'
    }
}

});
1 Answers

All objects created in MongoDB have a property _id which serves as a unique ID. You can also use ObjectId to generate a unique key, like this:

const {ObjectId} = require('mongodb'); 
console.log(ObjectId());
Related