-
-
Save ebarahona/1a1135f7cd30622ff87cebf1ad6dad66 to your computer and use it in GitHub Desktop.
Auto-incrementing ID's in Loopback
This file contains hidden or 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 hidden or 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 hidden or 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": {} | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment