Search code examples
mysqlnode.jsloopbackjs

Why my datasource is not chanching from 'memory db' to MySQL in LoopBack 4?


I'm trying to learn LoopBack 4, so I make the tutorials examples they give in official docs. I want to change the datasource of the todoList example from 'In-memory db' for 'MySQL', but I have been not success, even if I think this is so trivial.

Here is some of code I have.

todo.repository.ts

export class TodoRepository extends DefaultCrudRepository<
  Todo,
  typeof Todo.prototype.id
  > {
  constructor(
    @inject('datasources.db') dataSource: MysqldbDataSource,
  ) {
    super(Todo, dataSource);
  }
}

todo-list.repository.ts

export class TodoListRepository extends DefaultCrudRepository<
  TodoList,
  typeof TodoList.prototype.id
  > {

  public readonly todos: HasManyRepositoryFactory<
    Todo,
    typeof TodoList.prototype.id
  >;
  constructor(
    @inject('datasources.db') dataSource: MysqldbDataSource,
    @repository.getter(TodoRepository)
    protected todoRepositoryGetter: Getter<TodoRepository>,
  ) {
    super(TodoList, dataSource);
    this.todos = this.createHasManyRepositoryFactoryFor(
      'todos',
      todoRepositoryGetter,
    );
  }
}

As far as I understand, here the repository code is in charge for connecting the controller with the actual data, then I replace the code and changed where it says DbDataSource to MysqldbDataSource as I show you in the code above.

Anyways, I keep having the data in data/db.json (where 'in-memory db' places the data) instead of retrieving data from the actual MySQL database. Any help ins appreciated.

EDIT:

Here is my config for the connection with the MySQL database

todo-list.repository.ts

{
  "name": "mysqldb",
  "connector": "mysql",
  "url": "mysql://root:123456@localhost/todo",
  "host": "localhost",
  "port": 3306,
  "user": "root",
  "password": "123456",
  "database": "todo"
}

Solution

  • Well, it was very simple as I supposed from the beginning. I just had to change the @inject name in both todo.repository.ts and todo-list.repository.ts, like this:

    @inject('datasources.mysqldb') dataSource: MysqldbDataSource
    

    I would swear I did that yesterday night before going to sleep, but did not work. Today I just create brand new repositories from the LB CLI and indeed it worked. Maybe I was just too sleepy yesterday...