Unique and Auto Generated ID that will End with Post-fix/start with Prefix in NodeJS

In this blog, we will discuss Unique and Auto-Generated ID that will End with Post-fix/start with Prefix in NodeJS. Please read the blog to understand it.So, let's start.

For auto-generated unique id, first, I try to understand what the logic is. So, in my store's table, there are the same fields like “store_id”, “name”, ”description”, ”address”, where I want to auto-generated the store_id. So I take the name field where I select the first 3 latter of the given names and that value is to keep in a variable with the update id. In that way, I have a unique and auto-generated store_id.

Below is the code for Controller page:


var str = fields.name ? fields.name[0] : '';
var storesName= str.replace(" ", "").substr(0, 3).toUpperCase();       
var storesID = storesName;

Here ‘storesName’ keeps the value of the name field with replacing of space (if there have any space) and select first 3 latter and converted it uppercase. Like, if the name is “BlueHorse” then the output is “BLU”


models.stores.create({
                name: fields.name[0]?fields.name[0]:null,
//store_id://if the store_id is auto generated then  add store_id   is not required on stores create.
                description: fields.description[0]?fields.description[0]:null,
                address: fields.address[0]?fields.address[0]:null,
                }).then(function(stores) {
                    var newStores_id= storesID +stores.id;

// here I add the update id with storesID and keep the value in newStores_id//

models.stores.update({
                     store_id: newStores_id ? newStores_id : null,                         
                    },{where:{id:stores.id}}).then(function(stores_update)

Conclusion:

This is very important part in NodeJS framework. The above code is developed and tested by me. Please share your review in the comment section. See you on my next blog.

Comments

We Serve clients globally in diverse industries

Stay Upto Date With Our Newsletter.