Search code examples
postgresqlloopbackjs

Cannot make work loopback 4 todo-list tutorial with connection to PostgreSQL


I am doing tutorials in the loopback documentation by I have a problem at the last stage of the todo-list tutorial, when I want to connect the app to a database (PostgreSQL, as in the tutorial).

I have initialized the application by doing lb4 example todo-list and then I have followed instructions given at https://loopback.io/doc/en/lb4/todo-list-tutorial-sqldb.html.

I did not forget to do npm run migrate -- --rebuild, tables are well created in the database. Tables are empty.

When I POST /todo-lists (using http://localhost:3000/explorer/#/TodoListController/TodoListController.create) with this body

{ "title": "grocery list" }

I get the answer

{
  "error": {
    "statusCode": 500,
    "message": "Internal Server Error"
  }
}

And I have this log in the console

npm start
...
Server is running at http://[::1]:3000
Request POST /todo-lists failed with status code 500. error: null value in column "id" of relation "todolist" violates not-null constraint
    at Parser.parseErrorMessage (C:\Users\azias\Documents\dev\js\loopback4-example-todo-list\node_modules\pg-protocol\dist\parser.js:278:15)
    at Parser.handlePacket (C:\Users\azias\Documents\dev\js\loopback4-example-todo-list\node_modules\pg-protocol\dist\parser.js:126:29)
    at Parser.parse (C:\Users\azias\Documents\dev\js\loopback4-example-todo-list\node_modules\pg-protocol\dist\parser.js:39:38)
    at Socket.stream.on (C:\Users\azias\Documents\dev\js\loopback4-example-todo-list\node_modules\pg-protocol\dist\index.js:10:42)
    at Socket.emit (events.js:198:13)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at Socket.Readable.push (_stream_readable.js:224:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)

As I understand the mentioned id is not automatically generated (I suppose it should be) and so is missing.

I am discovering loopback so I do not know what I have to change to make it works.


Solution

  • I think I have finally found.

    In all models, the id was defined as property with the setting generated: false, it has to be changed to generated: true. This make sequences to be generated in the database and the id automatically generated.

    For example, in todo-list.model.ts, the code

      @property({
        type: 'number',
        id: true,
        generated: false,
      })
      id?: number;
    

    has to be changed to

      @property({
        type: 'number',
        id: true,
        generated: true,
      })
      id?: number;
    

    (same in todo-list-image.model.ts and todo.model.ts)