Reputation: 1296
Loopback uses sequential number for model ID. Can I use my own ID generator on server side? How do I go about doing that?
Upvotes: 9
Views: 4546
Reputation: 411
If you use Loopback 4 then this is the setting for generating UUID in prime key. Inside you Model change this.
@property({
type: 'string',
id: true,
defaultFn: 'uuidv4',
}) id?: string;
This is the way to gen a unique id in your table.
Upvotes: 2
Reputation: 814
It is possible to specify Loopback generators (guid, uuid, ...) as a default function for id properties in your model definition file.
example with guid:
{
"name": "ModelName",
"base": "PersistedModel",
"idInjection": false,
"properties": {
"id": {
"type": "string",
"id": true,
"defaultFn": "guid"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
As far as I know, you can't specify there your own default function yet. See related github issue.
If you want more advanced behavior (e.g. your own generator), you can create models/model-name.js
file and extend a constructor of your model.
Upvotes: 10
Reputation: 2848
Yes, you would need to do a few things:
Set "idInjection": false
in the corresponding model.json to turn off automatic id injection
Add the property you want to your model, then set it to be an id either by setting "id": true
on the property in the model.json, or selecting the id radial next to the prop in the composer
Generate and inject the id, probably with an operation hook on before save
(https://docs.strongloop.com/display/public/LB/Operation+hooks) or maybe a mixin (https://docs.strongloop.com/display/public/LB/Defining+mixins)
Upvotes: 4