Loopback: Models with primary keys not called id

Created on 21 Aug 2014  路  4Comments  路  Source: strongloop/loopback

Hi,

Loopback is pretty awesome but I am having a small problem defining a primary key in the model.

A lot of databases have primary keys which are not simply called 'id'.

I can't find any documentation which tells me how to handle this case with a model in loopback.

Basic example of table creation in mysql:

CREATE TABLE contact(
    contact_id INT(10) NOT NULL AUTO_INCREMENT,
    contact_name VARCHAR(50) NOT NULL,
    PRIMARY KEY(`contact_id`)
) ...

In the loopback model definition doing the following produces an additional, unwanted and unnecessary, key called 'id'.

"properties": {
    "contact_id": {
      "type": "number",
      "generated": true,
      "id":true,
      "required":false,
      "doc":"This is the primary ID used to identify a contact"
    },

From the API Explorer:

[
  {
    "contact_id": 0,
    "contact_name": "",
    "id": 0
  }
]

What changes need to be made to the JSON above to make the model comply with the DB design?

Many thanks,

Ian

Most helpful comment

Use the idInjection attribute:

"idInjection": false,
"properties": {
    "contact_id": {
      "type": "number",
      "generated": true,
      "id":true,
      "required":false,
      "doc":"This is the primary ID used to identify a contact"
    },

By the way, if contact_id is a primary key, required should be true, n'est pas?

All 4 comments

Use the idInjection attribute:

"idInjection": false,
"properties": {
    "contact_id": {
      "type": "number",
      "generated": true,
      "id":true,
      "required":false,
      "doc":"This is the primary ID used to identify a contact"
    },

By the way, if contact_id is a primary key, required should be true, n'est pas?

Many thanks.. I don't recall seeing the idInjection attribute mentioned anywhere but I have only been playing with loopback for about 3 days.

On the face of it the model should set a primary key as required. However, following a few minutes of playing around, it should be possible to allow the DB to generate a primary key if none is provided.

So the snippet stays as it is - required should be false for fields with a default set.

Cheers.

http://docs.strongloop.com/display/LB/Model+Definition+JSON+file#ModelDefinitionJSONfile-IDproperties

Loopback is not supposed to create an id column if you have created one. Not sure it works :)

Yeah, maybe there is a bug there then.

I started by setting the id property of my field to true, the intuitive thing to do. However the automagically created id field appeared in API Explorer.

When you told me about the idInjection property the issue was resolved.

Was this page helpful?
0 / 5 - 0 ratings