Search code examples
node.jsrestloopbackjs

loopbackjs remote connector not returning ids


I have a nodejs application which is is trying to comunicate with a loopback server

I have the following datasources

{
    "db": {
        "name": "db",
        "connector": "memory"
    },
    "remoteDS": {
        "url": "http://localhost:3033/api",
        "name": "remoteDS",
        "connector": "remote"
    }
}

using loopback-connector-remote

I have common/models/pack.json

{
    "name": "pack",
    "plural": "packs",
    "base": "PersistedModel",
    "idInjection": true,
    "properties": {},
    "validations": [],
    "relations": {},
    "acls": [],
    "methods": {}
}

and my test.js

var app = require('./client/client');
app.models.Pack.create({foo: 'bar'})
    .then(result => {
        console.log(result); // { foo: 'bar', id: NaN }
        return app.models.Pack.find()
    })
    .then(result => {
        console.log(result); // [{ foo: 'bar', id: NaN }]
    })
    .catch(err => {
        console.error(err.message);
    })

I do not know why id: NaN

When I am trying via the api explorer I have the id

[
  {
    "foo": "bar",
    "id": "5bdaf67aed811700149e4549"
  }
]

Solution

  • Try using as your common/models/pack.json

    {
        "name": "pack",
        "plural": "packs",
        "base": "PersistedModel",
        "idInjection": false,
        "properties": {
            "id": {
                "type": "String",
                "id": 1
            }
        },
        "validations": [],
        "relations": {},
        "acls": [],
        "methods": {}
    }
    

    Loopback adds the id property as a number, so it may be trying to parseInt your Id value on create. Perhaps the REST connector is creating it and querying it?

    By default, if no ID properties are defined and the idInjection property is true (or is not set, since true is the default), LoopBack automatically adds an id property to the model as follows:

    id: {type: Number, generated: true, id: true}