MySql Like Auto Increment Numeric Primary Key For Loopback with MongoDB

Sunil K Samanta
2 min readAug 31, 2018

--

Using MongoDB’s default ObjectId is a good practice but if you want the MySql like Numeric Auto Increment primary key, then try the steps bellow.

Photo by Magda Ehlers from Pexels

You can use this method in a specific Model.js file. But here we’ll create a Mixin for that because we’re gonna include this mixin in any Model so that we can have the auto increment feature in Any Model.

For our reference we’ll use a model named customer which extends the default User Model.

STEP 1:

If your Model’s base Model is PersistedModel (not the default User model) then Skip to Step 2 . Now If your model’s base model is User, then you have to make the public attribute of the default User model false in server/model-config.json as bellow.

"User": {
"dataSource": "mongo",
"public": false // We made it public false
}

STEP 2:

First we’ll create a file named “auto-increment-primary-key.js” in “common/mixins/” (you can create anywhere else you put your mixins) with the bellow content

module.exports = function(Model, options) {
var modelName = Model.definition.name; //Get the Model Name from Model Instance
Model.observe('before save', function (ctx, next) {
if (!ctx.isNewInstance) {
next();
}else{
Model.getDataSource().connector.connect(function (err, db) {
var collection = db.collection('counter');
collection.findAndModify({name: modelName}, [['_id', 'asc']], {$inc: {value: 1}}, { new: true, upsert: true }, function (err, rec) {
if (err) {
console.err(err);
next();
} else {
getPrimaryKeyFromModel(Model, function(primaryKey){
if (ctx.instance) {
ctx.instance[primaryKey] = rec.value.value;
} else {
ctx.data[primaryKey] = rec.value.value;
}
next();
});
}

});
});
}
});
}
//Get the Primary Key from Model
var getPrimaryKeyFromModel = function(Model,cb){
var properties = Model.definition.rawProperties;
Object.keys(properties).forEach(function(key) {
if(properties[key].id === true){
cb(key);
}
});
}

STEP 3:

Now in our customer.json files disable the “idInjection” as

"idInjection": false

STEP 4:

And in the same customer.json file enable our new Mixin “autoIncrementPrimaryKey” as follows

"mixins": {
"autoIncrementPrimaryKey": true
}

STEP 5:

And declare customer_id field as primary key by setting “id” : true as follows

"customer_id": {
"type": "number",
"id": true,
"required": true
},

So our customer.json will finally look like

{
"name": "customer",
"base": "User",
"idInjection": false,
"options": {
"validateUpsert": true
},
"mixins": {
"autoIncrementPrimaryKey": true
},
"properties": {
"customer_id": {
"type": "number",
"id": true,
"required": true
},
"customer_name": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}

Now create a model instance by the POST method and the id should be generated automatically.

Feel free to comment if you have any suggestions or query.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sunil K Samanta
Sunil K Samanta

Written by Sunil K Samanta

Harmoniously blending technology, mindfulness, music, and travel. My journey is fueled by the vision of a more interconnected and compassionate world.

Responses (2)

Write a response