MySql Like Auto Increment Numeric Primary Key For Loopback with MongoDB

Sunil K Samanta
Aug 31, 2018 · 2 min read

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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade