nest: Typeorm fails to work in HMR
Cannot connect to database when using hmr
[ ] Regression
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Current behavior
After creating a new project, I directly use the document example to connect to mongodb.
If I use npm run start, it works.
if I use npm run webpack && npm run start:hmr, it will fail, as shown below

// ormconfig.json
{
"type": "mongodb",
"host": "localhost",
"database": "polaris",
"entities": [
"src/**/**.entity.ts"
],
"synchronize": true
}
Environment
Nest version: 5.0.0
For Tooling issues:
- Node version: 8.11.1
- Platform: Windows 10
Others:
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 15 (2 by maintainers)
Links to this issue
Commits related to this issue
- fix(*): webpack与 typeorm 的问题 https://github.com/nestjs/nest/issues/755#issuecomment-394073763 — committed to skywalker512/cqupt-user by deleted user 5 years ago
Yes, glob pattern will not work. You must provide class references to
entitiesfield instead.But fortunately webpack has feature require.context which allow to collect needed files.
Putting my two cents here for people with the same problem.
The reason this is happening is because
entities: [__dirname + '/**/*.ts'](or .js in my case) would cause typeorm to require those files (while the real entities is already loaded in the webpack bundle).getRepository(for example,getRepository(User), where thisUseris loaded from the webpack bundle), with the ones loaded in theentitiesconfig, which is loaded from js/ts files.My workaround is based on the fact that all the modules are loaded, hence all the entities should be loaded already, via imports. This is especially true in NestJS, with the well-structured project. Specifically, for each module, either the module itself or the controller will import the entity somewhere.
By leveraging the internal mechanism of
@Entitydecorator, we’ll be able to get a list of entity classes.Not sure how true this is, but seems to work well with both dev and prod settings.
It is not problem of nest. It is about webpack, if you want to use glob pattern, use
ts-node-dev