Can I use non-sequential id for loopback model?
Asked Answered
J

3

9

Loopback uses sequential number for model ID. Can I use my own ID generator on server side? How do I go about doing that?

Justinjustina answered 14/4, 2016 at 20:37 Comment(0)
C
10

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.

Confiscatory answered 15/4, 2016 at 7:1 Comment(0)
M
4

Yes, you would need to do a few things:

Mohun answered 15/4, 2016 at 0:34 Comment(0)
M
2

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.

Moneymaking answered 17/4, 2020 at 10:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.