Skip to content

Instantly share code, notes, and snippets.

@drmikecrowe
Last active June 17, 2021 16:38
Show Gist options
  • Save drmikecrowe/5a5568930bad567d4148aad75c94de5a to your computer and use it in GitHub Desktop.
Save drmikecrowe/5a5568930bad567d4148aad75c94de5a to your computer and use it in GitHub Desktop.
Auto-incrementing ID's in Loopback
module.exports = function (Account) {
Account.observe('before save', function addAccountId(ctx, next) {
if (!ctx.isNewInstance) {
debug('id is already set, returning', ctx.data);
return next();
}
app.dataSources.db.connector.collection("Sequences").findAndModify({name: 'Account'}, [['_id', 'asc']], {$inc: {value: 1}}, {new: true}, function (err, rec) {
if (err) {
console.err(err);
} else {
if (ctx.instance) {
ctx.instance.id = rec.value.value;
} else {
ctx.data.id = rec.value.value;
}
}
next();
});
});
}
{
"name": "Account",
"base": "PersistedModel",
"idInjection": false,
"properties": {
"id": {
"type": "Number",
"id": true,
"default": 0
},
...
}
}
{
"name": "Sequences",
"base": "PersistedModel",
"public": false,
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string"
},
"value": {
"type": "number",
"default": 100000
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
@Jyoti-meme
Copy link

Is this code applicable when connecting with a hyperledger network?

@oguzhankarahan
Copy link

oguzhankarahan commented Jan 27, 2020

You can do something like in this example for loopback 4

let last_record = await this.testRepository.findOne({order: ['id DESC']});
if(last_record) invoice.id = last_record.id+1;

This will generate your model with the property:

@property({
    type: 'number',
    required: false,
    default: 1,
    generated: false
  })
  id: number;

Hopefully, this helps, please write me if there is any other code. Thanks

@VishalSingh28
Copy link

How we can change the no of digit id which is already in single digit and auto increment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment