Skip to content
Advertisement

how to auto generate id like AB22020001 in nodejs

i want auto generate id like “DC” + yaer + mounth + 4 digit in nodejs.

I am using node js to create an api to connect to the database which I use phpmyadmin I want to create an id like AB22020001 But now all I can do is create an ID like AB2202. I don’t know how to make the number after. My ID consists of 2 letters, last 2 digits of the year and month, and the other 4 digits run from 0001 to 9999. When a new month starts, the last 4 digits start counting at 00001 again.

in my code

let date_ob = new Date();
let year = date_ob.getFullYear();
let yaer_today = year.toString().substring(2)

let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);

const ID = 'AB' + yaer_today + month
console.log(ID)

Advertisement

Answer

Not sure if this is your exact requirement, It will increment the ID series according to your need, and will reset to “0001” once the month changes. but you didn’t tell what happens if counter reaches “9999” in same month.

function generateId() {
    let id = getLastId();
    let finalId = ''

    if (!id) {
        let alpha_series = "AB";

        let year_now = new Date().getFullYear().toString();
        year_now = year_now.slice(-2);

        let month_now = new Date().getMonth() + 1;

        month_now = month_now < 10 ? "0" + month_now : month_now;

        let incrementer = "0001";

        finalId = alpha_series + year_now + month_now + incrementer;

    } else {
        let alpha_series = id.slice(0, 2);

        let year_id = id.slice(2, 4);

        let year_now = new Date().getFullYear().toString();
        year_now = year_now.slice(-2);

        year_id = year_id == year_now ? year_id : year_now;

        let month_id = id.slice(4, 6);

        let month_now = new Date().getMonth() + 1;

        month_now = month_now < 10 ? "0" + month_now : month_now;

        let final_month_id = month_id == month_now ? month_id : month_now;

        let lastIdIncrement = parseInt(id.slice(-4));

        let incrementer = addLeadingZeros((lastIdIncrement + 1).toString());

        incrementer = month_id == month_now ? incrementer : "0001";


        finalId = alpha_series + year_id + final_month_id + incrementer;
    }

    //insert the id in db.
    return finalId;
}

function getLastId() {
    // query to get last inserted id
    let id = null; //replace this with actual id retrieved from DB.
    if (id)
        return id;
    else
        return null;
}

function addLeadingZeros(id) {
    if (id.length < 4) {
        var noneZeroEcode = Number(id).toString();
        var pad = "0000";
        var id = pad.substring(0, pad.length - noneZeroEcode.length) + noneZeroEcode;
        return id;
    } else {
        return id;
    }
}


console.log(generateId());

Advertisement