Last active
June 17, 2021 16:38
-
-
Save drmikecrowe/5a5568930bad567d4148aad75c94de5a to your computer and use it in GitHub Desktop.
Auto-incrementing ID's in Loopback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "Account", | |
"base": "PersistedModel", | |
"idInjection": false, | |
"properties": { | |
"id": { | |
"type": "Number", | |
"id": true, | |
"default": 0 | |
}, | |
... | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "Sequences", | |
"base": "PersistedModel", | |
"public": false, | |
"idInjection": true, | |
"options": { | |
"validateUpsert": true | |
}, | |
"properties": { | |
"name": { | |
"type": "string" | |
}, | |
"value": { | |
"type": "number", | |
"default": 100000 | |
} | |
}, | |
"validations": [], | |
"relations": {}, | |
"acls": [], | |
"methods": {} | |
} |
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
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
Is this code applicable when connecting with a hyperledger network?