Skip to content

Instantly share code, notes, and snippets.

@ebarahona
Forked from drmikecrowe/Account.js
Created July 30, 2018 17:27
Show Gist options
  • Save ebarahona/1a1135f7cd30622ff87cebf1ad6dad66 to your computer and use it in GitHub Desktop.
Save ebarahona/1a1135f7cd30622ff87cebf1ad6dad66 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": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment