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": {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How we can change the no of digit id which is already in single digit and auto increment