enigmare/v2-crawler
1904
1{"id":"stack-46879840","source":"stackoverflow","questionId":46879840,"title":"How can I have IS NULL condition in TypeORM find options?","tags":["sql","where-clause","typeorm","typeorm-activerecord"],"text":"Title: How can I have IS NULL condition in TypeORM find options?\nTags: sql, where-clause, typeorm, typeorm-activerecord\nSource: Stack Overflow\n\nQuestion:\nIn my queries I'm using TypeORM `find` option.\nHow can I have `IS NULL` condition in the `where` clause?\n\n========================================\n\nTop Answer:\nIf someone is looking for NOT NULL, it would be like this:\n\n```\nimport { IsNull, Not } from \"typeorm\";\n\nreturn await getRepository(User).findOne({\n where: { \n username: Not(IsNull())\n }\n});\n```\n\n========================================\n\nCode:\n```text\nfind\n```\n\n```text\nIS NULL\n```\n\n```text\nwhere\n```\n\n```js\nimport { IsNull } from \"typeorm\";\nreturn await getRepository(User).findOne({\n where: { \n username: IsNull()\n }\n});\n```\n\n```text\nIsNull()\n```\n\n```text\nconst users = await userRepository.createQueryBuilder(\"user\")\n .where(\"user.name IS NULL\")\n .getMany();\n```\n\n```text\nexport declare type FindOperatorType = \"not\" | \n\"lessThan\" | \n\"lessThanOrEqual\" | \n\"moreThan\" | \n\"moreThanOrEqual\" | \n\"equal\" | \n\"between\" | \n\"in\" | \n\"any\" | \n\"isNull\" | \n\"like\" | \n\"raw\";\n```\n\n```text\n{ \n where: { \n propertyToCheck: <Operator>\n }\n}\n```\n\n```text\nimport { Repository, Between, IsNull, LessThan } from 'typeorm';\n\n{ \n where: { \n age: LessThan(50)\n }\n}\n```\n\n```text\nasync articleRequests(\n accepted?: ArticleRequestAcceptance,\n): Promise<ArticleRequest[]> {\n const where: FindConditions<ArticleRequest>[] | FindConditions<ArticleRequest> = {};\n\n if (accepted !== undefined) {\n switch (accepted) {\n case ArticleRequestAcceptance.Accepted:\n where.accepted = true;\n break;\n case ArticleRequestAcceptance.Rejected:\n where.accepted = false;\n break;\n case ArticleRequestAcceptance.NotReviewedYet:\n where.accepted = undefined;\n break;\n }\n }\n\n return await ArticleRequest.find({ where }).catch(reason => {\n throw reason.message;\n });\n}\n```\n\n```sql\nSELECT '...' WHERE \"ArticleRequest\".\"accepted\" = NULL\n```\n\n```text\nif (accepted !== undefined) {\n switch (accepted) {\n case ArticleRequestAcceptance.Accepted:\n where.accepted = true;\n break;\n case ArticleRequestAcceptance.Rejected:\n where.accepted = false;\n break;\n case ArticleRequestAcceptance.NotReviewedYet:\n where.accepted = IsNull();\n break;\n }\n }\n```\n\n```text\nQueryBuilder\n```\n\n```text\nFindConditions\n```\n\n```text\n... WHERE \"ArticleRequest\".\"accepted\" = @0 -- PARAMETERS: [null]\n```\n\n```text\nundefined\n```\n\n```text\naccepted\n```\n\n```text\nnull\n```\n\n```text\nnull\n```\n\n```text\nnull\n```\n\n```text\n=\n```\n\n```text\n<>\n```\n\n```text\nIsNull()\n```\n\n```text\nFindOperator\n```\n\n```text\nIS NULL\n```\n\n```text\n= NULL\n```\n\n```js\nimport { IsNull, Not } from \"typeorm\";\n\nreturn await getRepository(User).findOne({\n where: { \n username: Not(IsNull())\n }\n});\n```\n\n```text\nTheModel.find({ theField: null })\n```\n\n========================================\n\nComments:\n- That is the manual way of doing it, but if you see this typeorm code it can do it for you - I'm just not sure how.\n- Maybe it helps somebody if you need not null values use: `.where(\"user.name IS NOT NULL\")`\n- .where(\"user.name IS NOT NULL\") is not working for me\n- If you want the opposite (when looking for a non-null column). Wrap that method. `Not(IsNull())`\n- Not necessarily, this can potentially cause a type error. You can also use `field: IsNull()`.\n- absolutely not, this is not going to work, it will be ignored","metadata":{"transformedAt":"2026-08-18T18:33:44.680Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":215,"estimatedTokens":872}}2{"id":"stack-46745688","source":"stackoverflow","questionId":46745688,"title":"TypeORM upsert - create if not exist","tags":["typescript","typeorm"],"text":"Title: TypeORM upsert - create if not exist\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nDoes TypeORM include some functionnality to avoid this : \n\n```\nlet contraption = await thingRepository.findOne({ name : \"Contraption\" });\n\nif(!contraption) // Create if not exist\n{\n let newThing = new Thing();\n newThing.name = \"Contraption\"\n await thingRepository.save(newThing);\n contraption = newThing;\n}\n```\n\nSomething like : \n\n```\nlet contraption = await thingRepository.upsert({ name : \"Contraption\" });\n```\n\n========================================\n\nTop Answer:\nFor anyone finding this in 2021, Typeorm's `Repository.save()` method will update or insert if it finds a match with a primary key. This works in sqlite too.\n\nFrom the documentation:\n\n```\n/**\n * Saves all given entities in the database.\n * If entities do not exist in the database then inserts, otherwise updates.\n */\n```\n\n========================================\n\nCode:\n```text\nlet contraption = await thingRepository.findOne({ name : \"Contraption\" });\n\nif(!contraption) // Create if not exist\n{\n let newThing = new Thing();\n newThing.name = \"Contraption\"\n await thingRepository.save(newThing);\n contraption = newThing;\n}\n```\n\n```text\nlet contraption = await thingRepository.upsert({ name : \"Contraption\" });\n```\n\n```text\nawait connection.createQueryBuilder()\n .insert()\n .into(Post)\n .values(post2)\n .onConflict(`(\"id\") DO NOTHING`)\n .execute();\n\nawait connection.createQueryBuilder()\n .insert()\n .into(Post)\n .values(post2)\n .onConflict(`(\"id\") DO UPDATE SET \"title\" = :title`)\n .setParameter(\"title\", post2.title)\n .execute();\n```\n\n```text\nlet contraption = await thingRepository.save({id: 1, name : \"New Contraption Name !\"});\n```\n\n```text\nRepository<T>.save()\n```\n\n```text\n@OneToMany(type => Post, post => post.user, {\n cascade: true\n })\n posts: Post[];\n\n\nexport const saveAllPosts = async (req: Request, res: Response) => {\n const userRepository = getManager().getRepository(User);\n const postRepository = getManager().getRepository(Post);\n let i;\n let newUsers:any = [];\n let newUser:any = {};\n let newPost:any = {};\n for(i=1; i<=6; i ++) {\n newUser = await userRepository.findOne({ \n where: { id: i} \n });\n if(typeof newUser == \"undefined\") {\n newUser = new User();\n console.log(\"insert\");\n } else {\n console.log(\"update\");\n } \n newUser.name = \"naval pankaj test\"+i; \n\n newPost = await postRepository.findOne({ \n where: { userId: i} \n });\n if(typeof newPost == \"undefined\") {\n newPost = new Post();\n console.log(\"post insert\");\n } else {\n console.log(\"post update\");\n }\n newPost.title = \"naval pankaj add post title \"+i;\n newUser.posts = [newPost];\n newUsers.push(newUser); \n }\n await userRepository.save(newUsers); \n res.send(\"complete\");\n};\n```\n\n```text\nconst posts = [{ id: 1, title: \"First Post\" }, { id: 2, title: \"Second Post\" }];\n\nawait connection.createQueryBuilder()\n .insert()\n .into(Post)\n .values(posts)\n .onConflict(`(\"id\") DO UPDATE SET \"title\" = excluded.\"title\"`)\n .execute();\n```\n\n```text\nawait connection.createQueryBuilder()\n .insert()\n .into(Post)\n .values(post)\n .orIgnore()\n .execute();\n```\n\n```text\nawait getConnection()\n .createQueryBuilder()\n .insert()\n .into(GroupEntity)\n .values(updatedGroups)\n .orUpdate({ conflict_target: ['id'], overwrite: ['name', 'parentId', 'web', 'avatar', 'description'] })\n .execute();\n```\n\n```text\nONCONFLICT\n```\n\n```text\n/**\n * Saves all given entities in the database.\n * If entities do not exist in the database then inserts, otherwise updates.\n */\n```\n\n```text\nRepository.save()\n```\n\n```text\nawait this.yourRepository.upsert({name: 'John'}, ['id']) // assuming id is unique\n```\n\n```text\n@Entity()\n@Unique('constraint_name', ['col_one', 'col_two'])\n```\n\n```text\nawait this.yourRepository.upsert({name: 'John'}, ['constraint_name'])\n```\n\n```text\nupsert\n```\n\n```text\nUnique\n```\n\n```text\nupsert\n```\n\n```text\n@Entity()\n@Unique('constraint_name', ['id'])\n```\n\n```text\nawait this.yourRepository.upsert(\n {\n id: uuid,\n key1: value1,\n ...\n },\n {\n skipUpdateIfNoValuesChanged: true, // If true, postgres will skip the update if no values would be changed (reduces writes)\n conflictPaths: ['id'], // column(s) name that you would like to ON CONFLICT\n },\n);\n```\n\n```js\n@Entity(\"thing\")\n@Unique([\"name\", \"color\"])\nexport class Thing {\n @PrimaryGeneratedColumn()\n id: string;\n\n @Column()\n name: string;\n\n @Column()\n color: string;\n\n // list goes on\n}\n```\n\n```js\nawait repository.upsert(\n [\n { name: \"a red thing\", color: \"red\" },\n { name: \"a blue thing\", color: \"blue\" },\n ],\n {\n conflictPaths: [\"name\", \"color\"],\n skipUpdateIfNoValuesChanged: true,\n upsertType: \"on-conflict-do-update\",\n }\n);\n```\n\n```text\nconst repository = dataSource.getRepository(Thing);\n\nawait repository\n .createQueryBuilder()\n .insert()\n .into(Thing)\n .values([\n { name: \"a red thing\", color: \"red\" },\n { name: \"a blue thing\", color: \"blue\" },\n ])\n .orUpdate([\"name\", \"color\"])\n .orIgnore()\n .execute();\n```\n\n```text\nid\n```\n\n```text\nupsert\n```\n\n```text\nasync upsertRecord(createDtoGeneric, read: boolean = true) {\n const pk = createDtoGeneric.getPK()\n // enable below if pk is not auto-generated column\n // if (!createDtoGeneric[createDtoGeneric.getPK()])\n // createDtoGeneric.initPK()\n const upsertResponse = await this._repo.upsert(createDtoGeneric, { conflictPaths: createDtoGeneric.getConflictPaths(), skipUpdateIfNoValuesChanged: true, upsertType: 'on-conflict-do-update' })\n if (read) {\n delete createDtoGeneric[pk]\n return await this.findOneByQuery(createDtoGeneric)\n }\n else\n return upsertResponse;\n}\n```\n\n========================================\n\nComments:\n- a library does this - github.com/danielmhanover/typeorm-upsert\n- it's pretty easy to create a custom repository that extends the standard one as outlined by the docs here, typeorm.io/#/custom-repository\n- Thanks @danielmhanover for sharing. That repo has a fork that is more popular, that supports bulk upsert - github.com/lupu60/nestjs-toolbox\n- This solution is not an actual `upsert`, it's just an `update`. Upsert is this: github.com/typeorm/typeorm/issues/1090\n- Yes you're right ! I'm updating the solution to point out to this feature request and the current partial solution.\n- @BeyondTheSea Are those two completely distinct examples, or do you need to run both when using typeorm? To me, the first call looks like it's an insert that skips conflicting rows, and the second one is an actual upsert -- but isn't the second one sufficient on its own without the first call?\n- How can I specify a auto generated uuid field so that `.save` would work and not insert if the object is alredy there?\n- How to use `onConflict` when `values` is passed an array of records instead of a single record?\n- @LandonKuhn you got any solution for array of records?\n- @TomerAmir @BeyondTheSea apologies for my lack of understanding, but how is `.save()` different from an upsert?\n- It seems that `onConflict` does not work with MySQL, but `orUpdate` does: github.com/typeorm/typeorm/issues/1090#issuecomment-63439148‌​7\n- `onConflict` method is marked as deprecated, check out answer from Moshe Simantov stackoverflow.com/a/63678950/3984428\n- It's not only on MySQL, Postgres works as well.\n- This should be the accepted answer, since `onConflict` is marked as deprecated\n- This answer must be accepted as the correct one. It's the best!\n- @CassioSeffrin not really. The question doesn't state that it is about MySQL. It could be about PostgreSQL as well. The best answer is the one with the use of `upsert` method.\n- Is it possible to do a non-primary key? Like I have \"email\" thats unique. Can I do `.save({ email: 'foo', age: 29 })` so it should update the row that is with `email: foo`?\n- I second Noitidart's comment/question: is there any way we can do this with some unique field, not necessarily the primary key?\n- Could you, please, link this section of the docs?\n- Documentation link for anyone interested: typeorm.io/#/repository-api You'll need to scroll to the \"save\" entry\n- @Noitidart Did you happen to find a solution to what you describe?\n- To everyone who wants to do this with a non-primary key, here's how to do it: kindacode.com/snippet/…\n- @aviggiano Thanks for the reply, but im looking for a solution without query-builder. It seems to me a bit too low level for a propper solution provided by an ORM\n- thread to : github.com/typeorm/typeorm/issues/9445\n- @aviggiano has the best answer actually, all 3 ways combined.\n- If you are reading this in 2024, just switch to prisma, you'll have much less headaches.\n- This works for me But, I have to set the `conflictPaths` with details instead of just the `constraint_name` it is like `await this.yourRepository.upsert({name: 'John'}, ['col_one', 'col_two'])`\n- If performance is important to you, you should indeed use `upsert`. The TypeORM docs state: `Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient INSERT ... ON CONFLICT DO UPDATE/ON DUPLICATE KEY UPDATE query`\n- the name of the constraint gives \"unknown property\", passing property-names or column names gives \"driverError: error: there is no unique or exclusion constraint matching the\"\n- what is the response of `myRepositoy.upsert(data, ['..'])`?\n- The specific case of upserting on the `id` did not work for me, at least with TypeORM 0.2.41 (it works when the conflicting column is something else). I had to use the `save` method as suggested in this answer.\n- Ohh man you made my day! this works. just an addOn, there is some more useful option. `await manager.upsert(entity , data (object or array ), [\"conflictPaths\", \"columns\"] } );`\n- or instead of array of conflict paths, you can do ` UpsertOptions { conflictPaths: string[] | { [P in keyof Entity]?: true; }; /** * If true, postgres will skip the update if no values would be changed (reduces writes) */ skipUpdateIfNoValuesChanged?: boolean; /** * Define the type of upsert to use (currently, CockroachDB only). * * If none provided, it will use the default for the database (first one in the list) */ upsertType?: \"on-conflict-do-update\" | \"on-duplicate-key-update\" | \"primary-key\";`\n- stackoverflow.com/questions/78019622/…\n- QueryFailedError: ON CONFLICT DO UPDATE command cannot affect row a second time","metadata":{"transformedAt":"2026-08-18T18:33:44.681Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":325,"estimatedTokens":2704}}3{"id":"stack-53407236","source":"stackoverflow","questionId":53407236,"title":"TypeORM \"OR\" operator","tags":["sql","typescript","operators","typeorm"],"text":"Title: TypeORM \"OR\" operator\nTags: sql, typescript, operators, typeorm\nSource: Stack Overflow\n\nQuestion:\nI could not find any notion of OR operator neither in TypeORM docs nor in the source code. does it support it at all?\n\nI'm trying to do perform a basic search with a repository.\n\n```\ndb.getRepository(MyModel).find({\n name : \"john\",\n lastName: \"doe\"\n})\n```\n\nI know this generates an AND operation but\nI need an OR operation so SQL would look like:\n\n```\nname='john' OR lastName='doe'\n```\n\nAm I forced to use the query builder for something basic like this?\n\n========================================\n\nTop Answer:\n```\ndb.getRepository(MyModel).find({\n where: [\n { name: \"john\" },\n { lastName: \"doe\" }\n ]\n})\n```\n\nPass an array to `where`\n\n========================================\n\nCode:\n```js\ndb.getRepository(MyModel).find({\n name : \"john\",\n lastName: \"doe\"\n})\n```\n\n```text\nname='john' OR lastName='doe'\n```\n\n```text\nconst users = await db.getRepository(User).findBy({\n name: Or(Equal(\"John\"), ILike(\"Jane%\")),\n})\n```\n\n```sql\n-- Will generate the following query:\nSELECT * FROM \"user\" WHERE \"name\" = 'John' OR \"name\" ILIKE 'Jane%'\n```\n\n```text\nOr\n```\n\n```text\nreturn await getRepository(MyModel)\n .createQueryBuilder()\n .where(\"name = :name OR lastName = :lastName\", {\n name: \"john\",\n lastName: \"doe\"\n })\n .getMany();\n```\n\n```text\ndb.getRepository(MyModel).find({\n where: [\n { name: \"john\" },\n { lastName: \"doe\" }\n ]\n})\n```\n\n```text\nwhere\n```\n\n```text\nuserRepository.find({\n where: [\n {\n firstName: 'Timber',\n lastName: 'Saw',\n project: {\n name: 'TypeORM',\n },\n },\n {\n firstName: 'Timber',\n lastName: 'Saw',\n project: {\n initials: 'TORM',\n },\n },\n ],\n});\n```\n\n```text\nOR\n```\n\n```text\nsub-clause\n```\n\n```text\nmain-clause\n```\n\n```text\nTimber Saw\n```\n\n```text\nname = \"TypeORM\"\n```\n\n```text\ninitials = \"TORM\"\n```\n\n```text\ndb.getRepository(MyModel).find({\n where: [\n { name: \"john\", lastName: \"doe\" },\n { age: 20 }\n ]\n})\n```\n\n```text\nselect * from model where (name = \"john\" and lastname = \"doe\") OR age = 20\n```\n\n```text\nconst results = await db.getRepository(MyModel)\n .createQueryBuilder('model')\n .where('model.name = :name', { name: 'john' })\n .orWhere('model.lastName = :lastName', { lastName: 'doe' })\n .getMany();\n```\n\n========================================\n\nComments:\n- Well, the other answer without QueryBuilder works well, but in case you'd like to use QueryBuilder anyway then you can also use orWhere to create your `OR` expression.\n- sorry this dosnt work. you get this error: 'filter' field must be of BSON type object\n- Ok i figured it out. this will only work with SQL databases and not Mongo.\n- Works for Postgres. The question is, now, how to combine this \"OR\" sub-clause with additional \"AND\" sub-clauses. Any ideas?\n- Add more properties to the object\n- Hm, how would one express parentheses?\n- This executes AND not OR\n- @AlexFortuna That's what I'm wondering as well, or alternatively wanting the top level clause to be an AND clause with an OR sub-clause. `WHERE (column_a = \"foobar\" AND (column_b = \"foo\" OR column_c = \"bar\"))`\n- Thanks for pointing that out! This saved me some keystrokes and is much better in terms of readability!","metadata":{"transformedAt":"2026-08-18T18:33:44.681Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":169,"estimatedTokens":817}}4{"id":"stack-47814537","source":"stackoverflow","questionId":47814537,"title":"How to perform a like query TypeORM","tags":["javascript","typescript","typeorm"],"text":"Title: How to perform a like query TypeORM\nTags: javascript, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nHello guys I'm trying to find all the results that have a in them. I have tried a couple of ways but the problem is nothing works. It just returns an empty array\n\n```\nvar data = await getRepository(User)\n .createQueryBuilder(\"user\")\n .where(\"user.firstName = %:name%\", { name: firstName })\n .getMany();\n```\n\nand something like this\n\n```\nvar data = await getRepository(User)\n .createQueryBuilder(\"user\")\n .where(\"user.firstName like %:name%\", { name: firstName })\n .getMany();\n```\n\nbut nothing is working. All of these are returning me a empty array. Can somebody help me out thanks\n\n========================================\n\nTop Answer:\nTypeORM provides out of the box `Like` function. Example from their docs:\n\n```\nimport {Like} from \"typeorm\";\n\nconst loadedPosts = await connection.getRepository(Post).find({\n title: Like(\"%out #%\")\n});\n```\n\nin your case:\n\n```\nvar data = await getRepository(User).find({\n name: Like(`%${firstName}%`)\n});\n```\n\n========================================\n\nCode:\n```js\nvar data = await getRepository(User)\n .createQueryBuilder(\"user\")\n .where(\"user.firstName = %:name%\", { name: firstName })\n .getMany();\n```\n\n```js\nvar data = await getRepository(User)\n .createQueryBuilder(\"user\")\n .where(\"user.firstName like %:name%\", { name: firstName })\n .getMany();\n```\n\n```text\nvar data = await getRepository(User)\n .createQueryBuilder(\"user\")\n .where(\"user.firstName like :name\", { name:`%${firstName}%` })\n .getMany();\n```\n\n```js\nimport {Like} from \"typeorm\";\n\nconst loadedPosts = await connection.getRepository(Post).find({\n title: Like(\"%out #%\")\n});\n```\n\n```js\nvar data = await getRepository(User).find({\n name: Like(`%${firstName}%`)\n});\n```\n\n```text\nLike\n```\n\n```text\nvar data = await getRepository(User)\n .createQueryBuilder(\"user\")\n .where(\"user.firstName like '%' || :name || '%'\", {name: firstName })\n .getMany();\n```\n\n```text\nvar data = await getRepository(User)\n .createQueryBuilder(\"user\")\n .where(\"user.firstName ILIKE %q\", {q:`%${VALUE_HERE}%` })\n .getMany();\n```\n\n```text\nlet res = await this.trackingRepository.findAndCount({\n where: [{ username : Like(`%${searchValue}%`) },\n { action : Like(`%${searchValue}%`) },\n { ip : Like(`%${searchValue}%`) }],\n order: {\n [sortField]: sortOrder === \"descend\" ? 'DESC' : 'ASC',\n },\n skip: (current - 1) * pageSize,\n take: pageSize,\n });\n```\n\n```text\nvar data = await getRepository(User)\n .createQueryBuilder(\"user\")\n .where(\"user.firstName like :name\", { name:`%${firstName}%`})\n .getMany();\n```\n\n```text\nconst data = await getRepository(User)\n .createQueryBuilder(\"user\")\n .where(\"user.firstName like :name\", { name: firstName })\n .getOne();\n```\n\n```text\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Index({fulltext: true})\n @Column()\n name: string;\n }\n\n const data = await this.repository\n .createQueryBuilder()\n .select()\n .where('MATCH(name) AGAINST (:name IN BOOLEAN MODE)', {name: name})\n .getOne()\n```\n\n```text\n%\n```\n\n```text\nfirstName\n```\n\n```text\nlet firstName = '%John'\n```\n\n```text\nimport {Like} from \"typeorm\";\n\nconst loadedPosts = await UserRepository.find({\n where: {\n name: Like(\"%Mar%\")\n }\n});\n```\n\n```text\nimport {Like} from \"typeorm\";\n\nconst filters={\n name: 'Ca',\n age: '3'\n}\n\nconst columnFilters={}\nfor(const i in filters){\n columnFilters[i]= Like(`%${filters[i]}%`)\n}\n\nconst loadedPosts = await UserRepository.find({\n where: columnFilters\n});\n```\n\n========================================\n\nComments:\n- Will this properly escape `firstName`?\n- I tested it... I think it does parameterize it.\n- @user3413723 I just tested this. It does escape quotes and other characters, but it does not (and could not) escape \"%\" and \"_\" characters.\n- SQL injection!!!!\n- Is there official documentation for this ? I couldn't find\n- If you're coming here looking for `ilike` like I was, it appears it's coming in an upcoming release: github.com/typeorm/typeorm/pull/5828\n- If the `firstName` is not a safe value, your solution is not protected against SQL injection\n- @LucaRoverelli how do I make it safe from sql injection? is it possible using same syntax?\n- not working on mongodb\n- @LucaRoverelli i think solution is protected against sql injection because here we are not building raw query. value will be injected as parameterized in sql query. We can check underlying query by enabling logging option in datasource.\n- This is vulnerable to sql injection.\n- @tannerburton why? doesn't TypeORM sanitize the parameter, even if surrounded by %?\n- you shouldn't interpolate values manually. Your code is susceptible to SQL injection\n- What will be the best way to replace it ?\n- Use query parameters. I'll update your answer to use query parameters.","metadata":{"transformedAt":"2026-08-18T18:33:44.681Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":204,"estimatedTokens":1288}}5{"id":"stack-54246615","source":"stackoverflow","questionId":54246615,"title":"What’s the difference between remove and delete?","tags":["typescript","typeorm"],"text":"Title: What’s the difference between remove and delete?\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nFor example, I have a TypeORM entity `Profile`:\n\n```\n@Entity()\nclass Profile {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n gender: string;\n\n @Column()\n photo: string;\n\n @OneToOne(type => User, { cascade: true })\n @JoinColumn()\n user: User;\n}\n```\n\nAnd I’m not sure which one should I use to delete a user profile?\n\n```\nProfile.remove(profile)\nProfile.delete(profile)\n```\n\nWhat is the difference between the `remove` and `delete` methods in TypeORM?\n\n========================================\n\nCode:\n```text\n@Entity()\nclass Profile {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n gender: string;\n\n @Column()\n photo: string;\n\n @OneToOne(type => User, { cascade: true })\n @JoinColumn()\n user: User;\n}\n```\n\n```text\nProfile.remove(profile)\nProfile.delete(profile)\n```\n\n```text\nProfile\n```\n\n```text\nremove\n```\n\n```text\ndelete\n```\n\n```text\nawait repository.remove(user);\nawait repository.remove([\n category1,\n category2,\n category3\n]);\n```\n\n```text\nawait repository.delete(1);\nawait repository.delete([1, 2, 3]);\nawait repository.delete({ firstName: \"Timber\" });\n```\n\n```text\nimport {getConnection} from \"typeorm\";\n\nawait getConnection()\n .createQueryBuilder()\n .delete()\n .from(User)\n .where(\"id = :id\", { id: 1 })\n .execute();\n```\n\n```text\nremove\n```\n\n```text\ndelete\n```\n\n```text\nremove\n```\n\n```text\ndelete\n```\n\n```text\nEntity Listener\n```\n\n```text\n@BeforeRemove\n```\n\n```text\n@AfterRemove\n```\n\n```text\nrepository.remove\n```\n\n```text\n@BeforeInsert\n```\n\n```text\n@AfterInsert\n```\n\n```text\n@BeforeUpdate\n```\n\n```text\n@AfterUpdate\n```\n\n```text\nrepository.save\n```\n\n========================================\n\nComments:\n- I guess they have the meanings described here? github.com/typeorm/typeorm/blob/master/docs/… `remove()` being the one you should use when you have a profile object and `delete()` deleting based on criteria.\n- do lifecycle methods happen the same on both?\n- Also be aware that `repository.delete` does not trigger `@Before/After Remove` listeners, only `repository.remove` does. Same way, `repository.update` does NOT trigger `@Before/After Update` listeners, only `repository.save` does.\n- The information that `Before/After-Insert` only trigger with `repository.save` is incorrect! I have tried and it did trigger with `repository.insert` too. From this discussion, pleerock indirectly confirm that insert will also trigger the decorator.\n- @nyotoarif Is `.insert` using Subscribers now? If it does you could request documentation changes for which listener was affected. I've checked Docs and it still states that only `.save` triggered them. I haven't got the time to test them, I will update once I confirm if it does.\n- Given there isn't an `@AfterDelete` method, how does one get the `id` of a recently deleted/removed entity? I'm trying to use `beforeRemove` but it doesn't give access to the underlying document/row.\n- @HarryCramer As mentioned in one of the following discussion of the issue \"The subscriber does not have `beforeDelete`/`afterDelete` methods. You need to use remove method to get the entity information\"\n- Did not find in the documentation, but `remove()` also seems to mutate passed object by deleting the `id` field...\n- unable to understand `remove` method, how does it removes an entity from db table structure point of view? Does it clear the whole table associated with that entity?","metadata":{"transformedAt":"2026-08-18T18:33:44.681Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":164,"estimatedTokens":882}}6{"id":"stack-47792808","source":"stackoverflow","questionId":47792808,"title":"TypeORM: update item and return it","tags":["typescript","rest","orm","api-design","typeorm"],"text":"Title: TypeORM: update item and return it\nTags: typescript, rest, orm, api-design, typeorm\nSource: Stack Overflow\n\nQuestion:\nAs far as I know, it's a best practice to return an item after it has been updated. TypeORM's `updateById` returns `void`, not the updated item though.\n\nMy question: Is it possible to update and return the modified item in a single line?\n\nWhat I tried so far:\n\n```\nawait this.taskRepository.updateById(id, { state, dueDate });\nreturn this.taskRepository.findOne({ id });\n```\n\nWhat I'm looking for:\n\n```\nreturn this.taskRepository.updateById(id, { state, dueDate }); // returns updated task\n```\n\n========================================\n\nTop Answer:\nTo expand on sandrooco's answer, this is what I do:\n\n```\nconst property = await this.propertyRepository.findOne({\n where: { id }\n});\n\nreturn this.propertyRepository.save({\n ...property, // existing fields\n ...updatePropertyDto // updated fields\n});\n```\n\n========================================\n\nCode:\n```text\nawait this.taskRepository.updateById(id, { state, dueDate });\nreturn this.taskRepository.findOne({ id });\n```\n\n```text\nreturn this.taskRepository.updateById(id, { state, dueDate }); // returns updated task\n```\n\n```text\nupdateById\n```\n\n```text\nvoid\n```\n\n```text\nreturn this.taskRepository.save({\n id: task.id,\n state,\n dueDate\n});\n```\n\n```text\n.save\n```\n\n```text\nsave\n```\n\n```text\nconst property = await this.propertyRepository.findOne({\n where: { id }\n});\n\nreturn this.propertyRepository.save({\n ...property, // existing fields\n ...updatePropertyDto // updated fields\n});\n```\n\n```text\nconst post = (await Post.update({id}, {...input})).raw[0];\nreturn post; // returns post of type Post\n```\n\n```text\n@Mutation(() => PostResponse, { nullable: true })\nasync updatePost(\n @Arg(\"id\", () => Int) id: number,\n @Arg(\"input\") input: PostInput,\n): Promise<PostResponse | null> {\n const post = (await Post.update({id}, {...input})).raw[0];\n return { post };\n}\n```\n\n```text\n@Mutation(() => PostResponse, { nullable: true })\n@UseMiddleware(isAuthorized)\nasync updatePost(\n @Arg(\"id\", () => Int) id: number,\n @Arg(\"input\") input: PostInput,\n @Ctx() { req }: Context\n): Promise<PostResponse | null> {\n const post = await (Post.createQueryBuilder()\n .update(Post)\n .set({ ...input })\n .where('id = :id and \"creatorId\" = :creatorId', {\n id,\n creatorId: userId,\n })\n .returning(\"*\")\n .execute())\n .raw[0];\n\n return { post };\n}\n```\n\n```text\nresponse.raw[0]\n```\n\n```text\nawait Table.update({}, {})\n```\n\n```text\nTable\n```\n\n```text\nRepository\n```\n\n```text\nTable.save()\n```\n\n```text\ntype\n```\n\n```text\nTable.update({}, {})\n```\n\n```text\nQueryBuilder\n```\n\n```text\n.returning(\"*\")\n```\n\n```text\nasync findOne(id: string): Promise<Manufacturer> {\n const found = await this.repository.findOneBy({ id });\n\n if (!found) {\n throw new NotFoundException(`Could not find ${this.Entity.name} with id: ${id}`);\n }\n\n return found;\n}\n\nasync update(id: string, updateEmployeeDto: UpdateManufacturerDto): Promise<Manufacturer> {\n await this.findOne(id);\n\n return this.repository.save({ id, ...updateEmployeeDto });\n}\n```\n\n```text\n.save\n```\n\n```text\nasync update(\n updateUserNotificationDto: UpdateUserNotificationDto,\n id: string\n ): Promise<UserNotificationDto> {\n try {\n const entity = await this.userNotificationRepository.update(\n id,\n updateUserNotificationDto\n );\n return UserNotificationDto.fromEntity(entity.raw);\n } catch (e) {\n console.error(e);\n throw new HttpException(\n \"Notification failed to create\",\n HttpStatus.BAD_REQUEST\n );\n }\n }\n```\n\n========================================\n\nComments:\n- If you are looking for `UPDATE ... RETURNING`, it is not supported. Issue link: github.com/typeorm/typeorm/issues/4920\n- What is \"task\"? That wasn't mentioned in the original question.\n- I'm talking about the `..task` variable spreading. That just came out of nowhere and isn't in the original question; there you use `id`.\n- Be aware that `.save` will also create a new Entity when it doesn't exist. This might not always be desired. So `.update` would be a smarter choice and then still do a `.findOne(id: task.id)` to return the entire object.\n- I am maybe incorrect, but from my testing, when you use `.save` to update entity, this method is NOT returning entity back when you use `{...oldEntity, ...updates}`, but only plain object which can be problem for `class-serializer` for example.\n- @Baterka What do you mean by plain object? It returns the entity as usual with typeorm.\n- Afraid the updating by this way is not safe and make the debugging complicated. If specified ID is not existing in database, the new entity will be created which is the unexpected result. And, if some required fields is not specified (which could be fine for updating case but not file for creating operation), the `QueryFailedError:` will be thrown instead of `NotFound`.\n- This still makes 2 calls to the Db. Is there a way to make it make just one call. For example, in Postgres, you can run ``` UPDATE .. SET .. RETURNING * ``` and it would update the data and return the updated rows\n- I didn't find a way around this( I just made two calls there) but one thing I have resolved to do is to write raw queries anywhere I have these kinds of optimization issues that a raw query can give me.\n- This is kind of useless, you don't even need the existing fields (except the `id` of course).\n- You can use the update method. something like *repo.update(Model, modelPk, partiallyUpdatedFields)*. It will perform just one query\n- This makes 2 queries to the database and is not atomic.\n- @Xetera That's very true. If you are on PostgreSQL you could just write a raw query that performs the update and returns it (see this) eg. ``` UPDATE SET c=value RETURNING * ``` If you are not using Postgres then you might as well just perform an update and a find in a transaction. What do you think\n- This is precisely what I didn't want to do...\n- Thanks for sharing, @Joel This question should state its specific to Microsoft SQL Server and/or PostgreSQL, though, as this is not supported for MySQL: `.returning(\"*\")` That renders the answer invalid for those using MySQL.\n- 1. Question was \"Is it possible to update and return the modified item in a single line?\" --> SINGLE line 2. there's findOneOrFail for that\n- .raw[0] is an empty array and doesn't work .","metadata":{"transformedAt":"2026-08-18T18:33:44.681Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":223,"estimatedTokens":1610}}7{"id":"stack-43176006","source":"stackoverflow","questionId":43176006,"title":"TypeError: Class extends value undefined is not a function or null","tags":["javascript","typescript","typeorm"],"text":"Title: TypeError: Class extends value undefined is not a function or null\nTags: javascript, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am getting the following error when trying to create these entities.\n\n`TypeError: Class extends value undefined is not a function or null`\n\nI am assuming this has something to do with circular dependencies, but how is that supposed to be avoided when using table inheritance and one to many relationships?\n\nIt is complaining about the following javascript at `BaseComic_1.BaseComic`.\n\n**`let Variant = class Variant extends BaseComic_1.BaseComic {`**\n\nHere is the complete file.\n\n```\n\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c = 0; i--) if (d = decorators[i]) r = (c 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst typeorm_1 = require(\"typeorm\");\nconst Comic_1 = require(\"./Comic\");\nconst BaseComic_1 = require(\"./BaseComic\");\nlet Variant = class Variant extends BaseComic_1.BaseComic {\n};\n__decorate([\n typeorm_1.ManyToOne(type => Comic_1.Comic, comic => comic.variants),\n __metadata(\"design:type\", Comic_1.Comic)\n], Variant.prototype, \"comic\", void 0);\nVariant = __decorate([\n typeorm_1.ClassEntityChild()\n], Variant);\nexports.Variant = Variant;\n//# sourceMappingURL=Variant.js.map\n```\n\n```\nimport {Entity, Column, PrimaryGeneratedColumn, OneToMany} from \"typeorm\";\nimport {Comic} from \"./Comic\";\n\n@Entity()\nexport class Series {\n\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column(\"text\", {\n length: 30\n })\n public copyright: string;\n\n @Column(\"text\", {\n length: 100\n })\n public attributionText: string;\n\n @Column(\"text\", {\n length: 150\n })\n public attributionHTML: string;\n\n @Column(\"text\", {\n length: 50\n })\n public etag: string;\n\n @Column(\"text\", {\n length: 200\n })\n public title: string;\n\n @Column(\"text\")\n public description: string;\n\n @Column(\"number\", {\n length: 4\n })\n public startYear: number;\n\n @Column(\"number\", {\n length: 4\n })\n public endYear: number;\n\n @Column(\"text\", {\n length: 20\n })\n public rating: string;\n\n @Column(\"text\", {\n length: 20\n })\n public type: string;\n\n @Column(\"text\")\n public thumbnail: string;\n\n @OneToMany(type => Comic, comic => comic.series)\n public comics: Array;\n}\n```\n\n```\nimport {Entity, TableInheritance, PrimaryGeneratedColumn, Column, ManyToOne, DiscriminatorColumn} from \"typeorm\";\nimport {Series} from \"./Series\";\n\n@Entity()\n@TableInheritance(\"class-table\")\n@DiscriminatorColumn({ name: \"type\", type: \"string\"})\nexport class BaseComic {\n\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column(\"text\", {\n length: 30\n })\n public copyright: string;\n\n @Column(\"text\", {\n length: 100\n })\n public attributionText: string;\n\n @Column(\"text\", {\n length: 150\n })\n public attributionHTML: string;\n\n @Column(\"text\", {\n length: 50\n })\n public etag: string;\n\n @Column(\"text\", {\n length: 200\n })\n public title: string;\n\n @Column(\"int\")\n public issue: number;\n\n @Column(\"text\")\n public variantDescription: string;\n\n @Column(\"boolean\")\n public variant: boolean;\n\n @Column(\"text\")\n public description: string;\n\n @Column(\"int\")\n public pageCount: number;\n\n @Column(\"date\")\n public onSaleDate: Date;\n\n @Column(\"date\")\n public unlimitedDate: Date;\n\n @Column(\"text\")\n public thumbnail: string;\n\n @ManyToOne(type => Series, series => series.comics)\n public series: Series;\n}\n```\n\n```\nimport {OneToMany, ClassEntityChild} from \"typeorm\";\nimport {Variant} from \"./Variant\";\nimport {BaseComic} from \"./BaseComic\";\n\n@ClassEntityChild()\nexport class Comic extends BaseComic {\n\n @OneToMany(type => Variant, variant => variant.comic)\n public variants: Variant[];\n}\n```\n\n```\nimport {ManyToOne, ClassEntityChild} from \"typeorm\";\nimport {Comic} from \"./Comic\";\nimport {BaseComic} from \"./BaseComic\";\n\n@ClassEntityChild()\nexport class Variant extends BaseComic {\n\n @ManyToOne(type => Comic, comic => comic.variants)\n public comic: Comic;\n}\n```\n\n========================================\n\nTop Answer:\nAs noted in Thomas Jensen's comment above, circular references can occur not just in Types, but also in files.\nI encountered this same problem when I was exporting both the base and derived types from the same file. Such as:\n\n```\n// index.ts\nexport { BaseClass } from \"./base\";\nexport { DerivedClass } from \"./derived\";\n```\n\nThis is an easy pitfall to fall into. Posting this here in the hopes it'll save someone else the debugging time.\n\n========================================\n\nCode:\n```text\n\"use strict\";\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst typeorm_1 = require(\"typeorm\");\nconst Comic_1 = require(\"./Comic\");\nconst BaseComic_1 = require(\"./BaseComic\");\nlet Variant = class Variant extends BaseComic_1.BaseComic {\n};\n__decorate([\n typeorm_1.ManyToOne(type => Comic_1.Comic, comic => comic.variants),\n __metadata(\"design:type\", Comic_1.Comic)\n], Variant.prototype, \"comic\", void 0);\nVariant = __decorate([\n typeorm_1.ClassEntityChild()\n], Variant);\nexports.Variant = Variant;\n//# sourceMappingURL=Variant.js.map\n```\n\n```text\nimport {Entity, Column, PrimaryGeneratedColumn, OneToMany} from \"typeorm\";\nimport {Comic} from \"./Comic\";\n\n@Entity()\nexport class Series {\n\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column(\"text\", {\n length: 30\n })\n public copyright: string;\n\n @Column(\"text\", {\n length: 100\n })\n public attributionText: string;\n\n @Column(\"text\", {\n length: 150\n })\n public attributionHTML: string;\n\n @Column(\"text\", {\n length: 50\n })\n public etag: string;\n\n @Column(\"text\", {\n length: 200\n })\n public title: string;\n\n @Column(\"text\")\n public description: string;\n\n @Column(\"number\", {\n length: 4\n })\n public startYear: number;\n\n @Column(\"number\", {\n length: 4\n })\n public endYear: number;\n\n @Column(\"text\", {\n length: 20\n })\n public rating: string;\n\n @Column(\"text\", {\n length: 20\n })\n public type: string;\n\n @Column(\"text\")\n public thumbnail: string;\n\n @OneToMany(type => Comic, comic => comic.series)\n public comics: Array<Comic>;\n}\n```\n\n```text\nimport {Entity, TableInheritance, PrimaryGeneratedColumn, Column, ManyToOne, DiscriminatorColumn} from \"typeorm\";\nimport {Series} from \"./Series\";\n\n@Entity()\n@TableInheritance(\"class-table\")\n@DiscriminatorColumn({ name: \"type\", type: \"string\"})\nexport class BaseComic {\n\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column(\"text\", {\n length: 30\n })\n public copyright: string;\n\n @Column(\"text\", {\n length: 100\n })\n public attributionText: string;\n\n @Column(\"text\", {\n length: 150\n })\n public attributionHTML: string;\n\n @Column(\"text\", {\n length: 50\n })\n public etag: string;\n\n @Column(\"text\", {\n length: 200\n })\n public title: string;\n\n @Column(\"int\")\n public issue: number;\n\n @Column(\"text\")\n public variantDescription: string;\n\n @Column(\"boolean\")\n public variant: boolean;\n\n @Column(\"text\")\n public description: string;\n\n @Column(\"int\")\n public pageCount: number;\n\n @Column(\"date\")\n public onSaleDate: Date;\n\n @Column(\"date\")\n public unlimitedDate: Date;\n\n @Column(\"text\")\n public thumbnail: string;\n\n @ManyToOne(type => Series, series => series.comics)\n public series: Series;\n}\n```\n\n```text\nimport {OneToMany, ClassEntityChild} from \"typeorm\";\nimport {Variant} from \"./Variant\";\nimport {BaseComic} from \"./BaseComic\";\n\n@ClassEntityChild()\nexport class Comic extends BaseComic {\n\n @OneToMany(type => Variant, variant => variant.comic)\n public variants: Variant[];\n}\n```\n\n```text\nimport {ManyToOne, ClassEntityChild} from \"typeorm\";\nimport {Comic} from \"./Comic\";\nimport {BaseComic} from \"./BaseComic\";\n\n@ClassEntityChild()\nexport class Variant extends BaseComic {\n\n @ManyToOne(type => Comic, comic => comic.variants)\n public comic: Comic;\n}\n```\n\n```text\nTypeError: Class extends value undefined is not a function or null\n```\n\n```text\nBaseComic_1.BaseComic\n```\n\n```text\nlet Variant = class Variant extends BaseComic_1.BaseComic {\n```\n\n```text\n// index.ts\nexport { BaseClass } from \"./base\";\nexport { DerivedClass } from \"./derived\";\n```\n\n```text\nnode --require ts-node/register path/to/index.ts\n```\n\n```text\ntsc\n```\n\n```text\n--require ts-node/register...\n```\n\n```js\n// jest.config.js\nconst { pathsToModuleNameMapper } = require('ts-jest/utils');\n// In the following statement, replace `./tsconfig` with the path to your `tsconfig` file\n// which contains the path mapping (ie the `compilerOptions.paths` option):\nconst { compilerOptions } = require('./tsconfig');\n\nmodule.exports = {\n // [...]\n moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths /*, { prefix: '<rootDir>/' } */ )\n};\n```\n\n```text\nmoduleNameMapper\n```\n\n```text\njest.config.js\n```\n\n```text\nts-config.json\n```\n\n```text\nEntity\n```\n\n```text\nimport { Entity } from 'typeorm/decorator/entity/Entity';\n```\n\n```text\nimport { Entity } from 'typeorm';\n```\n\n```text\nmadge --circular --extensions ts <directory_path>\n```\n\n```text\nmadge --circular <directory_path>\n```\n\n```text\n.ts\n```\n\n```text\n.js\n```\n\n```text\n// -- app.js --\nimport { AbstractNode } from './internal'\n\n/* as is */\n\n// -- internal.js --\nexport * from './AbstractNode'\nexport * from './Node'\nexport * from './Leaf'\n\n// -- AbstractNode.js --\nimport { Node, Leaf } from './internal'\n\nexport class AbstractNode {\n /* as is */\n}\n\n// -- Node.js --\nimport { AbstractNode } from './internal'\n\nexport class Node extends AbstractNode {\n /* as is */\n}\n\n// -- Leaf.js --\nimport { AbstractNode } from './internal'\n\nexport class Leaf extends AbstractNode {\n /* as is */\n}\n```\n\n```text\nclass Card extends React.Compoonent {\n```\n\n```text\nC:\\Users\\Jeremy>node -v\nv17.1.0\n\nC:\\Users\\Jeremy>npm -v\n8.1.2\n```\n\n```text\nmodule.exports = { AbstractClass } // this will cause issues if you use import/export syntax\n```\n\n```text\nexport class AbstractClass { /* stuff */ }\n```\n\n```text\nC:\\applications\n```\n\n```text\nC:\\Program Files\\nodejs\n```\n\n```text\nnpm install\n```\n\n```text\nexport abstract class BaseService {\n ...\n}\n```\n\n```text\n@Injectable({\n providedIn: 'root'\n})\nexport class MyExtendedService extends BaseService {\n```\n\n```text\n@Injectable()\nexport abstract class BaseService {\n ...\n}\n```\n\n```text\nTypeError: Class extends value undefined is not a function or null\n```\n\n```text\napp.module.ts\n```\n\n```text\n@Injectable\n```\n\n```text\nclass Pointer {}\n```\n\n```text\nexport class Pointer {}\n```\n\n```text\nexport class Arrow extends Pointer {}\n```\n\n```js\n// index.vue\n\nimport Impl from './index'\n```\n\n```text\n/my-component\n index.vue\n index.ts\n```\n\n```text\nindex.vue\n```\n\n```text\nindex.ts\n```\n\n```text\nindex.vue\n```\n\n```text\nindex.ts\n```\n\n```text\ncommon.ts\n```\n\n```text\nentity/\n-- index.ts\n-- base.entity.ts\n-- foo/\n-- --foo.entity.ts\n```\n\n```text\nexport { default as MyBaseEntity } from './base.entity'; // <-- This was the problem\nexport { default as FooEntity } from './foo/foo.entity';\n```\n\n```ts\nimport {\n BaseEntity, BeforeInsert,\n CreateDateColumn,\n ObjectIdColumn,\n UpdateDateColumn\n} from 'typeorm';\nimport { v4 as uuidv4 } from 'uuid';\n\nexport class MyBaseEntity extends BaseEntity {\n @ObjectIdColumn()\n id!: string;\n\n @CreateDateColumn({name: 'created_at'})\n createdAt: Date;\n\n @UpdateDateColumn({name: 'updated_at'})\n updatedAt: Date;\n\n @BeforeInsert()\n beforeInsert() {\n this.id = uuidv4();\n }\n}\n```\n\n```ts\nimport {\n BaseEntity, BeforeInsert,\n CreateDateColumn,\n ObjectIdColumn,\n UpdateDateColumn\n} from 'typeorm';\nimport {Injectable} from '@nestjs/common';\nimport { MyBaseEntity } from './../base.entity';\n\n@Injectable()\n@Entity('foo')\nexport class FooEntity extends MyBaseEntity {}\n```\n\n```text\nClass extends value undefined is not a constructor or null\n```\n\n```text\nclass App extends React.Component () {\n```\n\n```text\nclass App extends React.Component {\n```\n\n```text\nimport React from 'react';\n```\n\n```text\n\"use client\";\n\n// import statements\n\n// code\n```\n\n```text\nNext JS\n```\n\n```text\n13.4.12\n```\n\n```text\nApp Router\n```\n\n```text\nClient Component\n```\n\n```text\nrm -rf node_modules\n\nnpm install\n```\n\n```text\nnode_modules\n```\n\n```text\nnpm i <package>\n```\n\n```text\nclass Parent{\n static foo(){}\n }\n\n class Child extends Parent{\n bar(){\n Parent.foo(); //Circular\n }\n }\n```\n\n```text\nstatic async getDerivedClassInstance() {\n return (await import('./DerivedClass')).DerivedClass;\n}\n```\n\n```text\n(await getDerivedClassInstance()).myFunction()\n```\n\n```text\nlet AssignConsultantCR = class AssignConsultantCR extends change_request_base_entity_1.ChangeRequest {\n ^\n\nTypeError: Class extends value undefined is not a constructor or null\n```\n\n```text\nimport { ChangeRequest } from '@entities/change-request';\n```\n\n```text\nimport { ChangeRequest } from '../change-request/change-request-base.entity';\n```\n\n```text\nexport * from './change-request/change-request.entity';\n```\n\n========================================\n\nComments:\n- I had a circular import issue with browserify. It was inconsistent and weird--modifying the file or commenting and removing things and rerunning would sometimes make it go away. Tricky.\n- Note that it seems that the circular reference is between *files*, not simply *types*. So even when your type references are not circular, you may still have this problem depending on the .ts files your types reside in.\n- @JoshuaKing can you link to a resource regarding that \"limitation\" of cirtualr importing classes in typescript?\n- From my experience also the order of imports is important. I had a User entity und 2 other entities which had the same abstract class. The other 2 entities also imported the User and as long as the abstract class was the last import (mainly after user) everything was fine. As soon as i ordered the imports in another way the application broke.\n- @BrunoBieri it's not Typescript's limitation. This is a runtime error - the module resolver is unable to navigate it's way around the circular import. A good resource I've found is in You Don't Know JS.\n- I just ran into a circular dependency causing this error, however the issue wasn't circular *exports*, it was circular *files*. The default exported class also had exported constants, and those constants were causing a circular dependency. When another class tried to extend the first class, this issue reared it's ugly head. Cost me a full day here. Remember: Circular dependencies are file based, not export based.\n- Due to the large number of possible dependencies, it helps to use a checker like Madge. `npm i --saveDev madge; node_modules/madge/bin/cli.js --warning --circular --extensions ts ./` Needs explicit import paths (no omitted 'index'), still worthwhile.\n- I humbly suggest editing the answer and bolding the **also applies to circular files** part!\n- We also had the same issue in TypeScript project, our issue caused by bad practice of COMMON CONST import. we had shared constants not in a common path in the project.\n- so what is the best work around for this when you have an index file like this. where do you put the base files? Or is an index file kinda of an anti-pattern\n- I don't think `index.ts` files are an anti-pattern, I know some people disagree with that. I think they're a great way to provide a useful public interface to a module. From memory I ended up resolving this issue by refactoring to not require exporting the base class at all. Unfortunately I can't give you a better answer than that.\n- there's something oddly poetic about \"pitfall to fall into\" in a post about circular references... :)\n- @NathanBeach, that's why it is called a tautology. :)\n- This was the issue for me, I had to put the two classes in separate files\n- I have a circular reference with `imports` between my base model and my database adapter, which is bad and I'm about to fix it, but it's still working. What prevented me from starting was some test code in the adapter and once I moved it to a unit test where it belongs this error went away.\n- I ran into this same scenario, where I had an instance of derived class in the base class. Thank you\n- So there is no way to export both the base class and derived class?\n- Thanks for pointing this out! I was able to solve all circular dependencies in my TypeScript project using npmjs.com/package/dependency-cruiser 👍\n- yes, I saw this error when I wasn't mocking things in jest properly - specifically, when mocking an entire module via `__mocks__`, all symbols used from there need to be mocked (or unmocked with `requireActual`, etc)\n- Thank you for sharing this. Weirdly I got No circular dependency found! yet the thing still throws the same error. Though it doesn't solve my problem, I would have spent ages looking for a circular dependency if it weren't for this.\n- I want to put in good word for dpdm an alternative to Madge. In my code, Madge found 1 trivial circular dependency and wasn't helpful at all; dpdm, on the other hand, found 27 substantive circular paths. Recommended.\n- @JoshHansen does dpdm search recursively if a directory is given? I'm pretty sure madge doesn't, and from the github it seems rather abandoned, both reasons enough to prefer dpdm, but the latter doesn't report how many files it analysed so it's hard to tell whether it ignore any subdirectories.\n- The best idea by a long sea mile to get a consistent, clean, maintainable import. Should get way more upvotes.\n- Thanks you! Indeed this answer needs to be upvoted A LOT.\n- This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review\n- This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:44.681Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":70,"totalLines":807,"estimatedTokens":4837}}8{"id":"stack-44974594","source":"stackoverflow","questionId":44974594,"title":"Postgres enum in TypeORM","tags":["postgresql","typeorm"],"text":"Title: Postgres enum in TypeORM\nTags: postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn TypeORM, how can I create a postgres enum type *Gender* as in this raw query\n\n```\nCREATE TYPE public.Gender AS ENUM (\n 'male', 'female'\n);\nALTER TABLE public.person ALTER COLUMN gender TYPE public.gender USING gender::gender;\n```\n\nand use it in the Entity class?\n\nI have tried\n\n```\n@Entity()\nexport class Person {\n @Column('enum')\n gender: 'male' | 'female'\n}\n```\n\nbut obviously this isn't the right way, since I got the error message \"type *enum* does not exist\".\n\nI don't want to use typescript enum either, since it will give me a bunch of 0s and 1s in the database.\n\n========================================\n\nTop Answer:\n### Enum is now supported on TypeOrm for postgres\n\nBy the docs\n\nenum column type is supported by postgres and mysql. There are various possible column definitions:\n\nUsing typescript enums:\n\n```\nexport enum UserRole {\n ADMIN = \"admin\",\n EDITOR = \"editor\",\n GHOST = \"ghost\"\n}\n\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({\n type: \"enum\",\n enum: UserRole,\n default: UserRole.GHOST\n })\n role: UserRole;\n\n}\n```\n\nUsing array with enum values:\n\n```\nexport type UserRoleType = \"admin\" | \"editor\" | \"ghost\",\n\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({\n type: \"enum\",\n enum: [\"admin\", \"editor\", \"ghost\"],\n default: \"ghost\"\n })\n role: UserRoleType;\n}\n```\n\n========================================\n\nCode:\n```text\nCREATE TYPE public.Gender AS ENUM (\n 'male', 'female'\n);\nALTER TABLE public.person ALTER COLUMN gender TYPE public.gender USING gender::gender;\n```\n\n```text\n@Entity()\nexport class Person {\n @Column('enum')\n gender: 'male' | 'female'\n}\n```\n\n```text\nenum Gender {\n Male,\n Female,\n Other\n}\n\n@Entity()\nexport class Person {\n @Column('int')\n gender: Gender\n}\n```\n\n```text\nenum Gender {\n Male = 'male',\n Female = 'female',\n Other = 'other'\n}\n\n@Entity()\nexport class Person {\n @Column('text')\n gender: Gender\n}\n```\n\n```text\n0.1.0\n```\n\n```text\nPostgreSQL\n```\n\n```text\nTypeORM\n```\n\n```text\n@Column\n```\n\n```text\nint\n```\n\n```text\n@IsEnum\n```\n\n```text\nstring\n```\n\n```text\nexport function CheckEnum(tableName: string, fieldName: string, enumValue: any) {\n // Hash enum value and put it as part of constraint name so we can\n // force typeorm to generate migration for enum changes.\n const hash = crypto\n .createHash('sha1')\n .update(Object.values(enumValue).join(''))\n .digest('hex')\n return Check(\n // https://til.hashrocket.com/posts/8f87c65a0a-postgresqls-max-identifier-length-is-63-bytes\n `cke_${tableName}_${fieldName}_${hash}`.slice(0, 63),\n `${fieldName} in (${Object.values(enumValue).map(t => `'${t}'`)})`,\n )\n}\n```\n\n```text\nexport enum Gender {\n Male = 'male',\n Female = 'female',\n Other = 'other'\n}\n\n@Entity()\n@CheckEnum('person', 'gender', Gender)\nexport class Person {\n```\n\n```text\nexport enum UserRole {\n ADMIN = \"admin\",\n EDITOR = \"editor\",\n GHOST = \"ghost\"\n}\n\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({\n type: \"enum\",\n enum: UserRole,\n default: UserRole.GHOST\n })\n role: UserRole;\n\n}\n```\n\n```text\nexport type UserRoleType = \"admin\" | \"editor\" | \"ghost\",\n\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({\n type: \"enum\",\n enum: [\"admin\", \"editor\", \"ghost\"],\n default: \"ghost\"\n })\n role: UserRoleType;\n}\n```\n\n```ss\nenum SomeEnum{\n # ...\n}\n\nclass Entity {\n @Field()\n @Column()\n someEnumField: SomeEnum;\n}\n```\n\n========================================\n\nComments:\n- for the enum name in database it creates prefix with the table name. is it possible to avoid it somehow?\n- @kashlo Are you generating migrations automatically with the orm cli?","metadata":{"transformedAt":"2026-08-18T18:33:44.681Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":244,"estimatedTokens":963}}9{"id":"stack-53922503","source":"stackoverflow","questionId":53922503,"title":"How to implement pagination in NestJS with TypeORM","tags":["typescript","nestjs","typeorm"],"text":"Title: How to implement pagination in NestJS with TypeORM\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIs there any way to get the total count and records with a single query, instead of running it as 2 separate queries?\n\nIf it's not possible, is there any way to reuse the where condition in both queries?\n\n```\nasync findAll(query): Promise {\n const take = query.take || 10\n const skip = query.skip || 0\n const keyword = query.keyword || ''\n\n const builder = this.userRepository.createQueryBuilder(\"user\")\n const total = await builder.where(\"user.name like :name\", { name: '%' + keyword + '%' }).getCount()\n const data = await builder.where(\"user.name like :name\", { name: '%' + keyword + '%' }).orderBy('name', 'DESC').skip(skip).take(take).getMany();\n\n return {\n data: data,\n count: total\n }\n}\n\n{\n count: 10,\n data: [\n {\n id: 1,\n name: 'David'\n },\n {\n id: 2,\n name: 'Alex'\n }]\n}\n```\n\n========================================\n\nTop Answer:\nsumming up...\n\nThis middleware checks if you have the take and skip parameters in the URL, if it does, it converts from string to number, if you don't use the default values. 10 for take and 0 for skip.\n\ntake is the number of results per page and skip, from where it should start reading records.\n\nWith that, I set up to intercept the \"product / paged\" route just for the GET method.\n\nWith this I can retrieve these values in the controller and pass to TypeORM or an SQL query.\n\nhttps://i.sstatic.net/fAZAv.png\n\n```\n@Injectable()\nexport class PagerMiddleware implements NestMiddleware {\n use(req: any, res: any, next: () => void) {\n req.query.take = +req.query.take || 10;\n req.query.skip = +req.query.skip || 0;\n next();\n }\n}\n```\n\n### and apply in module.\n\n```\nexport class AdminFeatureApi implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer.apply(PagerMiddleware)\n .forRoutes({ path: 'product/paged', method: RequestMethod.GET })\n }\n}\n```\n\n### Controller\n\n```\n@Controller('product')\nexport class TrainingDomainController {\n constructor(private service: YourService) {}\n\n @Get('paged')\n get(@Query() { take, skip }) {\n return this.service.findAll(take, skip);\n }\n}\n```\n\n### and service\n\n```\n@Injectable()\nexport class YourService {\n constructor(\n @InjectRepository(YourEntity)\n private readonly repo: MongoRepository\n ) {}\n\n async findAll(take: number = 10, skip: number = 0) {\n const [data, total] = await this.repo.findAndCount({ take, skip });\n return { data, total };\n }\n}\n```\n\nok?\n\n========================================\n\nCode:\n```ts\nasync findAll(query): Promise<Paginate> {\n const take = query.take || 10\n const skip = query.skip || 0\n const keyword = query.keyword || ''\n\n const builder = this.userRepository.createQueryBuilder(\"user\")\n const total = await builder.where(\"user.name like :name\", { name: '%' + keyword + '%' }).getCount()\n const data = await builder.where(\"user.name like :name\", { name: '%' + keyword + '%' }).orderBy('name', 'DESC').skip(skip).take(take).getMany();\n\n return {\n data: data,\n count: total\n }\n}\n\n{\n count: 10,\n data: [\n {\n id: 1,\n name: 'David'\n },\n {\n id: 2,\n name: 'Alex'\n }]\n}\n```\n\n```text\nasync findAll(query): Promise<Paginate> {\n const take = query.take || 10\n const skip = query.skip || 0\n const keyword = query.keyword || ''\n\n const [result, total] = await this.userRepository.findAndCount(\n {\n where: { name: Like('%' + keyword + '%') }, order: { name: \"DESC\" },\n take: take,\n skip: skip\n }\n );\n\n return {\n data: result,\n count: total\n }\n}\n```\n\n```text\ntypeorm\n```\n\n```text\nfindAndCount\n```\n\n```text\nRepository\n```\n\n```text\nasync getPaginatedResults(query: any, transactionManager?: EntityManager): Promise<any> {\n\n}\n```\n\n```text\n@Injectable()\nexport class PagerMiddleware implements NestMiddleware {\n use(req: any, res: any, next: () => void) {\n req.query.take = +req.query.take || 10;\n req.query.skip = +req.query.skip || 0;\n next();\n }\n}\n```\n\n```text\nexport class AdminFeatureApi implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer.apply(PagerMiddleware)\n .forRoutes({ path: 'product/paged', method: RequestMethod.GET })\n }\n}\n```\n\n```text\n@Controller('product')\nexport class TrainingDomainController {\n constructor(private service: YourService) {}\n\n @Get('paged')\n get(@Query() { take, skip }) {\n return this.service.findAll(take, skip);\n }\n}\n```\n\n```text\n@Injectable()\nexport class YourService {\n constructor(\n @InjectRepository(YourEntity)\n private readonly repo: MongoRepository<YourEntity>\n ) {}\n\n async findAll(take: number = 10, skip: number = 0) {\n const [data, total] = await this.repo.findAndCount({ take, skip });\n return { data, total };\n }\n}\n```\n\n```text\nasync findAll(query): Promise<Paginate> {\n const take = query.take || 10\n const page=query.page || 1;\n const skip= (page-1) * take ;\n const keyword = query.keyword || ''\n\n const [result, total] = await this.userRepository.findAndCount(\n {\n where: { name: Like('%' + keyword + '%') }, order: { name: \"DESC\" },\n take: take,\n skip: skip\n }\n );\n\n return {\n data: result,\n count: total\n }\n}\n```\n\n```text\nasync findAll(query): Promise<Paginate> {\n const take= query.take || 10\n const page=query.page || 1;\n const skip= (page-1) * take ;\n const keyword = query.keyword || ''\n\n const data = await this.userRepository.findAndCount(\n {\n where: { name: Like('%' + keyword + '%') }, order: { name: \"DESC\" },\n take: take,\n skip: skip\n }\n );\n return paginateResponse(data ,page,take)\n\n }\n```\n\n```text\nexport function paginateResponse(data,page,limit) {\n const [result, total]=data;\n const lastPage=Math.ceil(total/limit);\n const nextPage=page+1 >lastPage ? null :page+1;\n const prevPage=page-1 < 1 ? null :page-1;\n return {\n statusCode: 'success',\n data: [...result],\n count: total,\n currentPage: page,\n nextPage: nextPage,\n prevPage: prevPage,\n lastPage: lastPage,\n }\n}\n```\n\n```text\n/users?page=4&take=3\n```\n\n```text\nconst userRepository = dataSource.getRepository(User);\nconst _take = query.take || 10;\nconst _skip = query.skip || 0;\n```\n\n```text\nconst qb = await dataSource\n .getRepository(User)\n .createQueryBuilder(\"user\")\n .orderBy(\"user.id\", \"DESC\")\n .take(_take)\n .skip(_skip);\n\n const users = await qb.getMany();\n const total = await qb.getCount();\n```\n\n```text\nconst [users, total] = await userRepository.findAndCount({\n order: {\n id: 'DESC'\n }\n skip: _skip,\n take: _take\n});\n```\n\n========================================\n\nComments:\n- Great example but please add a note that the Like('%' + keyword + '%') will work only on SQL database and not on mongodb.\n- I can't find findAndCount on my model... only find\n- If you want to use the ClassSerializerInterceptor, I made some changes to it so it accepts a return value of type `[Array, number]`. Kind of useful in this context. So you can simply return `getManyAndCount()` and the data will be serialized anyway. Check it out: gist.github.com/ericjeker/08f719aae3b730c820b62136efec9708\n- I am confused. In the docs it says now `findAndCount - Finds entities that match given find options. Also counts all entities that match given conditions, but ignores pagination settings (skip and take options).` Did they change this?\n- OK i figured it out, only the count ignores pagination settings to give total count. Also to everyone trying to use this, in the linked example you definitely want to set skip to be `options.page * options.limit`. Its commented in the linked code and won't give proper result otherwise\n- please describe your answer\n- This middleware checks if you have the take and skip parameters in the URL, if it does, it converts from string to number, if you don't use the default values. 10 for take and 0 for skip. take is the number of results per page and skip, from where it should start reading records. With that, I set up to intercept the \"product / paged\" route just for the GET method. With this I can retrieve these values in the controller and pass to TypeORM or an SQL query.\n- You probably don't need middleware and just perform standard DTOs it's much cleaner.\n- This is a good solution if you want to standardize it throughout the entire app using decorators. Well done\n- This may be too late but we should `parseInt(page)` in `paginateResponse` before dealing with `nextPage` and `prevPage` if we are not parsing it anywhere else.","metadata":{"transformedAt":"2026-08-18T18:33:44.681Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":332,"estimatedTokens":2167}}10{"id":"stack-57871918","source":"stackoverflow","questionId":57871918,"title":"TypeORM: How to order by a relation field","tags":["typescript","typeorm"],"text":"Title: TypeORM: How to order by a relation field\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a `Singer` entity and a related `Song` entity\n\n**`Singer` entity**\n\n```\nexport class Singer {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToMany( type => Song, Song => Song.user )\n songs: Song[];\n\n}\n```\n\n**`Song` entity**\n\n```\nexport class Song {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @ManyToOne( type => Singer, Singer => Singer.songs )\n singer: Singer;\n\n}\n```\n\nI want to get all `Songs` ordered by `Singer` name\n\nI searched the docs and GitHub issues but can't find an answer\nHow can I solve this? better without `QueryBuilder`\n\n========================================\n\nTop Answer:\nI had the same issue i tried to order by custom column but without query builder because i was using Repository, this is my solution :\n\n```\nlet res = await this.trackingRepository.findAndCount({\n where: [{ username : Like(`%${searchValue}%`) },\n { action : Like(`%${searchValue}%`) },\n { ip : Like(`%${searchValue}%`) }],\n order: {\n [sortField]: sortOrder === \"descend\" ? 'DESC' : 'ASC',\n },\n skip: (current - 1) * pageSize,\n take: pageSize,\n });\n```\n\n========================================\n\nCode:\n```text\nexport class Singer {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToMany( type => Song, Song => Song.user )\n songs: Song[];\n\n}\n```\n\n```text\nexport class Song {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @ManyToOne( type => Singer, Singer => Singer.songs )\n singer: Singer;\n\n}\n```\n\n```text\nSinger\n```\n\n```text\nSong\n```\n\n```text\nSinger\n```\n\n```text\nSong\n```\n\n```text\nSongs\n```\n\n```text\nSinger\n```\n\n```text\nQueryBuilder\n```\n\n```js\nrepository.find({\n order: {\n singer: {\n name: \"ASC\"\n }\n }\n})\n```\n\n```text\nconnection.createQueryBuilder(Song, 'songs')\n .leftJoinAndSelect('songs.singer', 'singer')\n .orderBy('singer.name', 'ASC')\n .getMany();\n```\n\n```text\n// first fetch the song and include (=join) the\n// singer by the foreign key \"singer\"\nvar queryResult = await this.entityManager.find(Song, {\n relations: ['singer'],\n});\n\n// then use a library like lodash to do the ordering\nconst songsSortedBySinger = _.orderBy(queryResult, song => song.singer.name);\n```\n\n```text\nEntityManager\n```\n\n```text\nRepository\n```\n\n```text\nrelations\n```\n\n```text\nvar queryResult = await this.youRepository.find(Song, {\n relations: ['singer'],\n order: {\n name: 'ASC',\n },\n});\n```\n\n```text\nlet res = await this.trackingRepository.findAndCount({\n where: [{ username : Like(`%${searchValue}%`) },\n { action : Like(`%${searchValue}%`) },\n { ip : Like(`%${searchValue}%`) }],\n order: {\n [sortField]: sortOrder === \"descend\" ? 'DESC' : 'ASC',\n },\n skip: (current - 1) * pageSize,\n take: pageSize,\n });\n```\n\n```js\nconst queryResult = await this.songRepository.find(Song, {\n relations: ['singer'],\n order: {\n 'singer.name': 'ASC',\n },\n});\n```\n\n```text\nsinger.name\n```\n\n```text\n@Entity(\"sample30_post\", {\n orderBy: {\n title: \"ASC\",\n id: \"DESC\"\n }\n})\nexport class Post {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n}\n```\n\n```text\nsongRepository.find({\n order: {\n singer: {\n name: \"ASC\"\n }\n }\n})\n```\n\n========================================\n\nComments:\n- For the people that only check the accepted answer, `order` now supports nesting.\n- I tried this but i got error field does not exist, after some search i found that i have to add my relation to relations property something like this `repository.find({ relations:{ singer:true } order: { singer: { name: \"ASC\" } }})`\n- If I could accept 2 answers, I would've accepted yours as well. this is the approach I was using, but you explained it in a very nice and elegant way, thank you.\n- Thanks @Budget, no worries :) By the way, other ORMs in other languages actually support your requirement. For example in C# the \"Entity Framework\" allows you to simply write `songs.OrderBy(song => song.singer.name);` and it will automatically perform the join and the sort for you – but unfortunately TypeORM doesn't support this :(\n- Do you know if this type of functionality is supported in EF Core?\n- Yes defintitely, actually I was talking about \"EF Core\".\n- I see 2 cons here: First you're adding another dependency, and second you're sorting once the data is retrieved, so your not actualy sorting the DB data, but the DB results\n- Hi @SebastienH. your points are both valid but I think I've made this already explicitly clear in my first sentence: \" *if you are willing to do the **ordering in-memory** by delegating the task to a **library like lodash** [...].*\n- why this has 2 upvotes, this is not related to the question, we have a problem with ordering by relation entity property.\n- @DedaDev this remark will not improve the solution, thank you\n- @SalahED thanks for sharing the solution while using repository, I was after this and found your answer useful\n- THANK YOU!!!! This worked!\n- This solution is vulnerable to CWE-89 (SQL injection) and should not be used as an example.\n- I updated my solution to not be vulnerable to SQL injection\n- This is certainly good to know and a poorly documented feature but it is worth noting that it does not work when the entity is included via a relation. It's a shame that the `relationOptions` doesn't take such config too","metadata":{"transformedAt":"2026-08-18T18:33:44.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":246,"estimatedTokens":1391}}11{"id":"stack-55098023","source":"stackoverflow","questionId":55098023,"title":"TypeORM cascade option: cascade, onDelete, onUpdate","tags":["cascade","typeorm"],"text":"Title: TypeORM cascade option: cascade, onDelete, onUpdate\nTags: cascade, typeorm\nSource: Stack Overflow\n\nQuestion:\nDo cascade options in TypeORM overlap or do they have a completely different purpose? Their description in the documentation is very scarce and partly missing, or I couldn't find it.\n\nIOW, do the following options\n\n`{ cascade: \"update\" }` = `{ onUpdate: 'CASCADE' }`\n\n`{ cascade: \"remove\" }` = `{ onDelete: 'CASCADE' }`\n\nhave the same effect?\n\nOr the `cascade` option is only for the TypeORM use while `onUpdate` and `onDelete` are only for the DB schema (created by migration)?\n\n========================================\n\nTop Answer:\n`onDelete: 'CASCADE` isn't supported in OneToMany relations yet. More context here: https://github.com/typeorm/typeorm/issues/1913\n\n========================================\n\nCode:\n```text\n{ cascade: \"update\" }\n```\n\n```text\n{ onUpdate: 'CASCADE' }\n```\n\n```text\n{ cascade: \"remove\" }\n```\n\n```text\n{ onDelete: 'CASCADE' }\n```\n\n```text\ncascade\n```\n\n```text\nonUpdate\n```\n\n```text\nonDelete\n```\n\n```js\n@Entity()\nclass Book extends BaseEntity {\n @ManyToOne(() => Author, (author) => author.books, {\n onDelete: 'CASCADE',\n })\n public author?: Author\n}\n\n@Entity()\nclass Author extends BaseEntity {\n @OneToMany(() => Book, (book) => book.author, {\n cascade: true,\n })\n public books: Book[];\n}\n```\n\n```js\nconst author = await Author.findOne({ id: '123' });\nauthor.books.push(new Book(...));\nawait author.save();\n```\n\n```text\ncascade\n```\n\n```text\nonDelete\n```\n\n```text\nauthorId\n```\n\n```text\nBook\n```\n\n```text\ncascade: true\n```\n\n```text\nAuthor\n```\n\n```text\nBook\n```\n\n```text\nonDelete: 'CASCADE\n```\n\n========================================\n\nComments:\n- dude where did you read about the cascade? I could not find it in their documentation.\n- I guess setting `onDelete: 'CASCADE'`in the `@OneToMany`-side has no effect?\n- FYI: as of now cascade got extended. It is not just insert and update only anymore. Current options: `[\"insert\", \"update\", \"remove\", \"soft-remove\", \"recover\"]`\n- This is the best answer to solve the problem. Thanks!\n- The cascade option DOES affect the foreign key constraint. For this example, it will add \"ON DELETE CASCADE\" to the foreign key constraint of author → books for mysql.\n- having same situation. but i cant understand one thing when new book appears it inserts book. Does it work for both directions as well? meaning that if i remove existing book from parent will the book be removed or just the relationship will be cut off?\n- I don't see how one can come to the conclusion that cascade delete isn't supported based on the issue @jstnno links to? The issue mention a bug that was fixed in 2019!","metadata":{"transformedAt":"2026-08-18T18:33:44.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":119,"estimatedTokens":675}}12{"id":"stack-59435293","source":"stackoverflow","questionId":59435293,"title":"TypeORM Entity in NESTJS - Cannot use import statement outside a module","tags":["nestjs","typeorm"],"text":"Title: TypeORM Entity in NESTJS - Cannot use import statement outside a module\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nStarted new project with 'nest new' command. Works fine until I add entity file to it.\n\nGot following error:\n\n import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n \n ^^^^^^\n\n \n SyntaxError: Cannot use import statement outside a module\n\nWhat do I miss?\n\nAdding Entity to Module:\n\n```\nimport { Module } from '@nestjs/common';\nimport { BooksController } from './books.controller';\nimport { BooksService } from './books.service';\nimport { BookEntity } from './book.entity';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [TypeOrmModule.forFeature([BookEntity])],\n controllers: [BooksController],\n providers: [BooksService],\n})\nexport class BooksModule {}\n```\n\napp.module.ts:\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Connection } from 'typeorm';\nimport { BooksModule } from './books/books.module';\n\n@Module({\n imports: [TypeOrmModule.forRoot()],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n========================================\n\nTop Answer:\nIn the TypeORM documentation, i found a specific section for Typescript.\n\nThis section says:\n\n Install ts-node globally:\n\n```\nnpm install -g ts-node\n```\n\n \n Add typeorm command under scripts section in package.json\n\n```\n\"scripts\" {\n ...\n \"typeorm\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js\" \n}\n```\n\n \n Then you may run the command like this:\n\n```\nnpm run typeorm migration:run\n```\n\n \n If you need to pass parameter with dash to npm script, you will need\n to add them after --. For example, if you need to generate, the\n command is like this:\n\n```\nnpm run typeorm migration:generate -- -n migrationNameHere\n```\n\nThis works with my file config:\n\n```\n{\n \"type\": \"postgres\",\n \"host\": \"yourhost\",\n \"port\": 5423,\n \"username\": \"username\",\n \"password\": \"password\",\n \"database\": \"your_db\",\n \"synchronize\": true,\n \"entities\": [\n \"src/modules/**/*.entity.{ts,js}\"\n ],\n \"migrations\": [\n \"src/migrations/**/*.{ts,js}\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/modules\",\n \"migrationsDir\": \"src/migrations\"\n }\n}\n```\n\nThen you can run the generate command.\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\nimport { BooksController } from './books.controller';\nimport { BooksService } from './books.service';\nimport { BookEntity } from './book.entity';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [TypeOrmModule.forFeature([BookEntity])],\n controllers: [BooksController],\n providers: [BooksService],\n})\nexport class BooksModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Connection } from 'typeorm';\nimport { BooksModule } from './books/books.module';\n\n@Module({\n imports: [TypeOrmModule.forRoot()],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nentities: ['src/**/*.entity.{ts,js}']\n```\n\n```text\nentities: ['../**/*.entity.{ts,js}']\n```\n\n```text\nentities: [join(__dirname, '**', '*.entity.{ts,js}')]\n```\n\n```json\nentities: [\"dist/**/*.entity.js\"]\n```\n\n```json\nautoLoadEntities: true,\n```\n\n```text\nTypeormModule\n```\n\n```text\nentities\n```\n\n```text\nts\n```\n\n```text\njs\n```\n\n```text\njoin\n```\n\n```text\npath\n```\n\n```text\n__dirname\n```\n\n```text\nsrc\n```\n\n```text\ndist\n```\n\n```text\nts\n```\n\n```text\njs\n```\n\n```text\n.js\n```\n\n```text\nTypeormModule.forRoot()\n```\n\n```text\normconfig.json\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { ProjectsService } from './projects.service';\nimport { Projects } from './projects.entity';\n\nimport { ProjectsResolvers } from './projects.resolvers';\n\n@Module({\n imports: [\n TypeOrmModule.forFeature([Projects])],\n providers: [\n ProjectsService,\n ProjectsResolvers\n ],\n\n})\n\nexport class ProjectsModule {}\n```\n\n```text\n\"entities\" : [\n \"dist/entity/**/*.js\"\n ],\n \"migrations\" : [\n \"dist/migration/**/*.js\"\n ],\n \"subscribers\": [\n \"dist/subscriber/**/*.js\"\n ],\n```\n\n```text\normconfig.json\n```\n\n```text\nts\n```\n\n```text\normconfig.json\n```\n\n```text\nnpm install -g ts-node\n```\n\n```text\n\"scripts\" {\n ...\n \"typeorm\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js\" \n}\n```\n\n```text\nnpm run typeorm migration:run\n```\n\n```text\nnpm run typeorm migration:generate -- -n migrationNameHere\n```\n\n```text\n{\n \"type\": \"postgres\",\n \"host\": \"yourhost\",\n \"port\": 5423,\n \"username\": \"username\",\n \"password\": \"password\",\n \"database\": \"your_db\",\n \"synchronize\": true,\n \"entities\": [\n \"src/modules/**/*.entity.{ts,js}\"\n ],\n \"migrations\": [\n \"src/migrations/**/*.{ts,js}\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/modules\",\n \"migrationsDir\": \"src/migrations\"\n }\n}\n```\n\n```text\n\"module\": \"es6\"\n```\n\n```text\n\"module\": \"commonjs\",\n```\n\n```text\nentities: ['dist/**/*.entity.js']\n```\n\n```text\n{\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"xxxxxxxx\",\n \"password\": \"xxxxxxxx\",\n \"database\": \"typescript_orm\",\n \"synchronize\": true,\n \"logging\": false,\n \"migrationTableName\": \"migrations\",\n \"entities\": [\n \"dist/**/*.entity.js\"\n ],\n \"migrations\": [\n \"src/migration/**/*.{ts, js}\"\n ],\n \"suscribers\": [\n \"src/suscriber/**/*.{ts, js}\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/model\",\n \"migrationDir\": \"src/migration\",\n \"suscribersDir\": \"src/suscriber\"\n }\n}\n```\n\n```text\n// This is your ormconfig.json file\n\n...\n\"entities\": [\"dist/**/*.entity{.ts,.js}\"]\n...\n```\n\n```text\normconfig.json\n```\n\n```text\nts-node ./node_modules/typeorm/cli.js migration:generate -n <MirgrationName> -c <ConnectionType>\n```\n\n```text\nts-node ./node_modules/typeorm/cli.js migration:create -n AuthorHasMultipleBooks -c development\n```\n\n```text\normconfig.js\n```\n\n```text\nnode_modules\n```\n\n```js\n// FILE: src/config/ormconfig.ts\n\nconst connectionOptions: ConnectionOptions = {\n \n // Other configs here\n\n // My ormconfig isn't in root folder\n entities: [`${__dirname}/../**/*.entity.{ts,js}`],\n synchronize: false,\n dropSchema: false,\n migrationsRun: false,\n migrations: [getMigrationDirectory()],\n cli: {\n migrationsDir: 'src/migrations',\n }\n}\n\nfunction getMigrationDirectory() {\n const directory = process.env.NODE_ENV === 'migration' ? 'src' : `${__dirname}`;\n return `${directory}/migrations/**/*{.ts,.js}`;\n}\n\nexport = connectionOptions;\n```\n\n```json\n// FILE package.json\n\n{\n // Other configs here\n\n \"scripts\": {\n \"typeorm\": \"NODE_ENV=migration ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config src/config/database.ts\",\n \"typeorm:migrate\": \"npm run typeorm migration:generate -- -n\",\n \"typeorm:run\": \"npm run typeorm migration:run\",\n \"typeorm:revert\": \"npm run typeorm migration:revert\"\n }\n}\n```\n\n```text\n\"typeorm\": \"ts-node-dev ./node_modules/typeorm/cli.js\"\n```\n\n```text\nyarn typeorm migration:run\n```\n\n```text\ntsc\n```\n\n```text\nnodemon server.js\n```\n\n```text\nts-node server.ts\n```\n\n```text\nnode server.js\n```\n\n```text\ntsc\n```\n\n```sh\nnano ~/.zshrc\n```\n\n```sh\nalias typeorm=\"ts-node ./node_modules/typeorm/cli.js\"\n```\n\n```sh\n. ~/.zshrc\n```\n\n```text\nts-node\n```\n\n```text\nnode_modules\n```\n\n```text\nTYPEORM_ENTITIES=\"entities/*.ts\"\nTYPEORM_MIGRATIONS=\"migrations/*.ts\"\nTYPEORM_ENTITIES_DIR=\"entities\"\nTYPEORM_MIGRATIONS_DIR=\"migrations\"\n```\n\n```text\n{\n \"extends\": \"./tsconfig.json\",\n \"compilerOptions\": {\n \"module\": \"commonjs\"\n }\n}\n```\n\n```text\n\"local\": \"DOTENV_CONFIG_PATH=./.env ts-node -P ./tsconfig.yarn.json -r dotenv/config\"\n```\n\n```text\n\"typeorm:local\": \"yarn local ./node_modules/typeorm/cli.js\"\n```\n\n```text\n\"g:migration\": \"yarn typeorm:local migration:generate -n\"\n```\n\n```text\nnpm run g:migration -- User\n```\n\n```text\n.env\n```\n\n```text\normconfig.json\n```\n\n```text\n.js\n```\n\n```text\n*.ts\n```\n\n```text\nts-node\n```\n\n```text\normconfig.json\n```\n\n```text\ntsconfig.json\n```\n\n```js\nimport parseBoolean from '@eturino/ts-parse-boolean';\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\nimport * as dotenv from 'dotenv';\nimport { join } from 'path';\n\ndotenv.config();\n\nexport = [\n {\n //name: 'default',\n type: 'mssql',\n host: process.env.DEFAULT_DB_HOST,\n username: process.env.DEFAULT_DB_USERNAME,\n password: process.env.DEFAULT_DB_PASSWORD,\n database: process.env.DEFAULT_DB_NAME,\n options: {\n instanceName: process.env.DEFAULT_DB_INSTANCE,\n enableArithAbort: false,\n },\n logging: parseBoolean(process.env.DEFAULT_DB_LOGGING),\n dropSchema: false,\n synchronize: false,\n migrationsRun: parseBoolean(process.env.DEFAULT_DB_RUN_MIGRATIONS),\n migrations: [join(__dirname, '..', 'model/migration/*.{ts,js}')],\n cli: {\n migrationsDir: 'src/model/migration',\n },\n entities: [\n join(__dirname, '..', 'model/entity/default/**/*.entity.{ts,js}'),\n ],\n } as TypeOrmModuleOptions,\n {\n name: 'other',\n type: 'mssql',\n host: process.env.OTHER_DB_HOST,\n username: process.env.OTHER_DB_USERNAME,\n password: process.env.OTHER_DB_PASSWORD,\n database: process.env.OTHER_DB_NAME,\n options: {\n instanceName: process.env.OTHER_DB_INSTANCE,\n enableArithAbort: false,\n },\n logging: parseBoolean(process.env.OTHER_DB_LOGGING),\n dropSchema: false,\n synchronize: false,\n migrationsRun: false,\n entities: [],\n } as TypeOrmModuleOptions,\n];\n```\n\n```js\nimport configuration from '@config/configuration';\nimport validationSchema from '@config/validation';\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { LoggerService } from '@shared/logger/logger.service';\nimport { UsersModule } from '@user/user.module';\nimport { AppController } from './app.controller';\nimport ormconfig = require('./config/ormconfig'); //path mapping doesn't work here\n\n@Module({\n imports: [\n ConfigModule.forRoot({\n cache: true,\n isGlobal: true,\n validationSchema: validationSchema,\n load: [configuration],\n }),\n TypeOrmModule.forRoot(ormconfig[0]), //default\n TypeOrmModule.forRoot(ormconfig[1]), //other db\n LoggerService,\n UsersModule,\n ],\n controllers: [AppController],\n})\nexport class AppModule {}\n```\n\n```json\n\"scripts\": {\n ...\n \"typeorm\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./src/config/ormconfig.ts\",\n \"typeorm:migration:generate\": \"npm run typeorm -- migration:generate -n\",\n \"typeorm:migration:run\": \"npm run typeorm -- migration:run\"\n },\n```\n\n```text\nsrc/\n├── app.controller.ts\n├── app.module.ts\n├── config\n│ ├── configuration.ts\n│ ├── ormconfig.ts\n│ └── validation.ts\n├── main.ts\n├── model\n│ ├── entity\n│ ├── migration\n│ └── repository\n├── route\n│ └── user\n└── shared\n └── logger\n```\n\n```text\nTYPEORM_ENTITIES = src/modules/*.entity.ts\nTYPEORM_MIGRATIONS = src/migrations/*.entity.ts\nTYPEORM_MIGRATIONS_RUN = src/migrations\nTYPEORM_ENTITIES_DIR = src/modules\nTYPEORM_MIGRATIONS_DIR = src/migrations\n```\n\n```text\nnest start\n```\n\n```text\nTYPEORM_ENTITIES = dist/modules/*.entity.js\n TYPEORM_MIGRATIONS = dist/migrations/*.entity.js\n TYPEORM_MIGRATIONS_RUN = dist/migrations\n TYPEORM_ENTITIES_DIR = dist/modules\n TYPEORM_MIGRATIONS_DIR = dist/migrations\n```\n\n```text\nnode-ts\n```\n\n```text\nnest start\n```\n\n```text\nnest start\n```\n\n```text\nmodule.exports = {\n apps: [\n {\n name: \"app\",\n script: \"./build/index.js\",\n },\n ],\n };\n```\n\n```text\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"password\",\n \"database\": \"db_name\",\n \"synchronize\": false,\n \"logging\": true,\n \"entities\": [\n \"../src/entity/**/*.ts\", ===>>> this line is important\n \"./build/entity/**/*.js\"\n ],\n \"migrations\": [\n \"../src/migration/**/*.ts\",===>>> this line is important\n \"./build/migration/**/*.js\"\n ],\n \"subscribers\": [\n \"../src/subscriber/**/*.ts\",===>>> this line is important\n \"./build/subscriber/**/*.js\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\n```text\n{\n \"compilerOptions\": {\n \"lib\": [\n \"es5\",\n \"es6\"\n ],\n \"target\": \"es5\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"outDir\": \"./build\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"sourceMap\": true,\n \"esModuleInterop\": true\n }\n}\n```\n\n```text\ntsc =>> This command generate \"build\" folder\n```\n\n```text\ntsc && pm2 start pm2.config.js\n```\n\n```text\npm2.config.js\n```\n\n```text\normconfig.js\n```\n\n```text\ntsconfig.json\n```\n\n```text\npm2\n```\n\n```text\n\"../src/entity/**/*.ts\"\n```\n\n```text\n\"src/entity/**/*.ts\"\n```\n\n```text\n\"nodemon --exec ts-node ./src/index.ts\"\n```\n\n```text\nimport { SomeClassFromTypeorm } from 'typeorm/browser';\n```\n\n```text\n'/browser'\n```\n\n```text\n{ \n \"type\": \"cockroachdb\",\n \"host\": \"localhost\",\n \"port\": 26257,\n \"username\": \"root\",\n \"password\": \"\",\n \"database\": \"test\",\n \"entities\": [\"dist/**/*.entity{.ts,.js}\"],\n \"migrations\": [\"migration/*.js\"],\n \"synchronize\": false,\n \"cli\": {\n \"migrationsDir\": \"migration\"\n }\n}\n```\n\n```text\n\"typeorm\": \"node --require ts-node/register ./node_modules/typeorm/cli.js\"\n```\n\n```text\nnpm run typeorm migration:generate -- -o -n init\n```\n\n```text\nnpm run start:dev\n```\n\n```text\normconfig,json\n```\n\n```text\npackage.json\n```\n\n```text\n-o\n```\n\n```json\n\"scripts\": {\n \"typeorm\": \"typeorm-ts-node-commonjs\"\n }\n```\n\n```json\n\"scripts\": {\n \"typeorm\": \"typeorm-ts-node-esm\"\n }\n```\n\n```text\nnpm run -- typeorm migration:generate --dataSource path/to/data-source.ts NameOfMigration\n```\n\n```text\ntypeorm migration:generate\n```\n\n```text\nnpx typeorm init\n```\n\n```text\npackage.json\n```\n\n```text\nentities: ['src/**/*.entity.{ts,js}']\n```\n\n```text\nimport { Answer } from './entities/answer/answer.entity';\n\nentities: [Answer]\n```\n\n```text\nTypeOrmModule.forRoot({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: '#GoHomeGota',\n database: 'quiz',\n **entities: [\"dist/**/*.entity{.ts,.js}\"],**\n synchronize: true,\n}),\n```\n\n```text\n//content of cli-orm-config.ts\n\nimport { DataSource, DataSourceOptions } from \"typeorm\"\nimport 'dotenv/config'\n\nexport const cliOrmConfig: DataSourceOptions = {\n type: 'postgres',\n host: process.env.DATABASE_HOST,\n port: (process.env.PG_DATABASE_PORT as any) as number,\n username: process.env.PG_DATABASE_USER,\n password: process.env.PG_DATABASE_PASSWORD,\n database: process.env.DATABASE_NAME,\n entities: [\"src/**/*/*.entity{.ts,.js}\"],\n migrations: [\"src/**/*/*-Migration{.ts,.js}\"]\n}\n\nconst datasource = new DataSource(cliOrmConfig)\n\nexport default datasource\n```\n\n```text\n//content of orm-config.ts, this is the one I use in nest TypeOrmModule.forRoot(ormConfig)\n\nimport { DataSource, DataSourceOptions } from 'typeorm';\nimport 'dotenv/config'\n\n\nexport const ormConfig: DataSourceOptions = {\n type: 'postgres',\n host: process.env.DATABASE_HOST,\n port: (process.env.PG_DATABASE_PORT as any) as number,\n username: process.env.PG_DATABASE_USER,\n password: process.env.PG_DATABASE_PASSWORD,\n database: process.env.DATABASE_NAME,\n entities: [\"dist/src/**/*/*.entity{.ts,.js}\"]\n}\n\nconst datasource = new DataSource(ormConfig)\n\nexport default datasource\n```\n\n```text\n// My package.json relevant scripts section\n\n\"typeorm\": \"ts-node ./node_modules/typeorm/cli -d ./src/db/cli-orm-config.ts\",\n\"nest:migration:generate\": \"npm run typeorm migration:generate ./src/db/migrations/Migration\",\n\"nest:migration:run\": \"npm run typeorm migration:run\"\n```\n\n```text\n\"module\": \"esnext\"\n```\n\n```text\n\"module\": \"commonjs\",\n```\n\n```text\ntsconfig.ts\n```\n\n```text\nnpx ts-node ./node_modules/.bin/typeorm migration:generate -n MigrationName -d src/migrations\n```\n\n```text\nnpx ts-node ./node_modules/.bin/typeorm migration:generate src/migration/MigrationName -d ormconfig.js\n```\n\n```js\nimport { DataSource, DataSourceOptions } from 'typeorm';\nimport { ConfigService } from '@nestjs/config';\nimport { config } from 'dotenv';\nimport * as path from 'path';\nimport { User } from '../users/users.entity';\nimport { FileStorage } from '../storage/storage.entity';\n\n// Load environment variables\nconfig({ path: `.env.${process.env.ENV}` });\n\nconst configService = new ConfigService();\n\n// Minimal data source options\nexport const dataSourceOptionsMinimal = {\n type: 'postgres',\n host: configService.getOrThrow('DB_HOST'),\n port: parseInt(configService.getOrThrow('DB_PORT'), 10),\n username: configService.getOrThrow('DB_USERNAME'),\n password: configService.getOrThrow('DB_PASSWORD'),\n database: configService.getOrThrow('DB_DATABASE'),\n};\n\n// Full data source options\nexport const dataSourceOptions: DataSourceOptions = {\n ...dataSourceOptionsMinimal,\n type: 'postgres',\n entities: [User, FileStorage],\n migrations: [path.join(__dirname, 'migrations/**/*.{ts,js}')],\n migrationsTableName: 'migrations',\n};\n\nexport default new DataSource(dataSourceOptions);\n```\n\n```text\nThis could happen if your project is set up in such a way that the working directory is not the root of your project but some other directory. Using /src ensures that the path is correctly resolved regardless of where the command is run.\n```\n\n```text\n\"dev\": \"nest start --watch\",\n```\n\n```text\n\"dev\": \"NODE_ENV=test 'ts-node' src/main.ts\",\n```\n\n```text\n.ts\n```\n\n```text\nts-node\n```\n\n```text\nnest start\n```\n\n```text\npackage.json\n```\n\n```text\nts-node\n```\n\n========================================\n\nComments:\n- import { Module } from '@nestjs/common';\n- @Preston care to elaborate on what you mean? Do you have to create a module for commonly shared files?\n- Are you getting the error from your linter or from a compilation? Where do you have this new file? Is it in your `src` directory? If you're using TypeORM, can you show your `TypeOrmModule` import in the `AppModule`'s `imports` array? There may be something wrong with the configuration we can't see\n- updated post with entity import info\n- Excellent. So does that mean you can ever have a base entity shared across multiple modules or would that base entity have to be part of a commons module of sorts?\n- I think i've already imported entity to module. Please take a look at updated post\n- Sorry Anton, I'm traveling on vacation now and can't help you until January. I would have to look at my old REST modules and I don't have them with me.\n- Anton, if you have already solved this then please post your solution to SO.\n- But this is a total mess. A typescript ORM that does not accept typescript for the migrations...\n- `deno` is the only native typescript code runner. `TypeORM`, while it uses Typescript, still works with `Node` and the JavaScript runtime. Maybe improvements can be made to accept `ts` files and compile them into JavaScript under the hood, then delete them so the end user doesn't see them, but that would need to be brought up as an issue on the TypeORM git repository\n- actually full line must be \"entities\": [\"dist/**/*.entity.js\"], because of json syntax.\n- I absolutely agree that having to reach into the transpiled JS for all this mess to work is a joke.\n- The Issue #4283 on Github explains in details why JavaScript should be used to read entities from Dist folder. This is the magic line I changed in `ormconfig.js` in the root folder, you too can try and see. `entities: ['dist/**/*.entity.js']` is the solution.\n- This is insane. Aren't we doing Typescript not to have to deal with this garbage?\n- The complaints in this thread is hilarious. How do you guys think Typescript works 🤣? You can still write the migrations in typescript, you just have to point the configuration to the transpiled JS from the TS you wrote. You are still using Typescript for development, but the library uses the transpiled JS. If you are mad about why a library uses transpiled JS, consider evaluating why such an implementation detail even matters to you at all. You're literally not interacting with the JS directly, you are still coding in TS.\n- it actually accepts the .ts migration file, please check the \"Running the migrations\" topic at https://wanago.io/2022/07/25/api-nestjs-database-migrations-‌​typeorm/. Basically as for 2024 you have to manually add the migration file via import syntax to the migrations array since string paths will be deprecated. Hope it helps\n- The `src` should probably be changed to `dist` as that's where the runnable code is after being transpiled to javascript.\n- It took me a while: During runtime, code will be run off the 'dist' (Distribution) folder. And the *.entity.ts file containing the database model, will be translated to .js file by TypeOrm. Hence - entities entry should point to *.entity.js under the 'dist' folder. Thank you all. Save my day.\n- 22.04.23 I had to run this: `npm run typeorm migration:generate -- migrationNameHere -d ./src/data-source.ts`\n- not working \"Not enough non-option arguments: got 0, need at least 1\"\n- doesnt work. \"Missing required argument: dataSource\"\n- I had to update `migrations` to match your syntax\n- I used this solution only for production. for development I change \"../src/entity/**/*.ts\" to \"src/entity/**/*.ts\" and then run \"nodemon --exec ts-node ./src/index.ts\" and it works\n- It it helps anyone else, this exact same thing happened to me, on a nestjs & typeorm project. `import { Unique } from 'typeorm/browser';` just needed to be changed to `import { Unique } from 'typeorm';`\n- That is not a solution. You just created a workaround and pretend that the problem is fixed.\n- I don't pretend that the problem is fixed, I just wanted to help and add the workaround that worked for me. Maybe it'll shad more light on the issue and help someone figure out a solution.\n- this idea sort of fixed for me...","metadata":{"transformedAt":"2026-08-18T18:33:44.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":125,"totalLines":1038,"estimatedTokens":5564}}13{"id":"stack-57611633","source":"stackoverflow","questionId":57611633,"title":"TypeORM array is not supported in postgres?","tags":["javascript","node.js","postgresql","typescript","typeorm"],"text":"Title: TypeORM array is not supported in postgres?\nTags: javascript, node.js, postgresql, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a column `kid_ages` which is `Integer[]`. When migrating, I get the following error:\n\n`DataTypeNotSupportedError: Data type \"Array\" in \"home.kid_ages\" is not supported by \"postgres\" database.`\n\nI tried adding the following options to my column:\n\n```\ntype: 'array'\n```\n\nand:\n\n```\narray: true,\ndefault: [],\nnullable: false,\n```\n\nlike this:\n\n```\n@Column({\n array: true,\n default: [],\n nullable: false,\n})\nkid_ages: string;\n```\n\n========================================\n\nTop Answer:\nFor people looking to deal with arrays or string within your entities, based on @thopaw 's answer, you can use the following code:\n\n```\n@Column(\"text\", { array: true })\nkid_ages: string[];\n```\n\n========================================\n\nCode:\n```text\ntype: 'array'\n```\n\n```text\narray: true,\ndefault: [],\nnullable: false,\n```\n\n```text\n@Column({\n array: true,\n default: [],\n nullable: false,\n})\nkid_ages: string;\n```\n\n```text\nkid_ages\n```\n\n```text\nInteger[]\n```\n\n```text\nDataTypeNotSupportedError: Data type \"Array\" in \"home.kid_ages\" is not supported by \"postgres\" database.\n```\n\n```text\n@Column(\"int\", { array: true })\narray: number[];\n```\n\n```text\nkid_ages: string[];\n```\n\n```text\n@Column(\"int\", { array: true })\nkid_ages: number[];\n```\n\n```text\nkid = getRepository('kid')\n .createQueryBuilder()\n .where(':kid_age = ANY (kid.kid_ages)', { kid_age: 5 });\n```\n\n```js\n@Column(\"text\", { array: true })\nkid_ages: string[];\n```\n\n```text\n@Column(\"text\", { array: true, default: \"{}\" })\n tags: string[];\n```\n\n```text\nthis.getFindQueryBuilder().where(\"recipe.tags && ARRAY[:...tags]\", {tags: tags})\n```\n\n```text\n@Column(\"int\", { array: true, default: {} })\nages: Number[];\n```\n\n```text\n@Column({array: true})\ntags: string;\n```\n\n```text\nsimple-array\n```\n\n```js\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column(\"simple-array\")\n names: string[]\n}\n```\n\n```text\nsimple-array\n```\n\n```text\ntext\n```\n\n========================================\n\nComments:\n- hmm, I seem to be getting an error using this: \" You need to provide explicit type\" Im using the following nullable type: @Field({ nullable: true }) @Column('text', { array: true }) tags?: string[] | null\n- I am no TypeORM Expert but you could try to default the null value to an empty array `@Column({ type: \"text\", array: true, default: [] })`\n- actually today (^0.3.0) it's just enough to use this one: `repository.find({ where: { kid_ages: ArrayContains([5]), }}`\n- Yes, there is an example stackoverflow.com/a/64301112/1074834","metadata":{"transformedAt":"2026-08-18T18:33:44.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":152,"estimatedTokens":666}}14{"id":"stack-59031198","source":"stackoverflow","questionId":59031198,"title":"Typeorm how to get relations of relations","tags":["mysql","typeorm"],"text":"Title: Typeorm how to get relations of relations\nTags: mysql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am getting the Object ChatRoomEntity with `entitymanager.findOne` method. The ChatRoomEntity has the variable `messages` which is a OneToMany - ManyToOne Relation. I have no problems to select that but how do I get the user which sent the message. Its a variable on MessageEntity with a OneToMany Relation.\n\nSo basically I want to select a room and all messages of it. But all messages should also have their values on `fromUser`.\nI select the room like this:\n\n```\nthis.entityManager.findOne(ChatRoomEntity, {where: {id: roomToJoin.id}, relations: ['activeUsers', 'messages']}).then(roomEntity => {\n// some code\n}\n```\n\nHere my entities:\n\nUserEntity\n\n```\n@Entity()\nexport class UserEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @CreateDateColumn()\n registrationDate: Date;\n\n @ManyToMany(type => ChatRoomEntity, room => room.activeUsers, {cascade: true})\n @JoinTable()\n activeChatRooms: ChatRoomEntity[];\n\n @OneToMany(type => ChatRoomMessageEntity, msg => msg.fromUser)\n chatRoomMessages: ChatRoomMessageEntity[];\n}\n```\n\nChatRoomEntity\n\n```\n@Entity()\nexport class ChatRoomEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column('varchar', {nullable: true})\n title: string;\n\n @OneToMany(type => ChatRoomMessageEntity, chatrmsg => chatrmsg.chatRoom)\n messages: ChatRoomMessageEntity[];\n\n @ManyToMany(type => UserEntity, user => user.activeChatRooms)\n activeUsers: UserEntity[];\n\n}\n```\n\nChatRoomMessageEntity\n\n```\n@Entity()\nexport class ChatRoomMessageEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column('varchar', {nullable: true})\n message: string;\n\n @CreateDateColumn()\n creationDate: Date;\n\n @ManyToOne(type => UserEntity, user => user.chatRoomMessages)\n fromUser: UserEntity;\n\n @ManyToOne(type => ChatRoomEntity, chatRoom => chatRoom.messages)\n chatRoom: ChatRoomEntity;\n\n}\n```\n\n========================================\n\nTop Answer:\n### Using QueryBuilder\n\n```\nawait getRepository(UserEntity)\n .createQueryBuilder('user')\n .leftJoinAndSelect('user.profile', 'profile')\n .leftJoinAndSelect('profile.images', 'images')\n .getMany()\n```\n\n### Using FindOptions\n\n```\nawait getRepository(UserEntity).find({ \n relations: ['profile', 'profile.images'] \n})\n```\n\n========================================\n\nCode:\n```text\nthis.entityManager.findOne(ChatRoomEntity, {where: {id: roomToJoin.id}, relations: ['activeUsers', 'messages']}).then(roomEntity => {\n// some code\n}\n```\n\n```text\n@Entity()\nexport class UserEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @CreateDateColumn()\n registrationDate: Date;\n\n @ManyToMany(type => ChatRoomEntity, room => room.activeUsers, {cascade: true})\n @JoinTable()\n activeChatRooms: ChatRoomEntity[];\n\n @OneToMany(type => ChatRoomMessageEntity, msg => msg.fromUser)\n chatRoomMessages: ChatRoomMessageEntity[];\n}\n```\n\n```text\n@Entity()\nexport class ChatRoomEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column('varchar', {nullable: true})\n title: string;\n\n @OneToMany(type => ChatRoomMessageEntity, chatrmsg => chatrmsg.chatRoom)\n messages: ChatRoomMessageEntity[];\n\n @ManyToMany(type => UserEntity, user => user.activeChatRooms)\n activeUsers: UserEntity[];\n\n}\n```\n\n```text\n@Entity()\nexport class ChatRoomMessageEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column('varchar', {nullable: true})\n message: string;\n\n @CreateDateColumn()\n creationDate: Date;\n\n @ManyToOne(type => UserEntity, user => user.chatRoomMessages)\n fromUser: UserEntity;\n\n @ManyToOne(type => ChatRoomEntity, chatRoom => chatRoom.messages)\n chatRoom: ChatRoomEntity;\n\n}\n```\n\n```text\nentitymanager.findOne\n```\n\n```text\nmessages\n```\n\n```text\nfromUser\n```\n\n```text\nthis.entityManager.findOne(ChatRoomEntity, {\n where: {id: roomToJoin.id},\n relations: ['activeUsers', 'messages', 'messages.fromUser'],\n }).then(roomEntity => {\n...\n```\n\n```text\n'relation.subrelation'\n```\n\n```text\nrelations\n```\n\n```text\nrelations: ['relation1', 'relation2', 'relation2.subrelation1']\n```\n\n```js\nawait getRepository(UserEntity)\n .createQueryBuilder('user')\n .leftJoinAndSelect('user.profile', 'profile')\n .leftJoinAndSelect('profile.images', 'images')\n .getMany()\n```\n\n```js\nawait getRepository(UserEntity).find({ \n relations: ['profile', 'profile.images'] \n})\n```\n\n```js\nexport class User extends Model {\n @HasOneColumn({related: Profile})\n profile;\n}\nexport class Profile extends Model {\n @HasOneColumn({related: Image})\n image;\n}\nexport class Image extends Model {\n name;\n}\n```\n\n```js\nUser.createQuery().with('profile.image').get()\n```\n\n```js\nconst user = await User.createQuery().first();\nconst image await (await user.profile).image\n```\n\n```text\nwith\n```\n\n```text\nconst users = await userRepository.find({\n where: { /* conditions */ },\n relations: { /* relations */ }\n})\n\n// users[0] if you want a first row\n```\n\n```text\nfindOne\n```\n\n```text\nfindOneBy\n```\n\n```text\nfind\n```\n\n```text\nreturn await brandRepo.findAndCount({\n order: { updated_at: \"desc\" },\n skip,\n take: limit,\n relations: {\n products: {\n sizes: true,\n brands: true,\n },\n },\n});\n```\n\n```text\nthis.entityManager.findOne(ChatRoomEntity, {\n where: {id: roomToJoin.id},\n relations: ['activeUsers', 'messages', 'messages.fromUser'],\n loadEagerRelations: true,\n }).then(roomEntity => {\n...\n```\n\n```text\nloadEagerRelations: true\n```\n\n========================================\n\nComments:\n- i have got issue when i remove the entity with fetched relation, please read this one its very much related stackoverflow.com/questions/74302343/…\n- There can be performance issues with that approach. I've built my projects api using it, but it ended up crushing my app on every request. Read more here. People in comments are suggesting to populate relations by separate queries.\n- sorry man could you link us to where they said they were deprecating findOne?","metadata":{"transformedAt":"2026-08-18T18:33:44.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":295,"estimatedTokens":1488}}15{"id":"stack-62696628","source":"stackoverflow","questionId":62696628,"title":"How can I create columns with type Date and type DateTime in nestjs with typeORM?","tags":["mysql","date","orm","nestjs","typeorm"],"text":"Title: How can I create columns with type Date and type DateTime in nestjs with typeORM?\nTags: mysql, date, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am new with nestjs. How can I set columns that accepts Date format and dateTime format?\n\nNot in both cases, the columns are two differents column, one accept Date and other dateTime.\n\n========================================\n\nTop Answer:\nHow about ?\n\n```\n@CreateDateColumn()\ncreated_at: Date;\n \n@UpdateDateColumn()\nupdated_at: Date;\n```\n\nEDIT\n\nYou can find more info here\n\n========================================\n\nCode:\n```text\n@Column({ type: 'date' })\ndate_only: string;\n\n@Column({ type: 'timestamptz' }) // Recommended\ndate_time_with_timezone: Date;\n\n@Column({ type: 'timestamp' }) // Not recommended\ndate_time_without_timezone: Date;\n```\n\n```text\n@CreateDateColumn()\ncreated_at: Date; // Creation date\n\n@UpdateDateColumn()\nupdated_at: Date; // Last updated date\n\n@DeleteDateColumn()\ndeleted_at: Date; // Deletion date\n```\n\n```text\ndate_only\n```\n\n```text\n@CreateDateColumn()\n```\n\n```text\n@UpdateDateColumn()\n```\n\n```text\n@DeleteDateColumn()\n```\n\n```text\n@CreateDateColumn()\ncreated_at: Date;\n \n@UpdateDateColumn()\nupdated_at: Date;\n```\n\n```js\n/**\n * Start DateTime\n */\n @Column({\n type: 'datetime',\n default: () => 'NOW()',\n })\n @Index()\n start: string;\n\n /**\n * End DateTime\n */\n @Column({\n type: 'datetime',\n nullable: true,\n })\n @Index()\n end: string;\n```\n\n```text\n@CreateDateColumn()\n```\n\n```text\n@UpdateDateColumn()\n```\n\n```text\n@CreateDateColumn({ name: 'created_at'})\ncreatedAt: Date;\n\n@UpdateDateColumn({ name: 'updated_at' })\nupdatedAt: Date;\n\n@DeleteDateColumn({ name: 'deleted_at' })\ndeletedAt: Date;\n```\n\n```text\nclass SomeEntity {\n\n @Column({\n name: 'created_at',\n type: 'timestamptz',\n })\n createdAt?: Date;\n\n @Column({\n name: 'updated_at',\n type: 'timestamptz',\n })\n updatedAt?: Date;\n\n @BeforeInsert()\n protected setCreatedAt(): void {\n this.createdAt = new Date();\n }\n\n @BeforeUpdate()\n protected setUpdatedAt(): void {\n this.updatedAt = new Date();\n }\n}\n```\n\n========================================\n\nComments:\n- This answer is not correct. The type returned by typeorm for `type: 'date'` is a string - not a date object with the time set to 0. See github.com/typeorm/typeorm/issues/2176\n- @sarfata I've updated my answer. Let me know what you think!\n- @CarloCorradini awesome! I like that you clearly recommend `timestamptz` too ;)\n- would timestamp be ok when using mysql? as timestamptz is not supported?\n- Ok, but how to use \"timestamptz\" with GraphQL? What should I use inside ObjectType and InputType to fix the issue with the wrong DateTime types?\n- @EugeneZalivadnyi I use GraphQL Scalars library with a date/time scalar mapping. E.g. `GraphQLTimestamp` for UNIX epoch or `GraphQLDateTime` for UTC. You decide what best suits your needs since the input given to the scalar is always a `Date` instance (`timestamptz`).\n- @CarloCorradini any reason why \"timestamptz\" is recommended over \"timestamp\"?\n- @bilard See stackoverflow.com/a/22925669/6676781\n- Anyone who comes here and doesn't find how to include the columns stackoverflow.com/questions/64941148/…\n- This should be the correct answer, simple and handled automatically by typeorm on save.\n- I don't believe this should be the correct answer, or upvoted as it is. There are more uses for timestamp columns than just created_at and updated_at values\n- @Eazash that's why I provided a link to the rest of the docs :D\n- Does this mean that `start` and `end` are of type `string` and not `Date`?\n- No, they are `type: 'datetime'`\n- Yes, that is w.r.t MySQL. I wanted to know about how they would appear in JS.\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:44.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":162,"estimatedTokens":1004}}16{"id":"stack-64635617","source":"stackoverflow","questionId":64635617,"title":"How to set a nullable database field to NULL with typeorm?","tags":["typescript","postgresql","express","typeorm"],"text":"Title: How to set a nullable database field to NULL with typeorm?\nTags: typescript, postgresql, express, typeorm\nSource: Stack Overflow\n\nQuestion:\nThis seems like such a simple question to answer, but finding an answer for this seems impossible.\n\nI am building a password reset feature for a backend application with Express and Typescript. I am using Postgres for the database and Typeorm for data manipulation. I have a *User* entity with these two columns in my database:\n\n```\n@Column({\n unique: true,\n nullable: true,\n})\nresetPasswordToken!: string;\n\n@Column({ nullable: true, type: 'timestamp with time zone' })\nresetPasswordExpiresAt!: Date;\n```\n\nWhen a user requests a password reset token the *resetPasswordToken* and *resetPasswordExpiresAt* fields get both filled with the desired values. With the token that was sent to the user's e-mail address, the user can reset his/her password. After the user's password is reset, I want to clear these two fields by setting them to *null*:\n\n```\nuser.resetPasswordToken = null;\nuser.resetPasswordExpiresAt = null;\nuser.save()\n```\n\nBut if I do this Typescript complains about the two lines where I assign the *null* value:\n\nType 'null' is not assignable to type 'string'.\n\nand\n\nType 'null' is not assignable to type 'Date'.\n\nIf I change the columns in my entity to accept *null* like below, the errors disappear:\n\n```\nresetPasswordToken!: string | null;\n...\nresetPasswordExpiresAt!: Date | null;\n```\n\nBut when I start my Express application I get the following error when Typeorm tries to connect to my database:\n\nData type \"Object\" in \"User.resetPasswordToken\" is not supported by \"postgres\" database.\n\n \n\nHow do I set these fields to *null*?\n\n========================================\n\nTop Answer:\nThe accepted answer is not exactly correct. Default typeorm conversion from string type is \"varchar\" on MySQL DB. So if you use `type: \"text\"` it will define the column incorrectly. If you want to make it compatible with default behavior you should use typescript types like this\n\n```\n@Column({\n type: String,\n unique: true,\n nullable: true,\n})\nresetPasswordToken!: string | null;\n```\n\n========================================\n\nCode:\n```text\n@Column({\n unique: true,\n nullable: true,\n})\nresetPasswordToken!: string;\n\n@Column({ nullable: true, type: 'timestamp with time zone' })\nresetPasswordExpiresAt!: Date;\n```\n\n```text\nuser.resetPasswordToken = null;\nuser.resetPasswordExpiresAt = null;\nuser.save()\n```\n\n```text\nresetPasswordToken!: string | null;\n...\nresetPasswordExpiresAt!: Date | null;\n```\n\n```text\n@Column({\n unique: true,\n nullable: true,\n})\nresetPasswordToken!: string;\n```\n\n```text\nresetPasswordToken!: string | null;\n```\n\n```text\n@Column({\n type: 'text',\n unique: true,\n nullable: true,\n})\nresetPasswordToken!: string;\n```\n\n```text\n{\n name: \"tag_id\",\n type: \"varchar\",\n isNullable: true\n},\n```\n\n```js\n@Column({\n type: String,\n unique: true,\n nullable: true,\n})\nresetPasswordToken!: string | null;\n```\n\n```text\ntype: \"text\"\n```\n\n```js\n@Column('text', {\n unique: true,\n nullable: true,\n})\nresetPasswordToken!: string;\n```\n\n```text\n@Column('text', {\n unique: true,\n nullable: true,\n})\nresetPasswordToken: string;\n\n//user.resetPasswordToken = null\n\nuser.save()\n```\n\n```text\nDate\n```\n\n```text\nnull\n```\n\n```text\nnullable:true\n```\n\n```text\n@Column()\n```\n\n========================================\n\nComments:\n- what's the version of ts-node you use? check here: github.com/TypeStrong/ts-node/issues/569\n- @Mahdi I am using the latest version (9.0.0) of ts-node. The solution in the link you sent me did not work for me.\n- Your question is discussed and answered here github.com/typeorm/typeorm/issues/2567\n- can you type `resetPasswordToken` as `string | null` now?\n- @superJustin, after adding `type: 'text'` to the column decorator you can add `string | null` for type checking.","metadata":{"transformedAt":"2026-08-18T18:33:44.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":178,"estimatedTokens":970}}17{"id":"stack-51198817","source":"stackoverflow","questionId":51198817,"title":"TypeORM how to seed database","tags":["typeorm"],"text":"Title: TypeORM how to seed database\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI am running my Node JS backend using typeorm ORM.\n\nComing from Entity Framework, it was very easy to seed the db with a few lines such as\n\n```\nDatabase.SetInitializer(new DbInitializer());\n```\n\nWhere the DbInitializer class would contain all the seeding info.\n\nIs there a similar approach to seed the database in TypeOrm?\nIf not, what is the recommended way of doing it?\n\n1) Create a new migration with the data insertion statements?\n2) Create a task where you instantiate and save entities?\n\n========================================\n\nTop Answer:\nUnfortunately, there is no officially released solution from TypeORM (at the time this answer was being published).\n\nBut there is a nice workaround we can use:\n\ncreate another connection inside `ormconfig.js` file and specify another\nfolder for \"migrations\" - in fact our **seeds**\n\n- generate and run your seeds with `-c `. That's it!\n\nSample **ormconfig.js**:\n\n```\nmodule.exports = [\n {\n ...,\n migrations: [\n 'src/migrations/*.ts'\n ],\n cli: {\n migrationsDir: 'src/migrations',\n }\n },\n {\n name: 'seed',\n ...,\n migrations: [\n 'src/seeds/*.ts'\n ],\n cli: {\n migrationsDir: 'src/seeds',\n }\n }\n]\n```\n\nSample **package.json**:\n\n```\n{\n ...\n scripts: {\n \"seed:generate\": \"ts-node typeorm migration:generate -c seed -n \",\n \"seed:run\": \"ts-node typeorm migration:run -c seed\",\n \"seed:revert\": \"ts-node typeorm migration:revert -c seed\",\n },\n ...\n}\n```\n\n========================================\n\nCode:\n```text\nDatabase.SetInitializer(new DbInitializer());\n```\n\n```text\n0-Seed\n```\n\n```text\nafter_create\n```\n\n```js\nmodule.exports = [\n {\n ...,\n migrations: [\n 'src/migrations/*.ts'\n ],\n cli: {\n migrationsDir: 'src/migrations',\n }\n },\n {\n name: 'seed',\n ...,\n migrations: [\n 'src/seeds/*.ts'\n ],\n cli: {\n migrationsDir: 'src/seeds',\n }\n }\n]\n```\n\n```js\n{\n ...\n scripts: {\n \"seed:generate\": \"ts-node typeorm migration:generate -c seed -n \",\n \"seed:run\": \"ts-node typeorm migration:run -c seed\",\n \"seed:revert\": \"ts-node typeorm migration:revert -c seed\",\n },\n ...\n}\n```\n\n```text\normconfig.js\n```\n\n```text\n-c <connection name>\n```\n\n```ts\n// file: src/seeding/SeedingModule.ts\n\n@Module({})\nexport class SeedingModule implements NestModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(SeedingMiddleware)\n .forRoutes('*')\n }\n}\n```\n\n```ts\n// file: src/seeding/SeedingMiddleware.ts\nimport { Injectable, NestMiddleware } from '@nestjs/common';\nimport { Request, Response } from 'express';\nimport { EntityManager } from 'typeorm';\nimport { SeedingLogEntry } from './entities/SeedingLogEntry.entity';\n\n@Injectable()\nexport class SeedingMiddleware implements NestMiddleware {\n\n // to avoid roundtrips to db we store the info about whether\n // the seeding has been completed as boolean flag in the middleware\n // we use a promise to avoid concurrency cases. Concurrency cases may\n // occur if other requests also trigger a seeding while it has already\n // been started by the first request. The promise can be used by other\n // requests to wait for the seeding to finish.\n private isSeedingComplete: Promise<boolean>;\n\n constructor(\n private readonly entityManager: EntityManager,\n ) {}\n\n async use(req: Request, res: Response, next: Function) {\n\n if (await this.isSeedingComplete) {\n // seeding has already taken place,\n // we can short-circuit to the next middleware\n return next();\n }\n\n this.isSeedingComplete = (async () => {\n // for example you start with an initial seeding entry called 'initial-seeding'\n // on 2019-06-27. if 'initial-seeding' already exists in db, then this\n // part is skipped\n if (!await this.entityManager.findOne(SeedingLogEntry, { id: 'initial-seeding' })) {\n await this.entityManager.transaction(async transactionalEntityManager => {\n await transactionalEntityManager.save(User, initialUsers);\n await transactionalEntityManager.save(Role, initialRoles);\n // persist in db that 'initial-seeding' is complete\n await transactionalEntityManager.save(new SeedingLogEntry('initial-seeding'));\n });\n }\n\n // now a month later on 2019-07-25 you add another seeding\n // entry called 'another-seeding-round' since you want to initialize\n // entities that you just created a month later\n // since 'initial-seeding' already exists it is skipped but 'another-seeding-round'\n // will be executed now.\n if (!await this.entityManager.findOne(SeedingLogEntry, { id: 'another-seeding-round' })) {\n await this.entityManager.transaction(async transactionalEntityManager => {\n await transactionalEntityManager.save(MyNewEntity, initalSeedingForNewEntity);\n // persist in db that 'another-seeding-round' is complete\n await transactionalEntityManager.save(new SeedingLogEntry('another-seeding-round'));\n });\n }\n\n return true;\n })();\n\n await this.isSeedingComplete;\n\n next();\n }\n}\n```\n\n```ts\n// file: src/seeding/entities/Seeding.entity.ts\n\nimport { Entity, PrimaryColumn, CreateDateColumn } from 'typeorm';\n\n@Entity()\nexport class Seeding {\n\n @PrimaryColumn()\n public id: string;\n\n @CreateDateColumn()\n creationDate: Date;\n\n constructor(id?: string) {\n this.id = id;\n }\n}\n```\n\n```text\nTypeOrmModule.forRoot\n```\n\n```text\nOnApplicationBootstrap\n```\n\n```text\nonApplicationBootstrap\n```\n\n```text\n// testSeed.ts\n\nimport { ConnectionOptions, createConnection, QueryRunner } from \"typeorm\";\n\nimport { config } from \"../config\";\n\nimport { DevSeed } from \"./DevSeed\";\n\ncreateConnection(config.typeOrmConfig as ConnectionOptions).then(async connection => {\n let queryRunner = connection.createQueryRunner(\"master\");\n\n // runs all seed SQL commands in this function.\n await DevSeed(queryRunner);\n\n await queryRunner.release();\n return connection.close();\n});\n```\n\n```text\nmigration:run\n```\n\n```text\nnode ./dist/path/to/testSeed.js\n```\n\n```js\nimport { MigrationInterface, QueryRunner } from 'typeorm';\nimport * as path from 'path';\nimport * as fs from 'fs';\n\nlet insertPermissionQueries = fs\n .readFileSync(path.resolve(__dirname, '../../scripts/sql/insert.sql'))\n .toString()\n .replace(/(\\r\\n|\\n|\\r)/gm, ' ') // remove newlines\n .replace(/\\s+/g, ' '); // excess white space\n\nexport class init1591103087130 implements MigrationInterface {\n name = 'init1591103087130';\n\n public async up(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(\n `CREATE TABLE \"public\".\"RoleTemp\" (\"idx\" uuid NOT NULL DEFAULT uuid_generate_v4(), \"name\" text, \"created_on\" TIMESTAMP DEFAULT now(), \"is_active\" boolean DEFAULT true, \"role_type\" text, \"created_by\" uuid NOT NULL, \"status\" text, \"alias\" text, \"operation\" text, \"rejection_reason\" text, \"id\" SERIAL NOT NULL, \"is_obsolete\" boolean NOT NULL DEFAULT false, \"modified_on\" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \"role_id\" integer, CONSTRAINT \"UQ_835baad60041a3413f9ef95bc07\" UNIQUE (\"idx\"), CONSTRAINT \"PK_a76dd0012be252eefbdd4a2a589\" PRIMARY KEY (\"id\"))`,\n );\n await queryRunner.query(\n `CREATE UNIQUE INDEX \"RoleTemp_idx_key\" ON \"public\".\"RoleTemp\" (\"idx\") `,\n );\n await queryRunner.query(\n `CREATE TABLE \"public\".\"PermissionRoleTemp\" (\"idx\" uuid NOT NULL DEFAULT uuid_generate_v4(), \"created_on\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"permission_base_name\" text, \"id\" SERIAL NOT NULL, \"is_obsolete\" boolean NOT NULL DEFAULT false, \"modified_on\" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \"role_id\" integer NOT NULL, \"permission_id\" integer NOT NULL, CONSTRAINT \"PK_c1f2648a18ac911e096f08c187d\" PRIMARY KEY (\"id\"))`,\n );\n await queryRunner.query(\n `CREATE TABLE \"public\".\"Permission\" (\"idx\" uuid NOT NULL DEFAULT uuid_generate_v4(), \"base_name\" text NOT NULL, \"url\" text NOT NULL, \"method\" text NOT NULL, \"created_on\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"is_active\" boolean NOT NULL DEFAULT true, \"permission_type\" text, \"alias\" text NOT NULL, \"id\" SERIAL NOT NULL, \"is_obsolete\" boolean NOT NULL DEFAULT false, \"modified_on\" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, CONSTRAINT \"PK_28657fa560adca66b359c18b952\" PRIMARY KEY (\"id\"))`,\n );\n await queryRunner.query(\n `CREATE TABLE \"public\".\"PermissionRole\" (\"idx\" uuid NOT NULL DEFAULT uuid_generate_v4(), \"created_on\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"is_active\" boolean NOT NULL DEFAULT true, \"permission_base_name\" text NOT NULL, \"id\" SERIAL NOT NULL, \"is_obsolete\" boolean NOT NULL DEFAULT false, \"modified_on\" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \"role_id\" integer NOT NULL, \"permission_id\" integer NOT NULL, CONSTRAINT \"PK_b5e2271c229f65f17ee93677a0f\" PRIMARY KEY (\"id\"))`,\n );\n await queryRunner.query(\n `CREATE TABLE \"public\".\"UserRole\" (\"idx\" uuid NOT NULL DEFAULT uuid_generate_v4(), \"created_on\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"is_active\" boolean NOT NULL DEFAULT true, \"id\" SERIAL NOT NULL, \"is_obsolete\" boolean NOT NULL DEFAULT false, \"modified_on\" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \"role_id\" integer NOT NULL, \"company_user_id\" integer NOT NULL, CONSTRAINT \"PK_431fc1ec3d46ac513ef3701604e\" PRIMARY KEY (\"id\"))`,\n );\n await queryRunner.query(\n `CREATE TABLE \"public\".\"UsersTemp\" (\"idx\" uuid DEFAULT uuid_generate_v1(), \"username\" text, \"first_name\" text, \"middle_name\" text, \"last_name\" text, \"password\" text, \"email\" text, \"address\" text, \"phone_number\" text, \"phone_ext\" text, \"company_idx\" uuid, \"is_superadmin\" boolean NOT NULL DEFAULT false, \"operation\" text, \"created_by\" text, \"status\" text, \"rejection_reason\" text, \"created_on\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"is_active\" boolean NOT NULL DEFAULT true, \"id\" SERIAL NOT NULL, \"is_obsolete\" boolean NOT NULL DEFAULT false, \"modified_on\" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \"role_id\" integer, \"user_id\" integer, CONSTRAINT \"PK_9d3fbcec3cc0b054324f93da038\" PRIMARY KEY (\"id\"))`,\n );\n await queryRunner.query(\n `CREATE TABLE \"public\".\"Role\" (\"idx\" uuid NOT NULL DEFAULT uuid_generate_v4(), \"name\" text NOT NULL, \"alias\" text NOT NULL, \"created_on\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"is_active\" boolean NOT NULL DEFAULT true, \"role_type\" text, \"created_by\" uuid NOT NULL, \"id\" SERIAL NOT NULL, \"is_obsolete\" boolean NOT NULL DEFAULT false, \"modified_on\" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, CONSTRAINT \"UQ_c9a53325a7642edb5f9bd44f5aa\" UNIQUE (\"idx\"), CONSTRAINT \"PK_422113329ddec949e76c7943c56\" PRIMARY KEY (\"id\"))`,\n );\n await queryRunner.query(\n `CREATE UNIQUE INDEX \"Role_idx_key\" ON \"public\".\"Role\" (\"idx\") `,\n );\n await queryRunner.query(\n `CREATE TABLE \"public\".\"Users\" (\"idx\" uuid NOT NULL DEFAULT uuid_generate_v4(), \"username\" text NOT NULL, \"first_name\" text NOT NULL, \"middle_name\" text, \"last_name\" text NOT NULL, \"password\" text NOT NULL, \"email\" text, \"address\" text, \"phone_number\" text, \"phone_ext\" text, \"company_idx\" uuid, \"created_on\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"is_active\" boolean NOT NULL DEFAULT true, \"is_superadmin\" boolean NOT NULL DEFAULT false, \"id\" SERIAL NOT NULL, \"is_obsolete\" boolean NOT NULL DEFAULT false, \"modified_on\" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \"role_id\" integer NOT NULL, CONSTRAINT \"PK_ac3c96e3c912cbda773b7c7edc9\" PRIMARY KEY (\"id\"))`,\n );\n await queryRunner.query(\n `CREATE TABLE \"public\".\"CompanyUser\" (\"id\" SERIAL NOT NULL, \"is_obsolete\" boolean NOT NULL DEFAULT false, \"modified_on\" TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \"idx\" uuid NOT NULL DEFAULT uuid_generate_v4(), \"company_idx\" uuid, \"created_on\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \"is_active\" boolean NOT NULL DEFAULT true, \"user_id\" integer, CONSTRAINT \"PK_4a915d69bf079a8e5dd10784cc3\" PRIMARY KEY (\"id\"))`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"RoleTemp\" ADD CONSTRAINT \"FK_d304588d17c9349ca6e7ebee5d3\" FOREIGN KEY (\"role_id\") REFERENCES \"public\".\"Role\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"PermissionRoleTemp\" ADD CONSTRAINT \"FK_7e7cdde853500f56b3db43fc258\" FOREIGN KEY (\"role_id\") REFERENCES \"public\".\"RoleTemp\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"PermissionRoleTemp\" ADD CONSTRAINT \"FK_0068d3de1c59050561d35f17544\" FOREIGN KEY (\"permission_id\") REFERENCES \"public\".\"Permission\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"PermissionRole\" ADD CONSTRAINT \"FK_5b57492441a568bc7562fbbaa5b\" FOREIGN KEY (\"role_id\") REFERENCES \"public\".\"Role\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"PermissionRole\" ADD CONSTRAINT \"FK_1951a810af06342fcd4530ec61c\" FOREIGN KEY (\"permission_id\") REFERENCES \"public\".\"Permission\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"UserRole\" ADD CONSTRAINT \"FK_fb09d73b0dd011be81a272e1efa\" FOREIGN KEY (\"role_id\") REFERENCES \"public\".\"Role\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"UserRole\" ADD CONSTRAINT \"FK_b221977a41587e58d7c58e16db0\" FOREIGN KEY (\"company_user_id\") REFERENCES \"public\".\"CompanyUser\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"UsersTemp\" ADD CONSTRAINT \"FK_6d74dfaddaa94e1bba0c8c12a2f\" FOREIGN KEY (\"role_id\") REFERENCES \"public\".\"Role\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"UsersTemp\" ADD CONSTRAINT \"FK_e5b2930fe35042dab17945bb131\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"Users\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"Users\" ADD CONSTRAINT \"FK_34be125e29cee0e71d58456aed7\" FOREIGN KEY (\"role_id\") REFERENCES \"public\".\"Role\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"CompanyUser\" ADD CONSTRAINT \"FK_1354e3e408b5ffdebe476a6fbd2\" FOREIGN KEY (\"user_id\") REFERENCES \"public\".\"Users\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`,\n );\n await queryRunner.query(insertPermissionQueries);\n }\n\n public async down(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(\n `ALTER TABLE \"public\".\"CompanyUser\" DROP CONSTRAINT \"FK_1354e3e408b5ffdebe476a6fbd2\"`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"Users\" DROP CONSTRAINT \"FK_34be125e29cee0e71d58456aed7\"`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"UsersTemp\" DROP CONSTRAINT \"FK_e5b2930fe35042dab17945bb131\"`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"UsersTemp\" DROP CONSTRAINT \"FK_6d74dfaddaa94e1bba0c8c12a2f\"`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"UserRole\" DROP CONSTRAINT \"FK_b221977a41587e58d7c58e16db0\"`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"UserRole\" DROP CONSTRAINT \"FK_fb09d73b0dd011be81a272e1efa\"`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"PermissionRole\" DROP CONSTRAINT \"FK_1951a810af06342fcd4530ec61c\"`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"PermissionRole\" DROP CONSTRAINT \"FK_5b57492441a568bc7562fbbaa5b\"`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"PermissionRoleTemp\" DROP CONSTRAINT \"FK_0068d3de1c59050561d35f17544\"`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"PermissionRoleTemp\" DROP CONSTRAINT \"FK_7e7cdde853500f56b3db43fc258\"`,\n );\n await queryRunner.query(\n `ALTER TABLE \"public\".\"RoleTemp\" DROP CONSTRAINT \"FK_d304588d17c9349ca6e7ebee5d3\"`,\n );\n await queryRunner.query(`DROP TABLE \"public\".\"CompanyUser\"`);\n await queryRunner.query(`DROP TABLE \"public\".\"Users\"`);\n await queryRunner.query(`DROP INDEX \"public\".\"Role_idx_key\"`);\n await queryRunner.query(`DROP TABLE \"public\".\"Role\"`);\n await queryRunner.query(`DROP TABLE \"public\".\"UsersTemp\"`);\n await queryRunner.query(`DROP TABLE \"public\".\"UserRole\"`);\n await queryRunner.query(`DROP TABLE \"public\".\"PermissionRole\"`);\n await queryRunner.query(`DROP TABLE \"public\".\"Permission\"`);\n await queryRunner.query(`DROP TABLE \"public\".\"PermissionRoleTemp\"`);\n await queryRunner.query(`DROP INDEX \"public\".\"RoleTemp_idx_key\"`);\n await queryRunner.query(`DROP TABLE \"public\".\"RoleTemp\"`);\n }\n}\n```\n\n```js\nimport { BootstrapConsole } from 'nestjs-console';\nimport { AppModule } from 'src/server/app/app.module';\n\nconst bootstrap = new BootstrapConsole({\n module: AppModule,\n useDecorators: true,\n});\nbootstrap.init().then(async (app) => {\n try {\n await app.init();\n await bootstrap.boot();\n app.close();\n\n process.exit(0);\n } catch (e) {\n app.close();\n\n process.exit(1);\n }\n});\n```\n\n```js\nimport { Inject } from '@nestjs/common';\nimport { Console, Command } from 'nestjs-console';\nimport { UsersService } from 'src/users/users.service';\n\n@Console()\nexport class SeedService {\n constructor(\n @Inject(UsersService) private usersService: UsersService,\n ) {}\n\n @Command({\n command: 'seed',\n description: 'Seed DB',\n })\n async seed(): Promise<void> {\n await this.seedUsers();\n }\n\n async seedUsers() {\n await this.usersService.create({ name: 'Joe' });\n }\n}\n```\n\n```js\n{\n \"scripts\": {\n \"console\": \"ts-node -r tsconfig-paths/register src/console.ts\",\n```\n\n```text\nnestjs-console\n```\n\n```text\nseed\n```\n\n```text\nyarn console seed\n```\n\n```text\nsrc/console.ts\n```\n\n```text\nsrc/console/seed.service.ts\n```\n\n```text\npackage.json\n```\n\n```js\nimport { Injectable, Logger } from '@nestjs/common';\n import { EntityManager } from 'typeorm';\n\n import { UserEntity} from 'src/entities/user.entity';\n import { RoleEntity } from 'src/entities/role.entity';\n\n import { userSeeds } from 'src/seeds/user.seeds';\n import { roleSeeds } from 'src/seeds/role.seeds';\n\n @Injectable()\n export class SeedingService {\n constructor(\n private readonly entityManager: EntityManager,\n ) {}\n\n async seed(): Promise<void> {\n\n // Replace with your own seeds\n await Promise.all([\n this.entityManager.save(UserEntity, userSeeds),\n this.entityManager.save(RoleEntity, roleSeeds),\n ]);\n\n }\n }\n```\n\n```js\nimport { Module, OnApplicationBootstrap } from '@nestjs/common'\n import { TypeOrmModule } from '@nestjs/typeorm';\n import { getConnectionOptions } from 'typeorm';\n\n @Module({\n imports: [\n TypeOrmModule.forRootAsync({\n useFactory: async () =>\n Object.assign(await getConnectionOptions(), {\n autoLoadEntities: true,\n }),\n }),\n TypeOrmModule.forFeature([\n CompanyOrmEntity,\n ProductOrmEntity,\n ]),\n ],\n providers: [\n SeedingService,\n ...\n ],\n ...\n })\n export class AppModule implements OnApplicationBootstrap {\n constructor(\n private readonly seedingService: SeedingService,\n ) {}\n\n async onApplicationBootstrap(): Promise<void> {\n await this.seedingService.seed();\n }\n }\n```\n\n```text\nOnApplicationBootstrap\n```\n\n```text\nsrc/seeding.service.ts\n```\n\n```text\nsrc/app.module.ts\n```\n\n```text\n// file: src/seeding/SeedingMiddleware.ts\n\nimport { Injectable, NestMiddleware } from '@nestjs/common';\nimport { Request, Response } from 'express';\nimport { TxnCategory } from 'src/txn-categories/entities/txn-category.entity';\nimport { init_categories } from 'src/txn-categories/entities/txn_cat-seed-data';\nimport { init_services } from 'src/txn-services/entities/txn-serv-seed-data';\nimport { TxnService } from 'src/txn-services/entities/txn-service.entity';\nimport { EntityManager } from 'typeorm';\nimport { Seeding } from './entities/seeding.entity';\n\n@Injectable()\nexport class SeedingMiddleware implements NestMiddleware {\n // to avoid roundtrips to db we store the info about whether\n // the seeding has been completed as boolean flag in the middleware\n // we use a promise to avoid concurrency cases. Concurrency cases may\n // occur if other requests also trigger a seeding while it has already\n // been started by the first request. The promise can be used by other\n // requests to wait for the seeding to finish.\n private isSeedingComplete: Promise<boolean>;\n\n constructor(private readonly entityManager: EntityManager) {}\n\n async use(req: Request, res: Response, next: any) {\n if (await this.isSeedingComplete) {\n // seeding has already taken place,\n // we can short-circuit to the next middleware\n return next();\n }\n\n this.isSeedingComplete = (async () => {\n // for example you start with an initial seeding entry called 'initial-seeding'\n // if 'init-txn-cats' and 'init-txn-serv' already exists in db, then this\n // part is skipped\n \n // MODIFIED\n if (\n !(await this.entityManager.findOne(Seeding, {\n id: 'init-txn-cats',\n }))\n ) {\n await this.entityManager.transaction(\n async (transactionalEntityManager) => {\n for (let i = 0; i < init_categories.length; i++) {\n await transactionalEntityManager.save(\n TxnCategory,\n init_categories[i],\n );\n }\n await transactionalEntityManager.save(new Seeding('init-txn-cats'));\n },\n );\n }\n\n // MODIFIED\n if (\n !(await this.entityManager.findOne(Seeding, {\n id: 'init-txn-serv',\n }))\n ) {\n await this.entityManager.transaction(\n async (transactionalEntityManager) => {\n for (let i = 0; i < init_services.length; i++) {\n await transactionalEntityManager.save(\n TxnService,\n init_services[i],\n );\n }\n await transactionalEntityManager.save(new Seeding('init-txn-serv'));\n },\n );\n }\n\n return true;\n })();\n\n await this.isSeedingComplete;\n next();\n }\n}\n```\n\n```text\n// file: src/txn-categories/entities/txn_cat-seed-data.ts\n\nexport const init_categories = [\n {\n id: 1,\n category_name: 'name 1',\n category_code: 'cat_code_1',\n enabled: true,\n },\n {\n id: 2,\n category_name: 'name 2',\n category_code: 'cat_code_2',\n enabled: true,\n },\n {\n id: 3,\n category_name: 'name 3',\n category_code: 'cat_code_3',\n enabled: true,\n },\n\n// etc\n];\n```\n\n```text\n// file: src/seeding/SeedingModule.ts\n\n@Module({})\nexport class SeedingModule {\n configure(consumer: MiddlewareConsumer) {\n consumer\n .apply(SeedingMiddleware)\n .forRoutes('*')\n }\n}\n```\n\n```text\n// file: src/seeding/entities/Seeding.entity.ts\n\nimport { Entity, PrimaryColumn, CreateDateColumn } from 'typeorm';\n\n@Entity()\nexport class Seeding {\n\n @PrimaryColumn()\n public id: string;\n\n @CreateDateColumn()\n creationDate: Date;\n\n constructor(id?: string) {\n this.id = id;\n }\n}\n```\n\n```text\nimport { MigrationInterface, QueryRunner } from 'typeorm';\nconst tableName = 'foo';\nconst columnName = 'foo_column';\nconst features = ['foo_content_1', 'foo_content_2'];\n\nexport class seedIntoPermissionsTable1638518166717 implements MigrationInterface {\n public async up(queryRunner: QueryRunner): Promise<void> {\n await Promise.all(features.map((feature) => queryRunner.query(`INSERT INTO ${tableName} (${columnName}) VALUES ('${feature}')`)));\n }\n\n public async down(queryRunner: QueryRunner): Promise<void> {\n await Promise.all(features.map((feature) => queryRunner.query(`DELETE FROM ${tableName} WHERE ${columnName}='${feature}';`)));\n }\n}\n```\n\n```text\nimport { MigrationInterface, QueryRunner } from 'typeorm';\n \n export class <Class Name> implements MigrationInterface {\n\n public async up(queryRunner: QueryRunner): Promise<void> {\n\n await queryRunner.connection\n .createQueryBuilder()\n .insert()\n .into('table_name', ['columns_1','column_2',...])\n .values([\n {\n columns_1: value,\n \n },\n {\n column_2: value\n }\n ])\n .execute();\n }\n }\n```\n\n```text\n#!/usr/bin/bash\n\nDATA=\"\"\n\nCreateAccount() {\n curl --location 'http://localhost:3000/v1/accounts' \\\n --header 'Content-Type: application/json' \\\n --data \"$1\"\n echo\n}\nCreateMovement() {\n curl --location 'http://localhost:3000/v1/movements' \\\n --header 'Content-Type: application/json' \\\n --data \"$1\"\n echo\n}\n\nCreateAccount '{ \"name\": \"First Account Name\", \"type\": 1 }'\nCreateAccount '{ \"name\": \"Second account\", \"type\": 2 }'\n\nCreateMovement '{ \"destiny\": 1, value: 10 }\nCreateMovement '{ \"destiny\": 2, value: 10 }\nCreateMovement '{ \"origin\": 1, \"destiny\": 2, value: 2 }\n```\n\n```js\nimport { dataSource } from '#database/data-source';\n import { Country } from '#database/entities/countries.entity';\n import { OrderStatus } from '#database/entities/order-statuses.entity';\n import { countries } from '#database/seeders/countries.seed';\n import { orderStatuses } from '#database/seeders/order-statuses.seed';\n import { SeederFactory } from '#database/seeders/seeder-factory';\n \n const runSeeders = async () => {\n const initializedDataSource = await dataSource.initialize();\n \n const seederFactory = new SeederFactory({\n dataSource: initializedDataSource,\n resetSequence: true,\n });\n \n const countriesSeeder = seederFactory.createSeeder(Country);\n const orderStatusSeeder = seederFactory.createSeeder(OrderStatus);\n \n await countriesSeeder.seed(countries);\n await orderStatusSeeder.seed(orderStatuses);\n \n await initializedDataSource.destroy();\n };\n \n runSeeders();\n```\n\n```js\nimport { DataSource, EntityTarget, Repository } from 'typeorm';\nimport { SeederInterface } from './seeder.interface';\n\ninterface SeederOptions<T> {\n resetSequence?: boolean;\n dataSource: DataSource;\n entity: EntityTarget<T>;\n}\n\nclass Seeder<T> implements SeederInterface<T> {\n private shouldResetSequence: boolean;\n private dataSource: DataSource;\n private entity: EntityTarget<T>;\n\n constructor({ resetSequence = false, dataSource, entity }: SeederOptions<T>) {\n this.shouldResetSequence = resetSequence;\n this.dataSource = dataSource;\n this.entity = entity;\n }\n\n async seed(data: T[]): Promise<void> {\n const repository: Repository<T> = this.dataSource.getRepository(this.entity);\n\n if (this.shouldResetSequence) {\n await this.resetSequence();\n }\n\n await repository.save(data);\n }\n\n private async resetSequence(): Promise<void> {\n await this.dataSource.query(\n `ALTER SEQUENCE ${\n this.dataSource.getMetadata(this.entity).tableName\n }_id_seq RESTART;`\n );\n }\n}\n\nexport interface SeederFactoryOptions {\n resetSequence?: boolean;\n dataSource: DataSource;\n}\n\nexport class SeederFactory {\n private resetSequence: boolean;\n private dataSource: DataSource;\n\n constructor({ resetSequence = false, dataSource }: SeederFactoryOptions) {\n this.resetSequence = resetSequence;\n this.dataSource = dataSource;\n }\n\n createSeeder<T>(entity: EntityTarget<T>): Seeder<T> {\n const seeder = new Seeder({\n resetSequence: this.resetSequence,\n dataSource: this.dataSource,\n entity,\n });\n\n return seeder;\n }\n}\n```\n\n```js\n\"seed\": \"env-cmd ts-node -r tsconfig-paths/register src/database/run-seeders.ts\"\n```\n\n```text\nSeederFactory\n```\n\n```text\npackage.json\n```\n\n```text\nrun-seeders.ts\n```\n\n```text\nseeder-factory.ts\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- using typeorm cli you can create migrations, as described at github.com/typeorm/typeorm/blob/master/docs/migrations.md\n- i recently published an article on how you can seed DB. Please check it out: medium.com/@bansalsushil_34403/how-to-seed-typeorm-d9637a594‌​8cc\n- What about: github.com/w3tecch/typeorm-seeding#-introduction\n- How would this work if you change the table structure (ex: rename a column)? Do you force people to update the seed scripts? Did you add tests to ensure the db seeding doesn’t get messed up? Do you just delete the db and reseed periodically?\n- Where did you find information about the ormconfig.js file? I cant see this anywhere in the current (2025) documentation","metadata":{"transformedAt":"2026-08-18T18:33:44.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":46,"totalLines":894,"estimatedTokens":7271}}18{"id":"stack-53495716","source":"stackoverflow","questionId":53495716,"title":"Searching data older than a Date with typeORM","tags":["database","mongodb","postgresql","typeorm","typeorm-activerecord"],"text":"Title: Searching data older than a Date with typeORM\nTags: database, mongodb, postgresql, typeorm, typeorm-activerecord\nSource: Stack Overflow\n\nQuestion:\nI am executing a query to **Postgre DB** to fetch data older than a specific date.\n\nHere's my function \n\n```\nasync filesListToDelete(): Promise {\n return await this.fileRepository.find({\n where: { last_modified: { $lt: '2018-11-15 10:41:30.746877' } },\n });\n}\n```\n\nHere's how I defined my File entity:\n\n```\nexport class File {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ nullable: false })\n idFonc: number;\n\n @Column({ nullable: false })\n version: number;\n\n @Column('varchar', { length: 100, nullable: false })\n filename: string;\n\n @Column({ nullable: true })\n last_modified: Date;\n\n @Column({ nullable: false })\n device: boolean;\n\n @ManyToOne(type => Type, { nullable: false })\n @JoinColumn({ referencedColumnName: 'id' })\n type: Type;\n\n @OneToMany(type => FileDevice, filedevice => filedevice.file)\n fileDevice: FileDevice[];\n}\n```\n\nI get this error \n\n```\nQueryFailedError: invalid input syntax for type timestamp: \"{\"$lt\":\"2018-11-15 10:41:30.746877\"}\"\n```\n\n========================================\n\nTop Answer:\nAlso you can do this using `createQueryBuilder` as below:\n\n```\npublic async filesListToDelete(): Promise {\n let record = await this.fileRepository.createQueryBuilder('file')\n .where('file.last_modified > :start_at', { start_at: '2018-11-15 10:41:30.746877' })\n .getMany();\n\n return record\n }\n```\n\n========================================\n\nCode:\n```text\nasync filesListToDelete(): Promise<any> {\n return await this.fileRepository.find({\n where: { last_modified: { $lt: '2018-11-15 10:41:30.746877' } },\n });\n}\n```\n\n```text\nexport class File {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ nullable: false })\n idFonc: number;\n\n @Column({ nullable: false })\n version: number;\n\n @Column('varchar', { length: 100, nullable: false })\n filename: string;\n\n @Column({ nullable: true })\n last_modified: Date;\n\n @Column({ nullable: false })\n device: boolean;\n\n @ManyToOne(type => Type, { nullable: false })\n @JoinColumn({ referencedColumnName: 'id' })\n type: Type;\n\n @OneToMany(type => FileDevice, filedevice => filedevice.file)\n fileDevice: FileDevice[];\n}\n```\n\n```text\nQueryFailedError: invalid input syntax for type timestamp: \"{\"$lt\":\"2018-11-15 10:41:30.746877\"}\"\n```\n\n```text\nasync filesListToDelete(): Promise<any> {\n return await this.fileRepository.find({\n where: { \n last_modified: LessThan('2018-11-15 10:41:30.746877') },\n});}\n```\n\n```text\npublic async filesListToDelete(): Promise<any> {\n let record = await this.fileRepository.createQueryBuilder('file')\n .where('file.last_modified > :start_at', { start_at: '2018-11-15 10:41:30.746877' })\n .getMany();\n\n return record\n }\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\nasync filesListToDelete(): Promise<any> {\n return await this.fileRepository.find({\n where: { last_modified: LessThan('2018-11-15 10:41:30.746877') },\n });\n}\n```\n\n```text\npublic async filesListToDelete(): Promise<any> {\n let record = await this.fileRepository.createQueryBuilder('file')\n .where('file.last_modified < :start_at', { start_at: '2018-11-15 10:41:30.746877' })\n .getMany();\n\n return record\n}\n```\n\n```text\nOLDER\n```\n\n```text\nTypeORM\n```\n\n```text\nPostgreSQL\n```\n\n```text\n{\n userId: \"c2ba135e\",\n transactionNumber: \"1234\",\n timestampFrom: \"2023-11-15T10:30:35\",\n timestampTo: \"2023-11-15T10:30:35\",\n}\n```\n\n```text\nasync fetchDetails(userId, transactionNumber, timestampFrom, timestampTo): Promise<any> {\n try {\n const query = \"payment.userId = :userId AND payment.pgTxnNo = :transactionNumber AND payment.createdDateTime >= :timestampFrom AND payment.createdDateTime <= :timestampTo\";\n\n const params = {\n userId: \"c2ba135e-7dfc-4f2b-91bf-124d76754965\",\n transactionNumber: \"1234\",\n timestampFrom: \"2023-11-15T10:30:35\",\n timestampTo: \"2023-11-15T10:30:35\",\n }\n\n const [users, totalCount] = await this.paymentRepo\n .createQueryBuilder('payment')\n .select([\n 'payment.createdBy',\n 'payment.pgTxnAmt',\n ])\n .where(query)\n .setParameters(params)\n .getManyAndCount();\n return { users, totalCount };\n } catch (error) {\n console.log(error)\n }\n }\n```\n\n```text\n\"payment.userId = :userId AND payment.pgTxnNo = :transactionNumber AND payment.createdDateTime >= :timestampFrom AND payment.createdDateTime <= :timestampTo\"\n```\n\n========================================\n\nComments:\n- Apologies, aren't they looking for LessThan b/c they're looking for data OLDER than that date? (And MoreThan will return more recent data?)\n- This answer is wrong. If you need to get an older date, you should be looking for a date less than the current date. You should use LessThan","metadata":{"transformedAt":"2026-08-18T18:33:44.682Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":211,"estimatedTokens":1232}}19{"id":"stack-49794140","source":"stackoverflow","questionId":49794140,"title":"Connection \"default\" was not found with TypeORM","tags":["node.js","postgresql","typeorm","nestjs"],"text":"Title: Connection \"default\" was not found with TypeORM\nTags: node.js, postgresql, typeorm, nestjs\nSource: Stack Overflow\n\nQuestion:\nI use TypeORM with NestJS and I am not able to save properly an entity. \n\nThe connection creation works, postgres is running on 5432 port. Credentials are OK too. \n\nHowever when I need to save a resource with entity.save() I got :\n\n```\nConnection \"default\" was not found.\n\nError\n at new ConnectionNotFoundError (/.../ConnectionNotFoundError.ts:11:22)\n```\n\nI checked the source file of TypeORM ConnectionManager (https://github.com/typeorm/typeorm/blob/master/src/connection/ConnectionManager.ts) but it seems that the first time TypeORM creates connection it attributes \"default\" name if we don't provide one, which is the case for me.\n\nI setup TypeORM with TypeOrmModule as \n\n```\nTypeOrmModule.forRoot({\n type: config.db.type,\n host: config.db.host,\n port: config.db.port,\n username: config.db.user,\n password: config.db.password,\n database: config.db.database,\n entities: [\n __dirname + '/../../dtos/entities/*.entity.js',\n ]\n })\n```\n\nOf course my constants are correct. Any ideas ?\n\n========================================\n\nTop Answer:\nthe upvoted answer is not necessarily correct, if you not specify the connection name it will default to \"default\".\n\n```\nconst manager = getConnectionManager().get('your_orm_name');\nconst repository = manager.getRepository(Model);\n```\n\n========================================\n\nCode:\n```text\nConnection \"default\" was not found.\n\n\nError\n at new ConnectionNotFoundError (/.../ConnectionNotFoundError.ts:11:22)\n```\n\n```text\nTypeOrmModule.forRoot({\n type: config.db.type,\n host: config.db.host,\n port: config.db.port,\n username: config.db.user,\n password: config.db.password,\n database: config.db.database,\n entities: [\n __dirname + '/../../dtos/entities/*.entity.js',\n ]\n })\n```\n\n```text\nconst shopkeeperRepository = getRepository(Shopkeeper);\n```\n\n```text\ntypeORM\n```\n\n```text\n@Entity()\n```\n\n```text\nBaseEntity\n```\n\n```text\nconst manager = getConnectionManager().get('your_orm_name');\nconst repository = manager.getRepository<AModel>(Model);\n```\n\n```text\nexport const dbConfig = {\n name: 'myDB',\n ...\n}\n\nawait createConnection(dbConfig) // like this\n```\n\n```text\n@Service() // typedi\nexport class Service {\n constructor(\n // inject without name -> fallback to default\n @InjectRepository() private readonly repository\n ) {}\n}\n```\n\n```text\nname\n```\n\n```text\nmyDB\n```\n\n```text\ndefault\n```\n\n```text\nname\n```\n\n```text\ndefault\n```\n\n```text\ndefault\n```\n\n```text\nname\n```\n\n```text\nmyDB\n```\n\n```text\nInjectRepository\n```\n\n```text\n@InjectRepository('myDB')\n```\n\n```text\nconst router = Router();\n\nrouter.get(\"/\", async function (req: Request, res: Response) {\n // here we will have logic to return all users\n const userRepository = getRepository(User);\n const users = await userRepository.find();\n res.json(users);\n});\n\nrouter.get(\"/:id\", async function (req: Request, res: Response) {\n // here we will have logic to return user by id\n const userRepository = getRepository(User);\n const results = await userRepository.findOne(req.params.id);\n return res.send(results);\n});\n```\n\n```text\ngetRepository()\n```\n\n```text\ngetRepository()\n```\n\n```text\nconst userRepo = getConnection(process.env.NODE_ENV).getRepository(User)\n```\n\n```text\nuser.save()\n```\n\n```text\nuserRepo.save(user)\n```\n\n```text\nconst connectionOptions = await getConnectionOptions(process.env.NODE_ENV);\nawait createConnection({...connectionOptions, name:\"default\"});\n```\n\n```text\n[\n{\n \"name\" : \"development\",\n \"type\": \"USER\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"PASS\",\n \"database\": \"YOURDB\"\n},\n{\n \"name\" : \"test\",\n \"type\": \"USERTEST\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"PASSTEST\",\n \"database\": \"YOURDBTEST\"\n}\n]\n```\n\n```text\ngetConnectionOptions\n```\n\n```text\ngetConnectionOptions\n```\n\n```text\normconfig.json\n```\n\n```text\nconnectionOptions\n```\n\n```text\ncreateConnection\n```\n\n```text\nconnectionOptions\n```\n\n```text\nimport { Connection, ConnectionManager, ConnectionOptions, createConnection, getConnectionManager } from 'typeorm';\n\nexport class Database {\n private connectionManager: ConnectionManager;\n\n constructor() {\n this.connectionManager = getConnectionManager();\n }\n\n public async getConnection(name: string): Promise<Connection> {\n const CONNECTION_NAME: string = name;\n let connection: Connection;\n const hasConnection = this.connectionManager.has(CONNECTION_NAME);\n if (hasConnection) {\n connection = this.connectionManager.get(CONNECTION_NAME);\n if (!connection.isConnected) {\n connection = await connection.connect();\n }\n } else {\n\n const connectionOptions: ConnectionOptions = {\n name: 'default',\n type: 'mysql',\n host: 'localhost',\n port: 3306,\n username: 'root',\n password: 'password',\n database: 'DemoDb',\n synchronize: false,\n logging: true,\n entities: ['src/entities/**/*.js'],\n migrations: ['src/migration/**/*.js'],\n subscribers: ['src/subscriber/**/*.js'],\n };\n connection = await createConnection(connectionOptions);\n }\n return connection;\n }\n}\n```\n\n```text\nimport {User} from 'src/entities/User.ts';\n import {Album} from 'src/entities/Album.ts';\n import {Photos} from 'src/entities/Photos.ts';\n const connectionOptions: ConnectionOptions = {\n name: 'default',\n type: 'mysql',\n host: 'localhost',\n port: 3306,\n username: 'root',\n password: 'password',\n database: 'DemoDb',\n synchronize: false,\n logging: true,\n entities: [User, Album, Photos],\n migrations: ['src/migration/**/*.js'],\n subscribers: ['src/subscriber/**/*.js'],\n };\n```\n\n```text\nconst connectionName = 'default';\n const database = new Database();\n const dbConn: Connection = await database.getConnection(connectionName);\n const MspRepository = dbConn.getRepository(Msp);\n await MspRepository.delete(mspId);\n```\n\n```text\nDatabase\n```\n\n```text\nWindows\n```\n\n```text\nd:/apps/app-name/etc\n```\n\n```text\nD\n```\n\n```text\nD:/apps/app-name/etc\n```\n\n```text\nlerna\n```\n\n```text\nA\n```\n\n```text\nB\n```\n\n```text\nnode_modules\n```\n\n```text\nyarn install\n```\n\n```text\nnpm install\n```\n\n```text\nyarn.lock\n```\n\n```text\ntypeorm\n```\n\n```js\nimport { Connection, getConnectionManager, getConnectionOptions, \n createConnection, getConnection, QueryRunner } from 'typeorm';\n \n async init() {\n let connection: Connection;\n let queryRunner: QueryRunner;\n\n if (!getConnectionManager().has('default')) {\n const connectionOptions = await getConnectionOptions();\n connection = await createConnection(connectionOptions);\n } else {\n connection = getConnection();\n }\n\n queryRunner = connection.createQueryRunner(); \n }\n```\n\n```text\n.has()\n```\n\n```text\ngetConnectionManager()\n```\n\n```js\ncreateConnections([\n {\n name: 'default',\n type: 'mysql',\n host: 'localhost',\n port: 3306,\n username: 'root',\n password: 'root',\n database: 'users',\n entities: [`${__dirname}/entity/*{.js,.ts}`],\n synchronize: true,\n logging: true\n }\n]);\n```\n\n```js\nimport {getConnection} from \"typeorm\";\n\nconst db1Connection = getConnection(\"db1Connection\");\n// you can work with \"db1\" database now...\n```\n\n```text\ndefault\n```\n\n```text\nimport { createConnection } from \"typeorm\";\n\nexport const getDBConnection = async () => {\n const dbConnection = await createConnection();\n if (!dbConnection.isConnected) await dbConnection.connect();\n return dbConnection;\n}\n```\n\n```text\nimport { Router } from 'express';\n\nconst router = Router();\n\n/* ... route configurations ... */\n\nexport default router;\n```\n\n```text\nconst bootstrap = async () => {\n try {\n // wait on connection to be established\n await getDBConnection();\n } catch (error) {\n // log error then throw\n throw error;\n }\n\n // create app\n const app = express();\n\n // some middleware configuration...\n\n // now import and setup the router\n const { default: router } = await import(\"./routers\");\n app.use(\"/api\", router);\n\n // some more middleware configuration...\n\n const server = http.createServer(app);\n server.listen(3000, () => console.log('app running at port: 3000'));\n};\n\nbootstrap();\n```\n\n```text\nindex\n```\n\n```text\nrouter\n```\n\n```text\ngetRepository\n```\n\n```text\ngetRepository\n```\n\n```text\ndb/index.ts\n```\n\n```text\ngetDBConnection\n```\n\n```text\nrouters/index.ts\n```\n\n```text\napp.ts\n```\n\n```text\nimport { HttpException, Inject, NotFoundException } from \"@nestjs/common\";\nimport { Not } from \"typeorm\";\nimport { Transactional } from \"typeorm-transactional-cls-hooked\";\nimport { TENANT_CONNECTION } from \"../tenant/tenant.module\";\nimport {Feriados} from './feriados.entity'; \n\nexport class FeriadosService {\n repository: any;\n\nconstructor(\n@Inject(TENANT_CONNECTION) private connection)\n{\n this.repository = connection.getRepository(Feriados)\n}\n\n@Transactional()\nasync agregar(tablaNueva: Feriados): Promise<Number> {\n const tablaAGuardar = await this.repository.create(tablaNueva)\n return await this.guardar(tablaAGuardar)\n}\n\n@Transactional()\nasync actualizar(tablaActualizada: Feriados): Promise<Number>{\n const tablaAGuardar = await this.repository.merge(tablaActualizada);\n return await this.guardar(tablaAGuardar)\n}\n\nasync guardar(tabla:Feriados){ \n await this.repository.save(tabla)\n return tabla.id \n}\n```\n\n```text\ntypeorm v0.3\n```\n\n```text\nConnection\n```\n\n```text\nDataSource\n```\n\n```text\ngetConnection\n```\n\n```text\nConnection \"default\" was not found\n```\n\n```text\ngetConnection\n```\n\n```text\napp.get(DataSource)\n```\n\n```text\nexport class AppModule {\n constructor(private dataSource: DataSource) {}\n\n getDataSource() {\n return this.dataSource;\n }\n}\n```\n\n```text\nconst repository = app\n .get(AppModule)\n .getDataSource()\n .getRepository('Entity_name');\n```\n\n========================================\n\nComments:\n- I assume you must provide `entities` to the TypeORM configuration (e.g. `entities: 'src/*/**.entity.ts'`).\n- Yes I have referenced my entities this way : `entities: [ __dirname + '/../../dtos/entities/*.entity.js', ]`, I edit my post\n- Not if you're using active record pattern: github.com/typeorm/typeorm/blob/master/docs/…\n- Ut works fine when I launch it with `ts-node` and starts to fail after transpilation. What do you mean `two can't live together`? Can you elaborate?\n- I have tried that connectionManager but i am getting the same error.\n- Thanks, it works. But calling getRepository in each route is not a good way.\n- If you got this error when using `npm link`, use `npm install $(npm pack | tail -1)` instead. This ensures that only one matching typeorm version is installed in the target project (if the typeorm semver versions match).\n- how can I use `app.get(DataSource)` in my service class?","metadata":{"transformedAt":"2026-08-18T18:33:44.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":76,"totalLines":590,"estimatedTokens":2763}}20{"id":"stack-50705276","source":"stackoverflow","questionId":50705276,"title":"TypeORM Postgres WHERE ANY or IN With QueryBuilder Or Find?","tags":["typeorm"],"text":"Title: TypeORM Postgres WHERE ANY or IN With QueryBuilder Or Find?\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI've been trying to figure out how to select every record in a Postgres db that includes a certain id in a column that has arrays of integers. I'm new at all this but I believe I want an SQL statement that looks like this:\n\n`SELECT * FROM members WHERE 2 = ANY(skill_id_array);`\n\nThe data in the skill_id_array column looks like this: {1,4,7}.\n\nFrom the Angular front-end I pass in an id such as 2 as a parameter. The logging in terminal shows the end of the select statement as this but it fails:\n\n`... WHERE $1 ANY (skill_id_array) -- PARAMETERS: [2]`\n\nI believe the issue is I'm trying to pass a variable into the code and it hates it. Notice that I've been trying the find method and QueryBuilder. Resulting errors are in the comments. (Full CRUD is working so my overall setup is fine.)\n\nThis works great but I understand this has a sql injection problem:\n\n```\nconst membersBySkill = await this.entityManager.query(\n `SELECT * FROM members WHERE ${integerId} = ANY(members.skill_id_array)`\n );\n```\n\nThis works but I'm not sure of a sql injection problem plus I would like to use TypeORM find or QueryBuilder.\n\n```\nconst sql = 'SELECT * FROM members WHERE '+ integerId + ' = ANY(skill_id_array)';\n const membersBySkill = await this.entityManager.query(sql);\n```\n\nIn my service:\n\n```\nimport {Any} from \"typeorm\";\n\n async getMembersBySkill(id) {\n const integerId = parseInt(id, 10); // convert id to integer for Postgres array.\n // console.log('skill_id in service', integerId);\n // Find one skill id in an array of id's.\n/*\n const membersBySkill = await this.connection.getRepository(Members).find({\n skill_id_array: Any(integerId)\n });\n // This results in an IDE error. It doesn't like a number as \n // the ANY param. \"{integerId: number} is not assignable to\n // parameter type '{}[] | FindOperator'.\n // In terminal: error: could not find array type for data type integer[]. \n // However, the db has integers.\n*/\n\n const membersBySkill = await getRepository(Members)\n .createQueryBuilder(\"members\")\n .select('*')\n .where(\":id IN (skill_id_array)\", {id: integerId})\n .getMany();\n // SELECT * FROM \"members\" \"members\" WHERE $1 IN (skill_id_array) -- PARAMETERS: [2]\n // server console: error: malformed array literal: \"2\"\n\n console.log('membersBySkill: ', membersBySkill);\n return membersBySkill;\n }\n```\n\nThe entity:\n\n```\n@Column('int', { array: true, nullable: true})\n skill_id_array: number[];\n```\n\nThe Postgres column type: `integer[]`\n\nI stop and start the Nestjs server with every change.\n\n========================================\n\nTop Answer:\nCurrently it is possible with syntax\n\n```\n.where(\"id IN(:...ids)\", { ids: [1,2,3] })\n```\n\n========================================\n\nCode:\n```text\nconst membersBySkill = await this.entityManager.query(\n `SELECT * FROM members WHERE ${integerId} = ANY(members.skill_id_array)`\n );\n```\n\n```text\nconst sql = 'SELECT * FROM members WHERE '+ integerId + ' = ANY(skill_id_array)';\n const membersBySkill = await this.entityManager.query(sql);\n```\n\n```text\nimport {Any} from \"typeorm\";\n\n async getMembersBySkill(id) {\n const integerId = parseInt(id, 10); // convert id to integer for Postgres array.\n // console.log('skill_id in service', integerId);\n // Find one skill id in an array of id's.\n/*\n const membersBySkill = await this.connection.getRepository(Members).find({\n skill_id_array: Any(integerId)\n });\n // This results in an IDE error. It doesn't like a number as \n // the ANY param. \"{integerId: number} is not assignable to\n // parameter type '{}[] | FindOperator<{}>'.\n // In terminal: error: could not find array type for data type integer[]. \n // However, the db has integers.\n*/\n\n const membersBySkill = await getRepository(Members)\n .createQueryBuilder(\"members\")\n .select('*')\n .where(\":id IN (skill_id_array)\", {id: integerId})\n .getMany();\n // SELECT * FROM \"members\" \"members\" WHERE $1 IN (skill_id_array) -- PARAMETERS: [2]\n // server console: error: malformed array literal: \"2\"\n\n console.log('membersBySkill: ', membersBySkill);\n return membersBySkill;\n }\n```\n\n```text\n@Column('int', { array: true, nullable: true})\n skill_id_array: number[];\n```\n\n```text\nSELECT * FROM members WHERE 2 = ANY(skill_id_array);\n```\n\n```text\n... WHERE $1 ANY (skill_id_array) -- PARAMETERS: [2]\n```\n\n```text\ninteger[]\n```\n\n```js\nconst membersBySkill = await getRepository(Members)\n .createQueryBuilder()\n .where(':id = ANY (skill_id_array)', {id: integerId})\n .getMany();\n```\n\n```js\nconst results = await getRepository(Members)\n .createQueryBuilder(\"member\") // you shall assign an alias\n .where(\":id = ANY(member.skill_id_array)\", { id: 1 }) // and use that alias everywhere in your query builder\n .getMany();\n```\n\n```text\nIN (id1, id2, id5)\n```\n\n```js\n.where(\"id IN(:...ids)\", { ids: [1,2,3] })\n```\n\n```js\nconst list = await this.repository.find({ where: { id: In([...idArr]) } });\n```\n\n========================================\n\nComments:\n- +1 for using ANY. I battled this for a while last night. I tried several approaches to format my array to work with the IN operator, but nothing worked. Slight tweak of the query to use ANY and it worked for my use case. Thanks!\n- This will work using the QueryBuilder but not using the query method for raw sql queries\n- You can find the discussion about this syntax here: github.com/typeorm/typeorm/issues/1239","metadata":{"transformedAt":"2026-08-18T18:33:44.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":179,"estimatedTokens":1384}}21{"id":"stack-68317383","source":"stackoverflow","questionId":68317383,"title":"TypeError: rxjs_1.lastValueFrom is not a function","tags":["postgresql","nestjs","typeorm"],"text":"Title: TypeError: rxjs_1.lastValueFrom is not a function\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am building an api using nestjs. After adding the typeorm and pg dependencies and adding the `TypeOrmModule.forRoot({})` code in `app.module.ts` like shown below.\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { CoffeesModule } from './coffees/coffees.module';\n\n@Module({\n imports: [CoffeesModule, TypeOrmModule.forRoot({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'xxx',\n database: 'postgres',\n autoLoadEntities: true,\n synchronize: true\n })],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule { }\n```\n\nI get an error `TypeError: rxjs_1.lastValueFrom is not a function` with but no error when I exclude `TypeOrmModule.forRoot({})`.\n\nWhat could be the reason for the error ?\n\n========================================\n\nTop Answer:\n### The real answer\n\nThe issue is conflict with nest version.. anyone who see this - just make sure all your nestJs packages are of version 7 or 8 - don't mix them. especially those:\n\n- @nestjs/common\n\n- @nestjs/core\n\n- @nestjs/typeorm\n\nfrom here: https://github.com/nestjs/nest/issues/7468#issuecomment-876174870\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { CoffeesModule } from './coffees/coffees.module';\n\n@Module({\n imports: [CoffeesModule, TypeOrmModule.forRoot({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'xxx',\n database: 'postgres',\n autoLoadEntities: true,\n synchronize: true\n })],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule { }\n```\n\n```text\nTypeOrmModule.forRoot({})\n```\n\n```text\napp.module.ts\n```\n\n```text\nTypeError: rxjs_1.lastValueFrom is not a function\n```\n\n```text\nTypeOrmModule.forRoot({})\n```\n\n```sh\nnpm i rxjs@^7\nyarn add rxjs@^7\npnpm i rxjs @^7\n```\n\n```text\ntoPromise()\n```\n\n```text\nlastValueFrom\n```\n\n```text\nrxjs\n```\n\n```text\nentities: [__dirname + '/src/**/*.entity{.ts,.js}'],\n```\n\n```text\nentities: [__dirname + '/**/*entity{.ts,.js}'],\n```\n\n========================================\n\nComments:\n- maybe: github.com/nestjs/nest/issues/7468","metadata":{"transformedAt":"2026-08-18T18:33:44.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":123,"estimatedTokens":640}}22{"id":"stack-50360101","source":"stackoverflow","questionId":50360101,"title":"How to exclude entity field from returned by controller JSON. NestJS + Typeorm","tags":["node.js","typescript","nestjs","typeorm"],"text":"Title: How to exclude entity field from returned by controller JSON. NestJS + Typeorm\nTags: node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to exclude password field from returned JSON. \nI am using NestJS and Typeorm. \n\nThe solution provided on this question doesn't work for me or in NestJS. I can post my code if needed.\nAny other ideas or solutions? Thanks.\n\n========================================\n\nTop Answer:\nLots of good answers in this thread. To build on apun's answer above, I think the following approach is the least likely to accidentally leak a password field:\n\n```\n@Column({ select: false })\npassword: string\n```\n\nIf the entity doesn't select that field by default, and it can only be explicitly queried (e.g. via `addSelect()` if using the query builder), I think it is a lot less likely that there's a slip somewhere, and there's less reliance on the \"magic\" of a framework (which is ultimately the `class-transformer` library) to ensure security. Realistically in many projects the only place you'd explicitly select it is where you check credentials.\n\nThis approach can also help keep the password hash from accidentally leaking into log entries, etc, which is a consideration that hasn't been mentioned yet. It feels much safer to toss around the user object knowing that it doesn't include sensitive information, especially if it could end up serialized in a log entry somewhere.\n\nAll said, the documented approach for NestJS is to use the `@Exclude()` decorator and the accepted answer is from the project's founder.\n\nI definitely make frequent use of the `Exclude()` decorator, but not necessarily for password or salt fields.\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class TransformInterceptor implements NestInterceptor {\n intercept(\n context: ExecutionContext,\n call$: Observable<any>,\n ): Observable<any> {\n return call$.pipe(map(data => classToPlain(data)));\n }\n}\n```\n\n```text\nimport { Exclude } from 'class-transformer';\n\nexport class User {\n id: number;\n email: string;\n\n @Exclude()\n password: string;\n}\n```\n\n```text\n@Exclude()\n```\n\n```text\n@UseInterceptors(ClassSerializerInterceptor)\n```\n\n```text\nimport { Exclude } from 'class-transformer';\n\nexport class User {\n /** other properties */ \n\n @Exclude()\n password: string;\n}\n```\n\n```text\n@SerializeOptions({\n excludePrefixes: ['_'],\n groups: ['admin']\n})\n```\n\n```text\n@Expose({ groups: [\"admin\"] })\nadminInfo: string;\n```\n\n```text\nClassSerializerInterceptor\n```\n\n```text\n@Exclude\n```\n\n```text\n@SerializeOptions()\n```\n\n```js\n@Entity()\nexport class User extends BaseAbstractEntity implements IUser {\n static passwordMinLength: number = 7;\n\n @ApiModelProperty({ example: faker.internet.email() })\n @IsEmail()\n @Column({ unique: true })\n email: string;\n\n @IsOptional()\n @IsString()\n @MinLength(User.passwordMinLength)\n @Exclude({ toPlainOnly: true })\n @Column({ select: false })\n password: string;\n\n @IsOptional()\n @IsString()\n @Exclude({ toPlainOnly: true })\n @Column({ select: false })\n passwordSalt: string;\n\n toJSON() {\n return classToPlain(this);\n }\n\n validatePassword(password: string) {\n if (!this.password || !this.passwordSalt) {\n return false;\n }\n return comparedToHashed(password, this.password, this.passwordSalt);\n }\n}\n```\n\n```text\n@Column({ select: false })\npassword: string\n```\n\n```text\n@Column({ select: false })\npassword: string\n```\n\n```text\naddSelect()\n```\n\n```text\nclass-transformer\n```\n\n```text\n@Exclude()\n```\n\n```text\nExclude()\n```\n\n```js\nimport { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity({ name: 'users' })\nexport class User {\n @PrimaryGeneratedColumn('uuid')\n id: string | undefined;\n\n @Column({ type: 'varchar', length: 100, unique: true })\n email: string | undefined;\n\n @Column({ type: 'text' })\n password: string | undefined;\n\n static removePassword(userObj: User) {\n return Object.fromEntries(\n Object.entries(userObj).filter(([key, val]) => key !== 'password')\n );\n }\n}\n```\n\n```js\nimport { Router, Request, Response, NextFunction } from 'express';\nimport { User } from '../../entity/User';\nimport { getRepository } from 'typeorm';\n\nconst router = Router();\n\nrouter.post(\n '/api/users/signin',\n (req: Request, res: Response, next: NextFunction) => {\n const { email } = req.body;\n\n getRepository(User)\n .findOne({ email })\n .then(user =>\n user ? res.send(User.removePassword(user)) : res.send('No such user:(')\n )\n .catch(err => next(new Error(err.message)));\n }\n);\n\nexport { router as signinRouter };\n```\n\n```js\nwithoutPassword() {\n return Object.fromEntries(\n Object.entries(this).filter(([key, val]) => key !== 'password')\n );\n}\n```\n\n```js\nres.send(user.withoutPassword());\n```\n\n```text\nremovePassword()\n```\n\n```text\nfilter()\n```\n\n```text\nfilter()\n```\n\n```text\nasync validateUser(email: string, password: string): Promise<UserWithoutPassword | null> {\n const user = await this.usersService.findOne({ email });\n\n if (user && await compare(password, user.password))\n {\n return plainToClass(UserWithoutPassword, user.toObject());\n }\n\n return null;\n}\n```\n\n```text\nplainToClass\n```\n\n```text\ntoJSON() { return classToPlain(this); }\n```\n\n```text\n@Post()\n@SerializeOptions({\n groups: ['admin','user'],\n})\nasync create(\n @Body() createProjectDto: CreateProjectDto,\n) {\n const data = await this.projectsService.create(createProjectDto);\n return classToClass(data, { groups: ['admin','DYNAMIC_GROUP'] });\n //Or you can return\n //return plainToClass(Project, plainObject, {groups: ['admin','DYNAMIC_GROUP']});\n}\n```\n\n```text\n@SerializeOptions\n```\n\n```text\nclassToClass\n```\n\n```text\nplainToClass\n```\n\n```text\nclassToClass\n```\n\n```text\nplainToClass\n```\n\n```text\n@SerializeOptions\n```\n\n```text\n@Injectable()\nexport default class TransformInterceptor implements NestInterceptor {\n intercept(\n context: ExecutionContext,\n next: CallHandler,\n ): Observable<AnyObject> {\n return next.handle().pipe(map((args) => instanceToPlain(args)));\n }\n}\n```\n\n```text\nimport { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';\nimport { map } from 'rxjs/operators';\n\n@Injectable()\nexport class ExcludeFieldsInterceptor implements NestInterceptor {\n private readonly excludedFields = ['password', 'secretKey']; // List of fields to remove\n\n intercept(context: ExecutionContext, next: CallHandler) {\n return next.handle().pipe(map((data) => this.cleanData(data)));\n }\n\n private cleanData(data: any): any {\n if (Array.isArray(data)) return data.map(this.cleanData.bind(this));\n if (data && typeof data === 'object') {\n this.excludedFields.forEach((field) => delete data[field]);\n Object.values(data).forEach((value) => this.cleanData(value)); // Recursively clean nested objects\n }\n return data;\n }\n}\n```\n\n```text\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { ExcludeFieldsInterceptor } from './interceptors/exclude-fields.interceptor';\n\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n app.useGlobalInterceptors(new ExcludeFieldsInterceptor()); // Apply globally\n await app.listen(3000);\n}\nbootstrap();\n```\n\n========================================\n\nComments:\n- Silva, Could you please point out a reference to \"exlude properties using groups.\"? I was not able find it. Thanks\n- That's ti @kamil-myśliwiec :-D Best answer for the creator.\n- Thank you, @kamil-myśliwiec . I will try this asap.\n- Also, you can exclude fields during database query (in ORM, or SQL query). Example for TypeORM - github.com/typeorm/typeorm/issues/535 .\n- I don't understand how to implement TransformInterceptor class in nest :( ?\n- The built in `ClassSerializerInterceptor` can be used here if im not mistaken\n- Is there anyway to do this with a prisma? Prisma doesn't seem to use the entity flow at all :(\n- @Kamil Myśliwiec and where to inject TransformInterceptor class?\n- You wouldn't happen to know if the built-in class supports defining groups, i.e `@Expose({ groups: [\"user\", \"admin\"] })`? I've been struggling to figure out how you'd indicate which group should be used from within the controller. From the `class-transformer` docs I can see it supports `classToPlain(user, { groups: [\"user\"] })`, but I'm a little confused where nest is calling it, and if I can pass through those options.\n- just a newbie question: where do you define the \"groups\", i.e how class-transformer would know which group the user is in? shall we define Group model first and make user has multiple groups kinda relation? i.e the user would have user.groups = ['editor', user']? Then how do we pass the user of the current request to the intercepter so it would show/hide fields accordingly?\n- @AhmetCetin The `SerializeOptions` only work if the `groups` are static per endpoint. If you want to dynamically determine the `groups` based on the request, you have to implement a custom interceptor for that.\n- See this answer, where the groups are dynamically determined for validation, you need to do something similar, but for serialization (in your case interceptor instead of pipe): stackoverflow.com/a/54057206/4694994\n- @KimKern, `@Expose` did not work as expected on method level on `POST` request. I am using nestjs `6.5.3`\n- @ddsultan Please open a new question about this; it's not possible to debug your issue in the comments without more details: a minimal example so that the problem can be reproduced and your expected behavior or output. Thanks :-)\n- Check my reply as below for how to use class-transformer groups in a dynamic way in Nestjs.\n- is there any document aboud toJSON() ?\n- toJSON method is a method that can be overriden in any javascript class. It defines how a class is converted to a regular object. When calling JSON.stringify, the toJSON method of the class is called. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… See the description section.\n- Only adding @Exclude({ toPlainOnly: true }) was what I was looking for\n- `classToPlain` is now deprecated. Use `instanceToPlain` instead.\n- Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.\n- Sure. I thought it was self explanatory.\n- Awesome. My problem solved with it\n- Please accompany your answer with an explanation","metadata":{"transformedAt":"2026-08-18T18:33:44.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":37,"totalLines":365,"estimatedTokens":2644}}23{"id":"stack-64105940","source":"stackoverflow","questionId":64105940,"title":"GraphQLError: Query root type must be provided","tags":["postgresql","graphql","nestjs","typeorm"],"text":"Title: GraphQLError: Query root type must be provided\nTags: postgresql, graphql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using NestJS, TypeORM and GraphQL for my backend API. I'm getting the following error:\n\n```\nGraphQLError [Object]: Query root type must be provided.\n at SchemaValidationContext.reportError (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:88:19)\n at validateRootTypes (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:107:13)\n at validateSchema (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:52:3)\n at graphqlImpl (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:79:62)\n at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:28:59\n at new Promise ()\n at Object.graphql (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:26:10)\n at GraphQLSchemaFactory. (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:49:52)\n at Generator.next ()\n at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/tslib/tslib.js:114:75\n```\n\nThis is what my file structure and code looks like:\nhttps://i.sstatic.net/fpUEL.png\n\nCan someone please help me. My repo: https://github.com/wise-introvert/nestjs-graphql-api.git\n\n========================================\n\nTop Answer:\nAlso ensure the Resolver is added in the module providers\n\n```\n@Module({\n imports: [\n GraphQLModule.forRoot({\n installSubscriptionHandlers: true,\n autoSchemaFile: true,\n }),\n ],\n controllers: [],\n providers: [FooResolver], //< This\n})\nexport class FooModule {}\n```\n\n========================================\n\nCode:\n```text\nGraphQLError [Object]: Query root type must be provided.\n at SchemaValidationContext.reportError (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:88:19)\n at validateRootTypes (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:107:13)\n at validateSchema (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/type/validate.js:52:3)\n at graphqlImpl (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:79:62)\n at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:28:59\n at new Promise (<anonymous>)\n at Object.graphql (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/graphql/graphql.js:26:10)\n at GraphQLSchemaFactory.<anonymous> (/home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/@nestjs/graphql/dist/schema-builder/graphql-schema.factory.js:49:52)\n at Generator.next (<anonymous>)\n at /home/wise-introvert/Container/Projects/the-notebook/app/server/node_modules/tslib/tslib.js:114:75\n```\n\n```js\n@Resolver()\nexport class FooResolver {\n\n @Query(() => String)\n sayHello(): string {\n return 'Hello World!';\n }\n}\n```\n\n```text\n@Query()\n```\n\n```js\n@Module({\n imports: [\n GraphQLModule.forRoot({\n installSubscriptionHandlers: true,\n autoSchemaFile: true,\n }),\n ],\n controllers: [],\n providers: [FooResolver], //< This\n})\nexport class FooModule {}\n```\n\n```js\n// Correct\nimport { Resolver, Query } from '@nestjs/graphql';\n\n// Incorrect in NestJS\nimport { Resolver, Query } from 'type-graphql';\n```\n\n```text\n@Module({ providers: [NftsResolver, NftsService] })\nexport class NftsModule {}\n```\n\n```text\nnfts.module.ts\n```\n\n```text\napp.module.ts\n```\n\n```js\n@Module({\n imports: [\n GraphQLModule.forRoot<ApolloDriverConfig>({\n driver: ApolloDriver,\n typePaths: ['./**/*.graphql'],\n definitions: {\n path: join(process.cwd(), 'src/graphql.ts'),\n outputAs: 'class',\n },\n }),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\n```\n\n```text\ntypePaths\n```\n\n```text\ndefinitions\n```\n\n```text\n*.graphql\n```\n\n========================================\n\nComments:\n- I've added a dummy function under `@Query` decorator in my resolver but it's still throwing the same error.\n- Thanks! This was the issue for me. The accepted answer did not solve the bug for me.\n- What was missing for me was `autoSchemaFile: true` in the options object.","metadata":{"transformedAt":"2026-08-18T18:33:44.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":147,"estimatedTokens":1136}}24{"id":"stack-56964351","source":"stackoverflow","questionId":56964351,"title":"Select attributes on repository.find() with relations (TypeORM)","tags":["javascript","typescript","typeorm"],"text":"Title: Select attributes on repository.find() with relations (TypeORM)\nTags: javascript, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nMy method returns a a bill object with all of User object.\nI would like that I return only bill object and User with two attributes in entity. I use TypeORM\n\n```\n/**\n * Returns a bills by account bill\n */\n async getByAccountBill(\n accountBill: string,\n id?: number\n ): Promise {\n const userService = new UserService();\n const user = await userService.getById(id);\n\n const bills = await this.billRepository.find({\n select: [\"accountBill\"],\n where: {\n accountBill: Like(`${accountBill}%`),\n user: Not(`${user.id}`)\n },\n relations: [\"user\"] // I get All object Entity (userId, password, login...) I want to only name and surname\n });\n\n if (bills) {\n return bills;\n } else {\n return undefined;\n }\n }\n```\n\n========================================\n\nTop Answer:\nIt's bit late but for all others who visit this page may be helpful\nthere is a option available in `typeorm` so we can get the result how we want.\n\n```\nreturn this.repository.find({\n relations: ['user'],\n loadRelationIds: true,\n where: { ... },\n order: { ... }\n});\n```\n\nhttps://i.sstatic.net/VOctS.png\n\n========================================\n\nCode:\n```text\n/**\n * Returns a bills by account bill\n */\n async getByAccountBill(\n accountBill: string,\n id?: number\n ): Promise<Object | undefined> {\n const userService = new UserService();\n const user = await userService.getById(id);\n\n const bills = await this.billRepository.find({\n select: [\"accountBill\"],\n where: {\n accountBill: Like(`${accountBill}%`),\n user: Not(`${user.id}`)\n },\n relations: [\"user\"] // I get All object Entity (userId, password, login...) I want to only name and surname\n });\n\n if (bills) {\n return bills;\n } else {\n return undefined;\n }\n }\n```\n\n```text\nconst values = this.billRepository.createQueryBuilder(\"bill\")\n .leftJoinAndSelect(\"bill.user\", \"user\")\n .where(\"bill.accountBill LIKE :accountBill\", {accountBill})\n .andWhere(\"user.id = :userId\", {userId: user.id})\n .select([\"user.name\", \"user.surname\"])\n .execute();\n```\n\n```text\n// NOTE\n// .execute() will return raw results.\n// To return objects, use .getMany()\n```\n\n```text\n/**\n * Applies give find options to the given query builder.\n */\n static applyOptionsToQueryBuilder<T>(qb: SelectQueryBuilder<T>, options: FindOneOptions<T> | FindManyOptions<T> | undefined): SelectQueryBuilder<T>;\n...\n if (options.loadRelationIds === true) {\n qb.loadAllRelationIds();\n }\n else if (options.loadRelationIds instanceof Object) {\n qb.loadAllRelationIds(options.loadRelationIds);\n }\n```\n\n```text\n/**\n * Loads all relation ids for all relations of the selected entity.\n * All relation ids will be mapped to relation property themself.\n * If array of strings is given then loads only relation ids of the given properties.\n */\nloadAllRelationIds(options?: { relations?: string[], disableMixedMap?: boolean }): this { // todo: add skip relations\n this.expressionMap.mainAlias!.metadata.relations.forEach(relation => {\n if (options !== undefined && options.relations !== undefined && options.relations.indexOf(relation.propertyPath) === -1)\n return;\n\n this.loadRelationIdAndMap(\n this.expressionMap.mainAlias!.name + \".\" + relation.propertyPath,\n this.expressionMap.mainAlias!.name + \".\" + relation.propertyPath,\n options\n );\n });\n return this;\n}\n\n/**\n * LEFT JOINs relation id and maps it into some entity's property.\n * Optionally, you can add condition and parameters used in condition.\n */\nloadRelationIdAndMap(mapToProperty: string, relationName: string, options?: { disableMixedMap?: boolean }): this;\n\n/**\n * LEFT JOINs relation id and maps it into some entity's property.\n * Optionally, you can add condition and parameters used in condition.\n */\nloadRelationIdAndMap(mapToProperty: string, relationName: string, alias: string, queryBuilderFactory: (qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>): this;\n\n/**\n * LEFT JOINs relation id and maps it into some entity's property.\n * Optionally, you can add condition and parameters used in condition.\n */\nloadRelationIdAndMap(mapToProperty: string,\n relationName: string,\n aliasNameOrOptions?: string|{ disableMixedMap?: boolean },\n queryBuilderFactory?: (qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>): this {\n\n const relationIdAttribute = new RelationIdAttribute(this.expressionMap);\n relationIdAttribute.mapToProperty = mapToProperty;\n relationIdAttribute.relationName = relationName;\n if (typeof aliasNameOrOptions === \"string\")\n relationIdAttribute.alias = aliasNameOrOptions;\n if (aliasNameOrOptions instanceof Object && (aliasNameOrOptions as any).disableMixedMap)\n relationIdAttribute.disableMixedMap = true;\n\n relationIdAttribute.queryBuilderFactory = queryBuilderFactory;\n this.expressionMap.relationIdAttributes.push(relationIdAttribute);\n\n if (relationIdAttribute.relation.junctionEntityMetadata) {\n this.expressionMap.createAlias({\n type: \"other\",\n name: relationIdAttribute.junctionAlias,\n metadata: relationIdAttribute.relation.junctionEntityMetadata\n });\n }\n return this;\n}\n```\n\n```text\n/**\n * Stores all join relation id attributes which will be used to build a JOIN query.\n */\nexport class RelationIdAttribute {\n\n // -------------------------------------------------------------------------\n // Public Properties\n // -------------------------------------------------------------------------\n\n /**\n * Alias of the joined (destination) table.\n */\n alias?: string;\n\n /**\n * Name of relation.\n */\n relationName: string;\n\n /**\n * Property + alias of the object where to joined data should be mapped.\n */\n mapToProperty: string;\n\n /**\n * Extra condition applied to \"ON\" section of join.\n */\n queryBuilderFactory?: (qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>;\n\n /**\n * Indicates if relation id should NOT be loaded as id map.\n */\n disableMixedMap = false;\n...\n```\n\n```js\nreturn this.repository.find({\n relations: ['user'],\n loadRelationIds: true,\n where: { ... },\n order: { ... }\n});\n```\n\n```text\ntypeorm\n```\n\n```text\nasync getByAccountBill(\n accountBill: string,\n id?: number\n ): Promise<Object | undefined> {\n const userService = new UserService();\n const user = await userService.getById(id);\n\n const bills = await this.billRepository.find({\n where: {\n accountBill: Like(`${accountBill}%`),\n user: Not(`${user.id}`)\n },\n relations: [\"user\"],\n select: {\n user: {\n id: true,\n name: true\n }\n }\n });\n\n if (bills) {\n return bills;\n } else {\n return undefined;\n }\n }\n```\n\n========================================\n\nComments:\n- The 'execute' method return a raw result, so maybe for you is better to use getMany thats return an object\n- Hey @zenbeni, I am trying to do somethiing similar but it would return `undefined` if there is no user and `andWhere` condition fails. How do we make same query work if there are no entries in relation table yet?\n- The question explicitly mentioned find() method. We want to rely on the wiring we have already done in the model. Query builder is a powerful tool, but it should only be employed in complex queries where model wiring isn't enough in my opinion. The question include a simple query.\n- @hadaytullah you can't use basic model wiring, as getting only 2 fields in User is completely out of the vanilla model which includes much more fields. You have to use custom query to object mapping to do so. Thus, query builder, this is for me the correct tool.\n- Since typeOrm lack applying selection on a joined table, we can use typescript Array.map() to remove unnecessary attributes from the collection. It is not a wise solution if the collection is too large. But at the same time, such mapping is anyway happing on the database server if we use query builder with that selection included in the query. So, we just moved that processing from DB server to the API server. The response time would be a good metric to decide which solution find+Array.map VS querybuilder is good for your app.\n- Data is where the performance is, you imply more network usage with your proposed solution, more I/O on database as you fetch more data than you need (I/O and network are in most cases more critical than any in-memory algorithm optimizations). Also you add non vanilla usage of data structures & TypeOrm with custom code that you will have to maintain afterwards (opposed to classic querybuilder api usage). Removing column data after having fetched them explicitely on the database is suboptimal at best and should be avoided performance wise.\n- It is typeORM modeling limitations that led to usage of query-builder or vanilla code. I guess once the models allow more complex joins, there would be no need for them. Sequalize is a bit more mature ORM and many complex joins can be done.\n- This is the best possible method than using query builder for simpler joins.","metadata":{"transformedAt":"2026-08-18T18:33:44.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":267,"estimatedTokens":2345}}25{"id":"stack-64941148","source":"stackoverflow","questionId":64941148,"title":"Node.js add created_at and updated_at in entity of typeorm","tags":["node.js","typeorm","node.js-typeorm"],"text":"Title: Node.js add created_at and updated_at in entity of typeorm\nTags: node.js, typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nI have `task` entity like this:\n\n```\nimport {BaseEntity, Column, Entity, PrimaryGeneratedColumn} from \"typeorm\";\n\n@Entity()\nexport class Task extends BaseEntity{\n @PrimaryGeneratedColumn()\n id:number;\n\n @Column()\n title:string\n\n @Column()\n description:string\n\n}\n```\n\nI want to add created_at and updated_at field to this entity and populate it automatically with `Node.js` like `Laravel` framework. My database is `postgres`\n\n========================================\n\nTop Answer:\n```\nimport {BaseEntity, Column, Entity, PrimaryGeneratedColumn, CreateDateColumn} from \"typeorm\";\n\n@Entity()\nexport class Task extends BaseEntity{\n @PrimaryGeneratedColumn()\n id:number;\n\n @Column()\n title:string\n\n @Column()\n description:string\n \n @CreateDateColumn()\n created_at: Date;\n\n @UpdateDateColumn()\n updated_at: Date;\n\n}\n```\n\n========================================\n\nCode:\n```text\nimport {BaseEntity, Column, Entity, PrimaryGeneratedColumn} from \"typeorm\";\n\n@Entity()\nexport class Task extends BaseEntity{\n @PrimaryGeneratedColumn()\n id:number;\n\n @Column()\n title:string\n\n @Column()\n description:string\n\n}\n```\n\n```text\ntask\n```\n\n```text\nNode.js\n```\n\n```text\nLaravel\n```\n\n```text\npostgres\n```\n\n```text\nimport { CreateDateColumn,UpdateDateColumn } from \"typeorm\";\n```\n\n```text\n@CreateDateColumn({ type: \"timestamp\", default: () => \"CURRENT_TIMESTAMP(6)\" })\npublic created_at: Date;\n\n@UpdateDateColumn({ type: \"timestamp\", default: () => \"CURRENT_TIMESTAMP(6)\", onUpdate: \"CURRENT_TIMESTAMP(6)\" })\npublic updated_at: Date;\n```\n\n```text\nimport {BaseEntity, Column, Entity, PrimaryGeneratedColumn, CreateDateColumn} from \"typeorm\";\n\n@Entity()\nexport class Task extends BaseEntity{\n @PrimaryGeneratedColumn()\n id:number;\n\n @Column()\n title:string\n\n @Column()\n description:string\n \n @CreateDateColumn()\n created_at: Date;\n\n @UpdateDateColumn()\n updated_at: Date;\n\n\n}\n```\n\n```text\nimport { CreateDateColumn, UpdateDateColumn } from 'typeorm';\n\n@CreateDateColumn()\ncreatedAt: Date;\n\n@UpdateDateColumn()\nupdatedAt: Date;\n```\n\n```js\nimport moment from \"moment\";\n\n@CreateDateColumn()\n created_at: Date;\n\n@UpdateDateColumn()\n updated_at: Date;\n\n@BeforeInsert()\ninsertCreated() {\n this.created_at = new Date(\n moment().tz(\"America/Sao_Paulo\").format(\"YYYY-MM-DD HH:mm:ss\")\n );\n this.updated_at = new Date(\n moment().tz(\"America/Sao_Paulo\").format(\"YYYY-MM-DD HH:mm:ss\")\n );\n }\n\n@BeforeUpdate()\ninsertUpdated() {\n this.updated_at = new Date(\n moment().tz(\"America/Sao_Paulo\").format(\"YYYY-MM-DD HH:mm:ss\")\n );\n }\n```\n\n========================================\n\nComments:\n- how about to add timestamps fields to all entities?\n- @ShaSha you can use entity inheritance technique\n- I noticed Welisson Moura's answer did not includ extra properties for the `CreateDateColumn` and `UpdateDateColumn` decorators. Is there any reason for the extra properties you specified?\n- @penava What does `CURRENT_TIMESTAMP(6)` actually do\n- @bilard save as 6 digit under second. 6 means save as micro second.\n- This is the right answer: stackoverflow.com/a/65066998/5129048\n- This works only for MySql... `onUpdate: \"CURRENT_TIMESTAMP(6)\"`","metadata":{"transformedAt":"2026-08-18T18:33:44.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":171,"estimatedTokens":829}}26{"id":"stack-63793417","source":"stackoverflow","questionId":63793417,"title":"TypeORM: What's difference between @Unique decorator and { unique: true } in column options?","tags":["typeorm"],"text":"Title: TypeORM: What's difference between @Unique decorator and { unique: true } in column options?\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nIn TypeORM you have the possibility to set a unique flag in the column options, or to set column(s) to unique for the entity.\n\nWhen would you use which, and what's the difference there?\n\n`@Unique([\"firstName\"])`\n\nhttps://typeorm.io/#/decorator-reference/unique\n\n```\n@Column({ unique: true })\nfirstName: string;\n```\n\nhttps://typeorm.io/#/decorator-reference/column\n\n========================================\n\nTop Answer:\nI prefer `unique: true` inside `@Column()` for readability.\n\nI prefer `@Unique()` if I need to make unique value for multiple columns, i.e composite key.\n\n```\n@Entity(\"t_mst_sales\")\n@Index([\"sellers\", \"productId\", \"salesDate\"], { unique: true })\nexport class PrataapSalesEntity extends BaseEntity {\n @PrimaryGeneratedColumn({ name: \"sales_id\" })\n ...\n \n @Column({ name: \"product_id\" })\n productId: number;\n\n @ManyToOne(() => Users, (user) => user.productSellers)\n @JoinColumn({ name: \"seller_id\" })\n sellers: Users;\n\n @Column({ name: \"sales_date\", type: \"date\" })\n salesDate: Date;\n\n ... \n}\n```\n\nBonus: I prefer `@Index()` over `@Unique()` whenever I need to create custom name of constraint.\n\n```\n@Index(\"uk_user_email\", [\"email\"], { unique: true })\nexport class Users extends BasicInfo {\n...\n@Column({ name: \"email\", type: \"varchar\", length: 30 })\nemail: string;\n...\n}\n```\n\n========================================\n\nCode:\n```text\n@Column({ unique: true })\nfirstName: string;\n```\n\n```text\n@Unique([\"firstName\"])\n```\n\n```js\n@Unique('my_unique_constraint', ['firstName']) // make firstName unique\nexport class PersonEntity {\n\n @Column({ unique: true }) // make firstName unique, too; decide which to chose\n firstName: string;\n...\n```\n\n```text\n@Unique\n```\n\n```text\n@Column({ unique: true })\n```\n\n```text\n@Unique\n```\n\n```text\n@Unique([\"firstName\", \"secondName\"])\n```\n\n```text\n@Column\n```\n\n```text\n@Unique\n```\n\n```text\n@Unique\n```\n\n```text\n@Unique\n```\n\n```text\n@Entity(\"t_mst_sales\")\n@Index([\"sellers\", \"productId\", \"salesDate\"], { unique: true })\nexport class PrataapSalesEntity extends BaseEntity {\n @PrimaryGeneratedColumn({ name: \"sales_id\" })\n ...\n \n @Column({ name: \"product_id\" })\n productId: number;\n\n @ManyToOne(() => Users, (user) => user.productSellers)\n @JoinColumn({ name: \"seller_id\" })\n sellers: Users;\n\n @Column({ name: \"sales_date\", type: \"date\" })\n salesDate: Date;\n\n ... \n}\n```\n\n```text\n@Index(\"uk_user_email\", [\"email\"], { unique: true })\nexport class Users extends BasicInfo {\n...\n@Column({ name: \"email\", type: \"varchar\", length: 30 })\nemail: string;\n...\n}\n```\n\n```text\nunique: true\n```\n\n```text\n@Column()\n```\n\n```text\n@Unique()\n```\n\n```text\n@Index()\n```\n\n```text\n@Unique()\n```\n\n========================================\n\nComments:\n- There is also `@Index({ unique: true })`\n- Is it possible to set the constraint name when using `@Column({ unique: true })`?\n- @Ari I don't think so, since there is no such property in the ColumnOptions github.com/typeorm/typeorm/blob/…","metadata":{"transformedAt":"2026-08-18T18:33:44.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":170,"estimatedTokens":770}}27{"id":"stack-52246722","source":"stackoverflow","questionId":52246722,"title":"How to query a Many-to-Many relation with TypeORM","tags":["typeorm"],"text":"Title: How to query a Many-to-Many relation with TypeORM\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\n`Note` has a many-to-many relationship to `Subject`\n\n**What is the best way to query it?** I would *like* to write the following to get all the subjects on a give note:\n\n```\nconst subjectRepo = connection.getRepository(Subject);\n const response = await subjectRepo.find({\n relations: ['notes'],\n where: { note }\n });\n```\n\nbut that returns ALL of the subjects, not just the subjects on the note.\n\nReln defined as:\n\n```\n@ManyToMany(() => Subject, (subject: Subject) => subject.notes)\n subjects: Subject[];\n```\n\n-- and --\n\n```\n@ManyToMany(() => Note, note => note.subjects)\n @JoinTable()\n notes: Note[];\n```\n\nThe executed query is:\n\n```\nSELECT \"Subject\".\"id\" AS \"Subject_id\", \"Subject\".\"name\" AS \"Subject_name\", \"Subject\".\"description\" AS \"Subject_description\", \"Subject\".\"createdDate\" AS \"Subject_createdDate\", \"Subject\".\"updatedDate\" AS \"Subject_updatedDate\", \"Subject\".\"notebookId\" AS \"Subject_notebookId\", \"Subject\".\"measurementsId\" AS \"Subject_measurementsId\", \"Subject_notes\".\"id\" AS \"Subject_notes_id\", \"Subject_notes\".\"content\" AS \"Subject_notes_content\", \"Subject_notes\".\"notedAt\" AS \"Subject_notes_notedAt\", \"Subject_notes\".\"createdDate\" AS \"Subject_notes_createdDate\", \"Subject_notes\".\"updatedDate\" AS \"Subject_notes_updatedDate\", \"Subject_notes\".\"notebookId\" AS \"Subject_notes_notebookId\" FROM \"subject\" \"Subject\" LEFT JOIN \"subject_notes_note\" \"Subject_Subject_notes\" ON \"Subject_Subject_notes\".\"subjectId\"=\"Subject\".\"id\" LEFT JOIN \"note\" \"Subject_notes\" ON \"Subject_notes\".\"id\"=\"Subject_Subject_notes\".\"noteId\"\n```\n\nNote: you can do this:\n\n```\nreturn subjectRepo\n .createQueryBuilder('subject')\n .leftJoin('subject.notes', 'note')\n .where('note.id = :id', { id: note.id })\n .getMany();\n```\n\nBut I am hoping for an approach with less strings, and explicit joining\n\n========================================\n\nCode:\n```text\nconst subjectRepo = connection.getRepository(Subject);\n const response = await subjectRepo.find({\n relations: ['notes'],\n where: { note }\n });\n```\n\n```text\n@ManyToMany(() => Subject, (subject: Subject) => subject.notes)\n subjects: Subject[];\n```\n\n```text\n@ManyToMany(() => Note, note => note.subjects)\n @JoinTable()\n notes: Note[];\n```\n\n```text\nSELECT \"Subject\".\"id\" AS \"Subject_id\", \"Subject\".\"name\" AS \"Subject_name\", \"Subject\".\"description\" AS \"Subject_description\", \"Subject\".\"createdDate\" AS \"Subject_createdDate\", \"Subject\".\"updatedDate\" AS \"Subject_updatedDate\", \"Subject\".\"notebookId\" AS \"Subject_notebookId\", \"Subject\".\"measurementsId\" AS \"Subject_measurementsId\", \"Subject_notes\".\"id\" AS \"Subject_notes_id\", \"Subject_notes\".\"content\" AS \"Subject_notes_content\", \"Subject_notes\".\"notedAt\" AS \"Subject_notes_notedAt\", \"Subject_notes\".\"createdDate\" AS \"Subject_notes_createdDate\", \"Subject_notes\".\"updatedDate\" AS \"Subject_notes_updatedDate\", \"Subject_notes\".\"notebookId\" AS \"Subject_notes_notebookId\" FROM \"subject\" \"Subject\" LEFT JOIN \"subject_notes_note\" \"Subject_Subject_notes\" ON \"Subject_Subject_notes\".\"subjectId\"=\"Subject\".\"id\" LEFT JOIN \"note\" \"Subject_notes\" ON \"Subject_notes\".\"id\"=\"Subject_Subject_notes\".\"noteId\"\n```\n\n```text\nreturn subjectRepo\n .createQueryBuilder('subject')\n .leftJoin('subject.notes', 'note')\n .where('note.id = :id', { id: note.id })\n .getMany();\n```\n\n```text\nNote\n```\n\n```text\nSubject\n```\n\n```sql\nSELECT *\nFROM subject\nJOIN subject_note AS jt on jt.subject_id = subject.id\nWHERE jt.note_id = :id\n```\n\n```js\nnote = await noteRepo.find({\n relations: ['subjects'],\n where: { id: note.id }\n});\nconst subjects = note.subjects\n```\n\n```js\n// note entity\n@ManyToMany(() => Subject, (subject: Subject) => subject.notes)\nsubjects: Promise<Subject[]>;\n\n// subject entity\n@ManyToMany(() => Note, note => note.subjects)\n@JoinTable()\nnotes: Promise<Note[]>;\n```\n\n```js\nconst note = await noteRepo.find({\n where: { id: someId }\n});\nconst subjects = await note.subjects\n```\n\n```text\nrepo.find\n```\n\n```text\nwhere\n```\n\n```text\nrepo.find(...)\n```\n\n```text\njoin\n```\n\n```text\nwhere\n```\n\n```text\nTypeORM\n```\n\n```text\nsubject\n```\n\n```text\nnote\n```\n\n```text\nTypeORM\n```\n\n```text\nTypeORM\n```\n\n```text\nPromise\n```\n\n```text\nawait\n```\n\n```text\nfind\n```\n\n========================================\n\nComments:\n- ## Update 1 year later After working with TypeORM for a year -- I have fully embraced the power of the queryBuilder and now is my first approach vs using finders.\n- Thanks a lot for this answer. But can't this be done with one single *.find* function? Something like .find({where: { note: contains('id')}}) of sort. Thank you.\n- seems like #2 is the best approach until you are forced to optimize\n- github.com/typeorm/typeorm/blob/master/docs/…\n- newbedev.com/typeorm-query-entity-based-on-relation-property\n- For future references","metadata":{"transformedAt":"2026-08-18T18:33:44.683Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":24,"totalLines":188,"estimatedTokens":1207}}28{"id":"stack-71803499","source":"stackoverflow","questionId":71803499,"title":"Typeorm when trying to run migrations: Missing required argument: dataSource","tags":["node.js","typeorm"],"text":"Title: Typeorm when trying to run migrations: Missing required argument: dataSource\nTags: node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to run TypeORM migrations with `ormconfig.json` like this\n\n```\n{\n \"name\": \"default\",\n \"type\": \"postgres\",\n \"host\": \"ip-is-here\",\n \"port\": 5432,\n \"username\": \"name\",\n \"password\": \"12345\",\n \"database\": \"db1\",\n \"synchronize\": false,\n \"logging\": false,\n \"entities\": [\"dist/storage/**/*.js\"],\n \"migrations\": [\"dist/storage/migrations/**/*.js\"],\n \"cli\": {\n \"entitiesDir\": \"src/storage\",\n \"migrationsDir\": \"src/storage/migrations\"\n }\n}\n```\n\nvia `yarn typeorm migration:run` \n\nBut get an error:\n\n```\nMissing required argument: dataSource\n```\n\nWhat I have to do?\nThank you for your advices!\n\n========================================\n\nTop Answer:\nwith latest typescript if you are using cli setup as per typeorm setup\n\nthen following package.json script will work\n\n```\n\"scripts\": {\n \"typeorm\": \"typeorm-ts-node-commonjs -d ./src/datasources/PostgresDatasource.ts\",\n}\n```\n\nRun `npm run typeorm migration:generate src/migration/initaltables` `npm run typeorm migration:run`\n\n========================================\n\nCode:\n```text\n{\n \"name\": \"default\",\n \"type\": \"postgres\",\n \"host\": \"ip-is-here\",\n \"port\": 5432,\n \"username\": \"name\",\n \"password\": \"12345\",\n \"database\": \"db1\",\n \"synchronize\": false,\n \"logging\": false,\n \"entities\": [\"dist/storage/**/*.js\"],\n \"migrations\": [\"dist/storage/migrations/**/*.js\"],\n \"cli\": {\n \"entitiesDir\": \"src/storage\",\n \"migrationsDir\": \"src/storage/migrations\"\n }\n}\n```\n\n```text\nMissing required argument: dataSource\n```\n\n```text\normconfig.json\n```\n\n```text\nyarn typeorm migration:run\n```\n\n```js\nexport const connectionSource = new DataSource({\n migrationsTableName: 'migrations',\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'user',\n password: 'pass',\n database: 'somehealthchecker',\n logging: false,\n synchronize: false,\n name: 'default',\n entities: ['src/**/**.entity{.ts,.js}'],\n migrations: ['src/migrations/**/*{.ts,.js}'],\n subscribers: ['src/subscriber/**/*{.ts,.js}'],\n});\n```\n\n```js\nawait connectionSource.initialize();\n```\n\n```js\nconst myRepo = connectionSource.getRepository(SomeEntity)\n```\n\n```json\n\"migration:generate\": \"./node_modules/.bin/ts-node ./node_modules/.bin/typeorm migration:generate -d src/modules/config/ormconfig.ts\",\n\"migration:up\": \"./node_modules/.bin/ts-node ./node_modules/.bin/typeorm migration:run -d src/modules/config/ormconfig.ts\",\n\"migration:down\": \"./node_modules/.bin/ts-node ./node_modules/.bin/typeorm migration:revert -d src/modules/config/ormconfig.ts\",\n```\n\n```text\normconfig.json\n```\n\n```text\normconfig.ts\n```\n\n```text\npackage.json\n```\n\n```text\nyarn typeorm migration:run -d dist/datasources/datasource.js\n```\n\n```text\nnpm run typeorm migration:generate -- -n migrationNameHere\n```\n\n```text\n--\n```\n\n```text\nexport const AppDataSource = new DataSource({\n type: \"postgres\",\n host: \"localhost\",\n port: 5432,\n username: \"postgres\",\n password: \"ROOT\",\n database: \"userLog\",\n synchronize: true,\n logging: true, \n entities: [User, Student],\n migrations: [\"src/migration/**/*.ts\"],\n migrationsTableName: \"custom_migration_table\",\n subscribers: [\"src/migration/**/*.ts\"],\n})\n```\n\n```text\nAppDataSource.initialize()\n .then(async () => {\n // do anything here like connecting to your express server or adding document to your db\n }\n```\n\n```text\n\"create\": \"typeorm migration:create ./src/migration/learningMigration\"\n\"generate\": \"typeorm migration:generate -n PostRefactoring\"\n\"migrate\": \"npx typeorm-ts-node-commonjs migration:run -d src/data-source\", \n\"revert\": \"npx typeorm-ts-node-commonjs migration:revert -d src/data-source\",\n```\n\n```text\ntypeorm migration:run\n```\n\n```text\n\"scripts\": {\n \"typeorm\": \"typeorm-ts-node-commonjs -d ./src/datasources/PostgresDatasource.ts\",\n}\n```\n\n```text\nnpm run typeorm migration:generate src/migration/initaltables\n```\n\n```text\nnpm run typeorm migration:run\n```\n\n```text\nnpx typeorm-ts-node-commonjs migration:run -- -d ./src/data-source.ts\n```\n\n```text\nnpx typeorm-ts-node-commonjs migration:run -d ./src/data-source.ts\n```\n\n```text\n\"scripts\": {\n \"migration:run\": \"typeorm-ts-node-commonjs migration:run -d ./src/data-source.ts\",\n \"migration:revert\": \"typeorm-ts-node-commonjs migration:revert -d ./src/data-source.ts\"\n}\n```\n\n```text\n--\n```\n\n========================================\n\nComments:\n- hi,in my case this is have the path:dist/data-source.js but it still not work,can you have another way?\n- This wanago.io/2022/07/25/api-nestjs-database-migrations-typeorm is a far more useful tutorial than the official docs\n- I am using NestJS, and I had to create an extra file that exports the DataSource object just for this purpose.\n- For my Nestjs projects, I also create a separate database configuration file to generate the migrations. I haven't found a way to make TypeOrm read configurations from a module yet, but it looks like TypeOrm can't do that. Since we use our own module system in Nestjs, if we were using Express, for example, we would need to create such a file one way or another, and there would be no problem. But at least it works\n- I wish this was written in the documentation\n- Then how can we import typeormmodule options in the AppModule? Or we have to write again all the configuration there?\n- @RiteshKhatri - Essentially, in the database.module.ts file (which is exactly the imported module), you configure the database connection and other subtle settings that your application will work with. ormconfig.ts can contain a list of basic settings for the same database (or repeat them if you want) and serves only to specify the path to the configuration file in a script to create a structural migration.\n- While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.\n- Very nice answer .Thank you very much\n- How to add scripts for generate command for migration in package.json. By the below way --- \"generate\": \"typeorm migration:generate -n PostRefactoring\". It is not working.","metadata":{"transformedAt":"2026-08-18T18:33:44.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":225,"estimatedTokens":1555}}29{"id":"stack-56660312","source":"stackoverflow","questionId":56660312,"title":"cannot connect an SSL secured database to typeorm","tags":["postgresql","ssl","nestjs","typeorm"],"text":"Title: cannot connect an SSL secured database to typeorm\nTags: postgresql, ssl, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThis is my first time using NestJS and I am having trouble connecting my Postgres database which is hosted on Digitalocean to NestJS.\n\nI searched online for solutions and tried adding `\"ssl\": \"true\" or \"extra\": { \"ssl\": \"true\" }`\n\nHeres my ormconfig.json\n\n```\n{\n \"type\": \"postgres\",\n \"host\": \"host\",\n \"port\": \"port\",\n \"username\": \"username\",\n \"password\": \"password\",\n \"database\": \"database\",\n \"extra\": {\n \"ssl\": \"true\"\n },\n \"synchronize\": \"true\",\n \"logging\": \"true\",\n \"entities\": [\"src/**/*.entity.ts\", \"dist/**/*.entity.js\"]\n}\n```\n\nI expect it to connect to the server. The error I'm getting is `[TypeOrmModule] Unable to connect to the database. error: no pg_hba.conf entry for host \"\", user \"\", database \"\", SSL off`\n\n========================================\n\nTop Answer:\nThis works if you are connecting to postgres database on heroku from localhost using typeorm.\n\n`ormconfig.json`\n\n```\n{\n \"name\": \"default\",\n \"type\": \"postgres\",\n \"url\": \"postgres://username:password@host:port/database\",\n \"synchronize\": true,\n \"logging\": true,\n \"entities\": [\"src/entity/*.*\"],\n \"ssl\": true,\n \"extra\": {\n \"ssl\": {\n \"rejectUnauthorized\": false\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n \"type\": \"postgres\",\n \"host\": \"host\",\n \"port\": \"port\",\n \"username\": \"username\",\n \"password\": \"password\",\n \"database\": \"database\",\n \"extra\": {\n \"ssl\": \"true\"\n },\n \"synchronize\": \"true\",\n \"logging\": \"true\",\n \"entities\": [\"src/**/*.entity.ts\", \"dist/**/*.entity.js\"]\n}\n```\n\n```text\n\"ssl\": \"true\" or \"extra\": { \"ssl\": \"true\" }\n```\n\n```text\n[TypeOrmModule] Unable to connect to the database. error: no pg_hba.conf entry for host \"\", user \"\", database \"\", SSL off\n```\n\n```text\nmodule.exports = {\n name: 'default',\n type: 'postgres',\n host: 'host',\n port: port,\n username: 'username',\n password: 'password',\n database: 'database',\n synchronize: true,\n dropSchema: false,\n logging: true,\n ssl: {\n ca: process.env.SSL_CERT,\n },\n entities: ['src/**/*.entity.ts', 'dist/**/*.entity.js'],\n};\n```\n\n```text\nssl: {\n rejectUnauthorized: false,\n ca: fs.readFileSync('/path/to/server-certificates/root.crt').toString(),\n key: fs.readFileSync('/path/to/client-key/postgresql.key').toString(),\n cert: fs.readFileSync('/path/to/client-certificates/postgresql.crt').toString(),\n },\n```\n\n```text\n{\n \"name\": \"default\",\n \"type\": \"postgres\",\n \"url\": \"postgres://username:password@host:port/database\",\n \"synchronize\": true,\n \"logging\": true,\n \"entities\": [\"src/entity/*.*\"],\n \"ssl\": true,\n \"extra\": {\n \"ssl\": {\n \"rejectUnauthorized\": false\n }\n }\n}\n```\n\n```text\normconfig.json\n```\n\n```js\nTypeOrmModule.forRoot({\n type: 'postgres',\n url: process.env.DATABASE_URL,\n autoLoadEntities: true,\n ssl:\n process.env.NODE_ENV === 'production'\n ? { rejectUnauthorized: false }\n : false,\n}),\n```\n\n```text\nPQSSLMODE\n```\n\n```text\nrequire\n```\n\n```text\nlibpq\n```\n\n```text\noptions: { encrypt: false }\n```\n\n```text\nTypeOrmModule.forRoot({\n type: 'mssql',\n host: 'your_db_server_address',\n port: 1433,\n username: 'user',\n password: 'pwd',\n database: 'your_db_name_here',\n entities: [Subscription],\n options: { encrypt: false }\n \n})\n```\n\n```js\nssl: {\n ca: readFileSync(join(__dirname, 'assets', 'RDS.us-east-1.ca-bundle.pem')).toString()\n },\n```\n\n```text\nurl\n```\n\n```text\nusername\n```\n\n```text\npassword\n```\n\n```text\nlogging\n```\n\n```js\nimport { DataSourceOptions } from 'typeorm';\n\nconst config: DataSourceOptions = {\n type: \"mssql\",\n host: \"dev\",\n database: \"dev\",\n username: \"\",\n password: \"\",\n synchronize: false,\n logging: false,\n entities: [\n \"src/entity/**/*.ts\"\n ],\n migrations: [\n \"src/migration/**/*.ts\"\n ],\n subscribers: [\n \"src/subscriber/**/*.ts\"\n ],\n extra: {\n trustServerCertificate: true,\n }\n};\n\nexport default config;\n```\n\n```text\ntype: \"mssql\"\n```\n\n```text\nextra\n```\n\n```text\ntrustServerCertificate\n```\n\n```text\nnew DataSource({\n ... current configuration,\n ssl: true,\n extra: {\n ssl: {\n rejectUnauthorized: false,\n },\n },\n })\n```\n\n```text\nsslmode=require\n```\n\n```text\nDataSource\n```\n\n========================================\n\nComments:\n- Hello, I have the same issue. But I don't have any ssl cerificate. Do you any advice or sujestion? or is it mandatory to get a ssl certificate?. Could you helpme with this question stackoverflow.com/questions/65136834/… please.\n- If you have hosted database you want to connect to you need to download SSL certificate from that platform, you can use that certificate then. it's probably something like `ca_certificate.crt` and you can find more about it in your cloud hosting provider documentation.\n- I had a similar issue on Digitalocean. But I was using the url parameter in the typeorm config, and the url from DO contains sslmode=require at the end. It turns out that the sslmode parmeter in the url overwrites the ssl-parameter in config, s o the ca parameter was never set. See: node-postgres.com/features/ssl\n- But what's actually stored in that SSL_CERT environment variable??\n- @Musilix the contents of the .crt file you get from Digital Ocean (or whomever), with the newlines removed so it's all on one line\n- For anyone wondering where the certificate and other variables are coming from: only the DATABASE_URL environment variable will be set by default. You have to configure the other ones by yourself, see docs.digitalocean.com/products/app-platform/how-to/… There is currently an open issue when using the url property. I got it working by not using the url property and by defining each setting (e.g. host, username, ...) separately\n- It's not the greatest answer, but this does answer the actual question, the link is correct\n- on azure, you're going to need the cert as well- stackoverflow.com/a/63043606/228369","metadata":{"transformedAt":"2026-08-18T18:33:44.683Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":266,"estimatedTokens":1498}}30{"id":"stack-52187328","source":"stackoverflow","questionId":52187328,"title":"How to specify ormconfig.ts for TypeORM?","tags":["javascript","node.js","typescript","typeorm"],"text":"Title: How to specify ormconfig.ts for TypeORM?\nTags: javascript, node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have created a sample TypeORM project using the TypeORM CLI which has ormconfig.json by default:\n\n```\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"postgres\",\n \"database\": \"test\",\n \"synchronize\": false,\n \"entities\": [\n \"src/entity/**/*.ts\"\n ],\n \"migrations\": [\n \"database/migrations/**/*.ts\"\n ],\n \"subscribers\": [\n \"src/subscriber/**/*.ts\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"database/migrations\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\nthis is the directory structure:\n\n```\n-database\n -migrations\n-src\n -entity\n-ormconfig.json\n```\n\nThis creates the migrations in the database/migrations folder properly as well as executes the migrations from it.\n\nI replaced ormconfig.json with the following ormconfig.ts :\n\n```\nexport default {\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'postgres',\n database: 'test',\n synchronize: false,\n \"entities\": [\n \"src/entity/**/*.ts\"\n ],\n \"migrations\": [\n \"database/migrations/**/*.ts\"\n ],\n \"subscribers\": [\n \"src/subscriber/**/*.ts\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"database/migrations\",\n \"subscribersDir\": \"src/subscriber\"\n }\n};\n```\n\nThis however creates migrations in the root directory instead of inside database/migrations.\n\nCan anyone help me in figuring out what's missing here and how I can use ormconfig.ts to generate migrations inside the intended directory?\n\n========================================\n\nTop Answer:\nHey i up this conversation since i can propose you a solution.\n\nYou can put the following line in your `package.json` file:\n\n```\n\"typeorm\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config server/environments/database.ts\",\n```\n\nAnd your ts config must export directly the config by doing that:\n\n```\nexport = { /* your config */ };\n```\n\nAs you can see, you can also specify the path of your config. No need for your config to be at the root level of your project.\n\nHope that will help you\n\n========================================\n\nCode:\n```text\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"postgres\",\n \"database\": \"test\",\n \"synchronize\": false,\n \"entities\": [\n \"src/entity/**/*.ts\"\n ],\n \"migrations\": [\n \"database/migrations/**/*.ts\"\n ],\n \"subscribers\": [\n \"src/subscriber/**/*.ts\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"database/migrations\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\n```text\n-database\n -migrations\n-src\n -entity\n-ormconfig.json\n```\n\n```text\nexport default {\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'postgres',\n database: 'test',\n synchronize: false,\n \"entities\": [\n \"src/entity/**/*.ts\"\n ],\n \"migrations\": [\n \"database/migrations/**/*.ts\"\n ],\n \"subscribers\": [\n \"src/subscriber/**/*.ts\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"database/migrations\",\n \"subscribersDir\": \"src/subscriber\"\n }\n};\n```\n\n```text\n\"typeorm\": \"ts-node -r tsconfig-paths/register ./node_modules/.bin/typeorm\",\n\"migration:generate\": \"npm run typeorm -- migration:generate --config src/config/ormconfig.json --connection --name \",\n\"migration:run\": \"npm run typeorm -- migration:run\"\n```\n\n```text\normconfig.json\n```\n\n```text\normconfig.ts\n```\n\n```text\nimport env from './src/env';\n\nexport = {\n host: env.DB_CONFIG.host,\n type: 'mysql',\n port: env.DB_CONFIG.port,\n username: env.DB_CONFIG.username,\n password: env.DB_CONFIG.password,\n database: env.DB_CONFIG.database,\n entities: [\n 'src/**/**.entity{.ts,.js}',\n ],\n migrations: [\n 'src/database/migrations/*.ts',\n ],\n cli: {\n migrationsDir: 'src/database/migrations',\n },\n synchronize: false,\n};\n```\n\n```text\n...\n\"scripts\": {\n ...\n \"migrate:create\": \"ts-node ./node_modules/typeorm/cli.js migration:create -n\",\n \"migrate:up\": \"ts-node ./node_modules/typeorm/cli.js migration:run\",\n \"migrate:down\": \"ts-node ./node_modules/typeorm/cli.js migration:revert\"\n ...\n }\n...\n```\n\n```text\nnpm run migrate:create FileName\nnpm run migrate:up\nnpm run migrate:down\n```\n\n```text\ndefault\n```\n\n```text\normconfig.ts\n```\n\n```text\nenv.ts\n```\n\n```text\nts-node\n```\n\n```text\ntypeorm cli\n```\n\n```text\npackage.json\n```\n\n```text\n\"typeorm\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config server/environments/database.ts\",\n```\n\n```text\nexport = { /* your config */ };\n```\n\n```text\npackage.json\n```\n\n```text\n.\n├── src // Typescript files\n│ ├── entities\n│ │ └── User.ts\n│ ├── db\n│ │ └── ormconfig.ts\n│ │ ├── migrations\n│ │ │ └── ... // migration files\n├── tsconfig.json\n├── package.json\n```\n\n```text\nimport path from \"path\";\nimport { ConnectionOptions } from \"typeorm\";\n\nexport default {\n name: \"default\",\n type: \"better-sqlite3\",\n database: \":memory:\",\n synchronize: true,\n migrationsRun: true,\n dropSchema: false,\n entities: [path.join(__dirname, \"..\", \"entities\", \"**\", \"*.*\"), path.join(__dirname, \"..\", \"entities\", \"*.*\")],\n migrations: [path.join(__dirname, \"migrations\", \"*.*\")],\n cli: {\n entitiesDir: path.join(__dirname, \"..\", \"entities\"),\n migrationsDir: path.join(__dirname, \"migrations\")\n }\n} as ConnectionOptions;\n```\n\n```json\n\"scripts\": {\n \"dev\": \"ts-node-dev src/index.ts\",\n \"build\": \"tsc\",\n \"start\": \"node dist/index.js\",\n \"typeorm\": \"ts-node ./node_modules/.bin/typeorm -f ./src/db/ormconfig.ts\",\n \"migration:generate\": \"yarn run typeorm migration:generate -n\",\n \"migration:blank\": \"yarn run typeorm migration:create -n\"\n},```\n\n## Usage\n\n```bash\n# Generate a blank migration\nyarn migration:blank migration-name-here\n\n# Generate migrations from database and entities.\nyarn migration:generate\n\n# Roll back a migration using cli options.\nyarn typeorm migration:down\n```\n\n```text\nsrc/db/ormconfig.ts\n```\n\n```text\nmigrations\n```\n\n```text\nsrc/db/ormconfig.ts\n```\n\n```text\nts-node\n```\n\n```text\nsrc/db/ormconfig.ts\n```\n\n```text\nsrc/db/package.json\n```\n\n```text\nimport { ConnectionOptions } from 'typeorm';\n\n// Check typeORM documentation for more information.\nconst config: ConnectionOptions = {\n type: 'postgres',\n host: process.env.SQL_IP, // localhost\n port: process.env.SQL_PORT,// 5432\n username: process.env.SQL_USER, // databse login role username\n password: process.env.SQL_PASSWORD, // database login role password\n database: process.env.SQL_DATABASE, // db name\n\n // entities name should be **.entity.ts\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n\n // We are using migrations, synchronize should be set to false.\n // synchronize: process.env.TYPEORM_SYNCHRONIZE\n // ? process.env.TYPEORM_SYNCHRONIZE.toLowerCase() === 'true'\n // : false,\n synchronize: false,\n\n // Run migrations automatically,\n // you can disable this if you prefer running migration manually.\n migrationsRun: false,\n\n logging: false,\n // logger: 'advanced-console',\n\n // Allow both start:prod and start:dev to use migrations\n // __dirname is either dist or src folder, meaning either\n // the compiled js in prod or the ts in dev.\n migrations: [__dirname + '/migrations/*{.ts,.js}'],\n cli: {\n // Location of migration should be inside src folder\n // to be compiled into dist/ folder.\n migrationsDir: 'src/database/migrations'\n }\n};\n\nexport = config;\n```\n\n```text\n\"typeorm\": \"ts-node --files -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config src/database/config.ts\"\n\"db:migrate\": \"npm run typeorm migration:run\",\n\"db:create-migration\": \"npm run typeorm migration:create -- -n\",\n```\n\n```json\n{\n \"scripts\": {\n \"typeorm\": \"yarn node -r ts-node/register/transpile-only $(yarn bin typeorm)\",\n \"generate-migration\": \"yarn typeorm --config ormconfig.ts migration:generate --check\",\n }\n \"dependencies\": {\n \"typeorm\": \"^0.2.41\",\n }\n \"devDependencies\": {\n \"ts-node\": \"^10.4.0\",\n }\n}\n```\n\n```text\n/* eslint-disable no-process-env */\nimport dotenv from 'dotenv';\nimport { SnakeNamingStrategy } from 'typeorm-naming-strategies';\n\ndotenv.config();\ndotenv.config({ path: './.env.local' });\n\nexport = {\n type: 'postgres',\n host: process.env.DB_HOST,\n port: process.env.DB_PORT,\n username: process.env.DB_USERNAME,\n password: process.env.DB_PASSWORD,\n database: process.env.DB_NAME,\n entities: ['src/infrastructure/persistence/**/*.entity.ts'],\n migrations: ['src/infrastructure/persistence/migrations/**/*.{ts,js}'],\n cli: {\n migrationsDir: 'src/infrastructure/persistence/migrations',\n },\n namingStrategy: new SnakeNamingStrategy(),\n};\n```\n\n```text\nimport { ConnectionOptions } from 'typeorm'; \nexport const baseConfig: ConnectionOptions = {\n synchronize: true, // TODO turn false after initial setup i.e. when moving to migrations\n type: 'mysql',\n host: 'localhost',\n port: 3306,\n username: 'xxx',\n password: 'xxx',\n database: 'xxx',\n entities: ['dist/Entities/**/**.entity.js'],\n migrations: ['dist/Migrations/*.js'],\n cli: {\n entitiesDir: 'dist/Entities/**/*.js',\n migrationsDir: 'dist/Migrations/*.js'\n }\n };\n```\n\n```text\n\"scripts\": {\n \"build\": \"rimraf ./dist && tsc\",\n \"start\": \"npm run build && node dist/index.js\",\n \"dev\": \"nodemon src/index.ts\",\n \"format:prettier\": \"prettier --config .prettierrc 'src/**/*.ts' --write\",\n \"lint\": \"eslint . --ext .ts\",\n \"lint:fix\": \"eslint . --ext .ts --fix\",\n \"test\": \"jest --runInBand\"\n },\n```\n\n```text\nomrconfig.json\n```\n\n```text\nomrconfig.ts\n```\n\n```text\nnpm i -g typeorm\n```\n\n```text\n\"typeorm\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config server/environments/migrations.ts\"\n```\n\n```text\n\"migrate:create\": \"typeorm migration:create \\\"./typeorm/migrations/\"\n```\n\n```text\nnpm run migrate:create -n {migrationName}\n```\n\n========================================\n\nComments:\n- I have an issue with this now. have you fixed this?\n- Since the `typeorm` package has its `bin` mapped already to `cli.js` you can omit the `cli.js` in those commands. So it's just `ts-node ./node_modules/typeorm ...`\n- Can you put you .env file here it would help Thank you.\n- Do you have working repo for the example you provided?.\n- Sorry, I don't have one exposed as public.\n- could you please please add a minimal working example repo?\n- Check github link in Solutions section. I have updated the answer to include github link.","metadata":{"transformedAt":"2026-08-18T18:33:44.684Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":39,"totalLines":484,"estimatedTokens":2674}}31{"id":"stack-56311203","source":"stackoverflow","questionId":56311203,"title":"Can I map entity field names to alias column names in TypeORM?","tags":["nestjs","typeorm"],"text":"Title: Can I map entity field names to alias column names in TypeORM?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am in the process of migrating from Rails to NestJs with TypeORM.\nFor historical reasons, table names and column names in Rails are `snaked_cased` - I don't want to copy this nuisance to our NestJs/React side.\n\nCan I create entity fields in NestJS (typeorm) called `firstName` but are mapped to a column named `first_name` in my DB?\n\nMy table\n\n```\n+-------------+--------------+----------------------------+\n| system_users |\n+-------------+--------------+----------------------------+\n| id | int(11) | PRIMARY KEY AUTO_INCREMENT |\n| first_name | varchar(100) | |\n| last_name | varcahr(100) | |\n+-------------+--------------+----------------------------+\n```\n\nMy User Entity Class\n\n```\nimport { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity({ name: 'system_users' })\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ length: 255 })\n first_name: string; // <-- I WANT THIS TO BE firstName (camelCased)\n\n @Column({ length: 255 })\n last_name: string; // <-- I WANT THIS TO BE lastName (camelCased)\n}\n```\n\n========================================\n\nTop Answer:\nIf anyone else comes across this issue, know that TypeORM supports naming strategies.\n\nAnd there is even a package for a snake case naming strategy\n\n========================================\n\nCode:\n```sql\n+-------------+--------------+----------------------------+\n| system_users |\n+-------------+--------------+----------------------------+\n| id | int(11) | PRIMARY KEY AUTO_INCREMENT |\n| first_name | varchar(100) | |\n| last_name | varcahr(100) | |\n+-------------+--------------+----------------------------+\n```\n\n```js\nimport { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity({ name: 'system_users' })\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ length: 255 })\n first_name: string; // <-- I WANT THIS TO BE firstName (camelCased)\n\n @Column({ length: 255 })\n last_name: string; // <-- I WANT THIS TO BE lastName (camelCased)\n}\n```\n\n```text\nsnaked_cased\n```\n\n```text\nfirstName\n```\n\n```text\nfirst_name\n```\n\n```js\n@Entity({ name: 'system_users' })\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ length: 255, name: \"first_name\" })\n firstName: string; \n\n @Column({ length: 255, name: \"last_name\" })\n lastName: string; \n}\n```\n\n```text\n@Column\n```\n\n```text\nname\n```\n\n========================================\n\nComments:\n- This was 100% identical to what I was looking as well. Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:44.684Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":114,"estimatedTokens":675}}32{"id":"stack-51537780","source":"stackoverflow","questionId":51537780,"title":"TypeORM: Joining when we have one to many and many to one relationship","tags":["nestjs","typeorm"],"text":"Title: TypeORM: Joining when we have one to many and many to one relationship\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\n```\n@Entity()\nexport class User {\n @PrimaryColumn()\n id: string;\n\n @Column({unique: true})\n username: string;\n\n @Column({unique: true})\n email: string;\n\n @OneToMany(type => Post, post => post.id)\n posts: Post[];\n}\n\n@Entity()\nexport class Post {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(type => User, user => user.posts)\n @JoinColumn({name: 'user_id'})\n user: User;\n\n @OneToMany(type => Image, image => image.id)\n images: Image[];\n}\n \n@Entity()\nexport class Image {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(type => Post, post => post.images)\n @JoinColumn({name : 'post_id'})\n post: Post;\n}\n```\n\nI have these 3 entities and I want to make a query to have all the posts from a user and for that post to get all the images. I am trying to do this using the following code:\n\n```\nreturn await this.postRepository.createQueryBuilder(\"post\")\n .innerJoinAndSelect(\"post.images\", \"image\")\n .where(\"user_id = :userId\", {userId: id})\n .getMany();\n```\n\nAnd I get the following error:\n\n```\nCannot read property 'joinColumns' of undefined\n```\n\nI also tried this instead of the `.innerJoin` from above:\n\n```\n.innerJoinAndSelect(Image, \"image\", \"image.post_id = post.id\")\n```\n\nThis way I don't get that error anymore, but as a result I get only the post and I don't get the images from it\n\n========================================\n\nTop Answer:\n```\n@Entity()\nexport class User {\n\n @OneToMany(type => Post, post => post.user)\n posts: Post[];\n}\n\n@Entity()\nexport class Post {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n user_id: number;\n\n @ManyToOne(type => User)\n @JoinColumn({name: 'user_id', referencedColumnName: 'id'})\n user: User;\n\n @OneToMany(type => Image, image => image.post)\n images: Image[];\n}\n\n@Entity()\nexport class Image {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n post_id: number;\n\n @ManyToOne(type => Post)\n @JoinColumn({name : 'post_id', referencedColumnName: 'id'})\n post: Post;\n}\n```\n\nTry this\n\n========================================\n\nCode:\n```ts\n@Entity()\nexport class User {\n @PrimaryColumn()\n id: string;\n\n @Column({unique: true})\n username: string;\n\n @Column({unique: true})\n email: string;\n\n @OneToMany(type => Post, post => post.id)\n posts: Post[];\n}\n\n@Entity()\nexport class Post {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(type => User, user => user.posts)\n @JoinColumn({name: 'user_id'})\n user: User;\n\n @OneToMany(type => Image, image => image.id)\n images: Image[];\n}\n \n@Entity()\nexport class Image {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(type => Post, post => post.images)\n @JoinColumn({name : 'post_id'})\n post: Post;\n}\n```\n\n```ts\nreturn await this.postRepository.createQueryBuilder(\"post\")\n .innerJoinAndSelect(\"post.images\", \"image\")\n .where(\"user_id = :userId\", {userId: id})\n .getMany();\n```\n\n```text\nCannot read property 'joinColumns' of undefined\n```\n\n```text\n.innerJoinAndSelect(Image, \"image\", \"image.post_id = post.id\")\n```\n\n```text\n.innerJoin\n```\n\n```js\n@OneToMany(type => Image, image => image.id)\nimages: Image[];\n```\n\n```js\n@OneToMany(type => Image, image => image.post)\nimages: Image[];\n```\n\n```js\n@OneToMany(type => Post, post => post.id)\nposts: Post[];\n```\n\n```js\n@OneToMany(type => Post, post => post.user)\nposts: Post[];\n```\n\n```js\nreturn await this.postRepository.find({\n relations: ['images', 'user'],\n where: { user: { id: id } },\n});\n```\n\n```text\nimage.id\n```\n\n```text\nimage.post\n```\n\n```text\npost.id\n```\n\n```text\npost.user\n```\n\n```text\n@JoinColumn()\n```\n\n```text\n@JoinColumn\n```\n\n```text\n@ManyToOne\n```\n\n```text\n@OneToMany\n```\n\n```text\n@OneToMany\n```\n\n```text\n@ManyToOne\n```\n\n```text\n@OneToMany\n```\n\n```text\n@ManyToOne\n```\n\n```text\n@ManyToOne\n```\n\n```text\n@Entity()\nexport class User {\n\n @OneToMany(type => Post, post => post.user)\n posts: Post[];\n}\n\n@Entity()\nexport class Post {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n user_id: number;\n\n @ManyToOne(type => User)\n @JoinColumn({name: 'user_id', referencedColumnName: 'id'})\n user: User;\n\n @OneToMany(type => Image, image => image.post)\n images: Image[];\n}\n\n@Entity()\nexport class Image {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n post_id: number;\n\n @ManyToOne(type => Post)\n @JoinColumn({name : 'post_id', referencedColumnName: 'id'})\n post: Post;\n}\n```\n\n========================================\n\nComments:\n- How is it going? did you solve the probelm?\n- This worked. A column with the foreign key was to be added. Thanks a lot\n- Using this I get : \"'type' is declared but its value is never read.\"\n- referencedColumnName: 'id' works for me!\n- If `@OneToMany` and `@ManyToOne` are matched, no extra parameter is needed. `@JoinColumn({name: 'user_id', referencedColumnName: 'id'})` `@JoinColumn()` // auto join\n- Using this method I get an error: 'type' is declared but its value is never read.\n- You should be able to sort that out by replacing 'type' with either () or _ (Empty parentheses or underscore) to let the typescript compiler know you do not want to use it. You may find more info in this answer here stackoverflow.com/a/41086381/10952954\n- The problem with the TypeORM documentation is that it assumes you're using the sync feature, so the library *creates* the join column so it knows which one is it. But it doesn't explain clearly how to deal with non-synced already existing tables.","metadata":{"transformedAt":"2026-08-18T18:33:44.684Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":305,"estimatedTokens":1361}}33{"id":"stack-72549668","source":"stackoverflow","questionId":72549668,"title":"How to do custom repository using TypeORM (MongoDB) in NestJS?","tags":["typescript","mongodb","nestjs","typeorm"],"text":"Title: How to do custom repository using TypeORM (MongoDB) in NestJS?\nTags: typescript, mongodb, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a question. With `@EntityRepository` decorator being marked as deprecated in `typeorm@^0.3.6`, what is now the recommended or TypeScript-friendly way to create a custom repository for an entity in NestJS? A custom repository before would look like this:\n\n```\n// users.repository.ts\nimport { EntityRepository, Repository } from 'typeorm';\nimport { User } from './user.entity';\n\n@EntityRepository(User)\nexport class UsersRepository extends Repository {\n async createUser(firstName: string, lastName: string): Promise {\n const user = this.create({\n firstName,\n lastName,\n });\n\n await this.save(user);\n\n return user;\n }\n}\n```\n\nAnd since NestJS is by default configured with TypeScript support, I will be able to call `usersRepository.createUser()` without an issue in a service like this:\n\n```\n// users.service.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { User } from './user.entity';\nimport { UsersRepository } from './users.repository';\n\n@Injectable()\nexport class UsersService {\n constructor(\n @InjectRepository(UsersRepository)\n private readonly usersRepository: UsersRepository,\n ) {}\n\n async createUser(firstName: string, lastName: string): Promise {\n return this.usersRepository.createUser(firstName, lastName);\n }\n}\n```\n\nThis is how the modules would import the custom repository:\n\n```\n// users.module.ts\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UsersController } from './users.controller';\nimport { UsersRepository } from './users.repository';\nimport { UsersService } from './users.service';\n\n@Module({\n imports: [TypeOrmModule.forFeature([UsersRepository])],\n controllers: [UsersController],\n providers: [UsersService],\n exports: [UsersService],\n})\nexport class UsersModule {}\n```\n\nAlso the reason why I mentioned MongoDB here is because I tried using `typeorm@0.2` where `@EntityRepository` is still supported but I receive an error when I tried to import it in the module stating `Repository not found` or something. Do note, if I chose `postgresql` as my database in TypeORM with the same changes above, I don't have this issue. Hence I went to check the latest only to find out it is already deprecated, I also didn't find any example in NestJS documentation.\n\n========================================\n\nTop Answer:\nThe way you can create a custom repository for mongo in `TypeORM` it with the following way:\n\n**users.repository.ts**\n\nHere instead of using `@EntityRepository` you will use the `@Injectable` decorator, and for inject, the `schema` will use MongoRepository\n\n```\n// users.repository.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { MongoRepository } from 'typeorm';\nimport { User } from './user.entity';\n@Injectable()\nexport class UsersRepository {\n constructor(\n @InjectRepository(User)\n private readonly usersRepository: MongoRepository,\n ) {}\n\n async createUser(firstName: string, lastName: string): Promise {\n const user = new User({\n firstName,\n lastName,\n });\n\n await this.usersRepository.save(user);\n\n return user;\n }\n \n\n //write other helpful methods here(find, delete, etc...)\n\n}\n```\n\n**users.service.ts**\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { User } from './user.entity';\nimport { UsersRepository } from './users.repository';\n\n@Injectable()\nexport class UsersService {\n constructor(private readonly usersRepository: UsersRepository) {}\n\n async createUser(firstName: string, lastName: string): Promise {\n return this.usersRepository.createUser(firstName, lastName);\n }\n}\n```\n\n**users.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UsersController } from './users.controller';\nimport { UsersRepository } from './users.repository';\nimport { UsersService } from './users.service';\nimport { User } from './user.entity';\nimport { UsersRepository } from './database/repository/UsersRepository';\n@Module({\n imports: [TypeOrmModule.forFeature([User])],\n controllers: [UsersController],\n providers: [UsersRepository, UsersService],\n exports: [UsersService],\n})\nexport class UsersModule {}\n```\n\n========================================\n\nCode:\n```text\n// users.repository.ts\nimport { EntityRepository, Repository } from 'typeorm';\nimport { User } from './user.entity';\n\n@EntityRepository(User)\nexport class UsersRepository extends Repository<User> {\n async createUser(firstName: string, lastName: string): Promise<User> {\n const user = this.create({\n firstName,\n lastName,\n });\n\n await this.save(user);\n\n return user;\n }\n}\n```\n\n```text\n// users.service.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { User } from './user.entity';\nimport { UsersRepository } from './users.repository';\n\n@Injectable()\nexport class UsersService {\n constructor(\n @InjectRepository(UsersRepository)\n private readonly usersRepository: UsersRepository,\n ) {}\n\n async createUser(firstName: string, lastName: string): Promise<User> {\n return this.usersRepository.createUser(firstName, lastName);\n }\n}\n```\n\n```text\n// users.module.ts\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UsersController } from './users.controller';\nimport { UsersRepository } from './users.repository';\nimport { UsersService } from './users.service';\n\n@Module({\n imports: [TypeOrmModule.forFeature([UsersRepository])],\n controllers: [UsersController],\n providers: [UsersService],\n exports: [UsersService],\n})\nexport class UsersModule {}\n```\n\n```text\n@EntityRepository\n```\n\n```text\ntypeorm@^0.3.6\n```\n\n```text\nusersRepository.createUser()\n```\n\n```text\ntypeorm@0.2\n```\n\n```text\n@EntityRepository\n```\n\n```text\nRepository not found\n```\n\n```text\npostgresql\n```\n\n```text\nimport {DataSource, Repository} from 'typeorm';\nimport {Injectable} from '@nestjs/common';\nimport {Team} from '@Domain/Team/Models/team.entity';\n\n@Injectable()\nexport class TeamRepository extends Repository<Team>\n{\n constructor(private dataSource: DataSource)\n {\n super(Team, dataSource.createEntityManager());\n }\n\n /**\n * Add a basic where clause to the query and return the first result.\n */\n async firstWhere(column: string, value: string | number, operator = '='): Promise<Team | undefined>\n {\n return await this.createQueryBuilder()\n .where(`Team.${column} ${operator} :value`, {value: value})\n .getOne();\n }\n}\n```\n\n```text\nimport {Injectable} from '@nestjs/common';\nimport {Team} from '@Domain/Team/Models/team.entity';\nimport {TeamRepository} from '@Domain/Team/Repositories/team.repository';\n\n@Injectable()\nexport class TeamService\n{\n constructor(\n private teamRepository: TeamRepository,\n )\n {\n }\n\n async create(): Promise<Team>\n {\n const team: Team = await this.teamRepository.firstWhere('id', 1);\n\n return this.teamRepository.save(team);\n }\n}\n```\n\n```text\nimport {Module} from '@nestjs/common';\nimport {TeamService} from '@Domain/Team/Services/team.service';\nimport {TypeOrmModule} from '@nestjs/typeorm';\nimport {Team} from '@Domain/Team/Models/team.entity';\nimport {TeamRepository} from '@Domain/Team/Repositories/team.repository';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Team])],\n exports: [TeamService],\n providers: [TeamService, TeamRepository],\n })\nexport class TeamModule\n{\n}\n```\n\n```text\n// users.repository.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { MongoRepository } from 'typeorm';\nimport { User } from './user.entity';\n@Injectable()\nexport class UsersRepository {\n constructor(\n @InjectRepository(User)\n private readonly usersRepository: MongoRepository<User>,\n ) {}\n\n async createUser(firstName: string, lastName: string): Promise<User> {\n const user = new User({\n firstName,\n lastName,\n });\n\n await this.usersRepository.save(user);\n\n return user;\n }\n \n\n //write other helpful methods here(find, delete, etc...)\n\n\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { User } from './user.entity';\nimport { UsersRepository } from './users.repository';\n\n@Injectable()\nexport class UsersService {\n constructor(private readonly usersRepository: UsersRepository) {}\n\n async createUser(firstName: string, lastName: string): Promise<User> {\n return this.usersRepository.createUser(firstName, lastName);\n }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UsersController } from './users.controller';\nimport { UsersRepository } from './users.repository';\nimport { UsersService } from './users.service';\nimport { User } from './user.entity';\nimport { UsersRepository } from './database/repository/UsersRepository';\n@Module({\n imports: [TypeOrmModule.forFeature([User])],\n controllers: [UsersController],\n providers: [UsersRepository, UsersService],\n exports: [UsersService],\n})\nexport class UsersModule {}\n```\n\n```text\nTypeORM\n```\n\n```text\n@EntityRepository\n```\n\n```text\n@Injectable\n```\n\n```text\nschema\n```\n\n```text\n// task.entity.ts\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Task {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column()\n title: string;\n\n @Column()\n description: string;\n}\n```\n\n```text\n// tasks.repository.ts\nimport { Injectable } from '@nestjs/common';\nimport { DataSource, Repository } from 'typeorm';\nimport { Task } from './tast.entity';\n\n@Injectable()\nexport class TasksRepository extends Repository<Task> {\n constructor(dataSource: DataSource) {\n super(Task, dataSource.createEntityManager());\n }\n}\n```\n\n```text\n//tasks.module.ts\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { TasksController } from './tasks.controller';\nimport { TasksService } from './tasks.service';\nimport { Task } from './tast.entity';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Task])], // NOTICE: HERE\n controllers: [TasksController], // NOTICE: HERE\n providers: [TasksService],\n})\nexport class TasksModule {}\n```\n\n```text\n@Injectable()\nexport class TasksService {\n constructor(\n @InjectRepository(Task) // NOTICE: here\n private readonly tasksRepository: TasksRepository,\n ) {}\n\n async getTaskById(id: string): Promise<Task> {\n const task = this.tasksRepository.findOne({\n where: {\n id,\n },\n });\n\n if (!task) {\n throw new NotFoundException(`Task with id ${id} not found`);\n }\n\n return task;\n }\n}\n```\n\n```text\n// users.repository.ts\nimport { Repository } from 'typeorm';\nimport { EntityRepository } from 'nestjs-typeorm-custom-repository';\n\nimport { User } from './user.entity';\n\n@EntityRepository(User)\nexport class UsersRepository extends Repository<User> {}\n```\n\n```text\n// users.service.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { User } from './user.entity';\nimport { UsersRepository } from './users.repository';\n\n@Injectable()\nexport class UsersService {\n constructor(\n private readonly usersRepository: UsersRepository,\n ) {}\n ...\n }\n}\n```\n\n```text\n// users.module.ts\nimport { Module } from '@nestjs/common';\nimport { CustomRepositoryModule } from 'nestjs-typeorm-custom-repository';\n\nimport { UsersController } from './users.controller';\nimport { UsersRepository } from './users.repository';\nimport { UsersService } from './users.service';\n\n@Module({\n imports: [CustomRepositoryModule.forFeature([UsersRepository])],\n controllers: [UsersController],\n providers: [UsersService],\n exports: [UsersService],\n})\nexport class UsersModule {}\n```\n\n```text\nexport const UserRepository = dataSource.getRepository(User).extend({\n findByName(firstName: string, lastName: string) {\n return this.createQueryBuilder(\"user\")\n .where(\"user.firstName = :firstName\", { firstName })\n .andWhere(\"user.lastName = :lastName\", { lastName })\n .getMany()\n },\n})\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { PlaygroundEntity } from 'src/entities/playground.entity';\nimport { Repository } from 'typeorm';\n\n@Injectable()\nexport class PlaygroundRepository {\n constructor(\n @InjectRepository(PlaygroundEntity)\n private readonly _repository: Repository<PlaygroundEntity>,\n ) {}\n\n public get _() {\n return this._repository;\n }\n\n async findWithCriteria() {\n return this._.find({ where: { datecolumn: new Date() } });\n }\n}\n```\n\n```js\nimport { Inject, Injectable } from '@nestjs/common';\nimport { PlaygroundRepository } from './repositories/pg.repository';\n\n@Injectable()\nexport class AppService {\n constructor(\n @Inject(PlaygroundRepository)\n private pgRepository: PlaygroundRepository,\n ) {}\n\n async start() {\n const customMethod = await this.pgRepository.findWithCriteria();\n\n const defaultMethod = await this.pgRepository._.find();\n }\n}\n```\n\n========================================\n\nComments:\n- Hey, thanks for this. I think it's almost there to what I was looking for! But there's one issue with this, it seems like it will only expose one function from `UsersRepository` which is the `createUser()` I created. But I can't use common functions of a repository like `.find()`, `.updateOne()`, etc with the custom `UsersRepository` in the `UsersService`, how to make it such that it would be an extension of a repository?\n- @unspeakable29 the best way to do that it creating an abstract class base repository, in this base repository implement all that you need(find(), findById(), findOne(), etc..), and in UsersRepository just extend the BaseRepository.\n- I see. I guess that's the best way huh. It used to be easier with `EntityRepository` but oh well. Thanks for the help! 🙏🏻\n- Thanks Nick, this is what I was looking for! It works on MongoDB too.\n- Thank you @Nick This was so helpful! It does work with mongo too, obviously just swapping out the extension in the repository to extend from MongoRepository instead of a regular one. I was struggling with this for like a week thank you for posting!\n- Thank you Nick, got this working. Seems much simpler than an alternative approach outlined here - gist.github.com/anchan828/9e569f076e7bc18daf21c652f7c3d012\n- Great job on figuring this out. Really appreciate it :).\n- How can we write unit test for the repository with this? I need to provide dependency for data source\n- @IshikaJain did you managed to find a proper solution? I saw this solution for unit tests (docs.nestjs.com/techniques/database#testing), but I'm struggling with e2e tests.\n- I 'm also really struggling to find a way to test team.repository.ts with jest as others have. I keep getting error like: Nest can't resolve dependencies of the XYZRepository (?). Please make sure that the argument DataSource at index [0] is available in the TypeOrmModule context. If anyone has managed to do it, please .\n- I meant, I'm trying to test a service that uses the team.repository.ts\n- Inside tests using jest, dataSource will be undefined\n- Hi, was there any solution for testing with this method ?\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:44.684Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":567,"estimatedTokens":4030}}34{"id":"stack-43726739","source":"stackoverflow","questionId":43726739,"title":"Is it possible to 'protect' a property and exclude it from select statements","tags":["typeorm"],"text":"Title: Is it possible to 'protect' a property and exclude it from select statements\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI'd like to protect certain properties on the data-layer level. For example I'd like to protect the password hash I store in the database for a user, so that it doesn't show up in arbitrary `select`-statements.\n\nThis way only when it's explicitly requested in a `select property, property2` statement.\n\n========================================\n\nTop Answer:\nTypeORM goes well with routing-controllers so you should use it, behind the scenes it uses class-transformer to serialize and deserialize your data. So you can use the `@Exclude` decorator from that library to prevent certain properties being sent down to the clients.\n\nIt also uses the class-validator library to validate the data when specifying it as the type in the controller functions. These are powerful toys. Here is a small example of how you can leverage both:\n\n```\nimport { Entity, Column, PrimaryGeneratedColumn, Index, OneToMany } from \"typeorm\";\nimport { Exclude, Expose } from \"class-transformer\";\nimport { IsNotEmpty, IsEmail, MinLength, MaxLength, Min, Max, IsNumber, IsString } from \"class-validator\";\n\n@Entity()\nexport class User extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n @IsNotEmpty()\n @IsEmail()\n @Index({ unique: true })\n email: string;\n\n @Exclude()\n @Column()\n passwordHash: string;\n\n @Column()\n @IsNotEmpty()\n @IsString()\n firstName: string;\n\n @Column()\n @IsNotEmpty()\n @IsString()\n lastName: string;\n\n @Column({ type: 'integer', default: Gender.NotSpecified })\n @IsNumber()\n @Min(1)\n @Max(3)\n gender: Gender;\n\n @Expose()\n get admin() {\n return this.role == Role.Admin;\n }\n\n @Expose()\n get stylist() {\n return this.role == Role.Stylist;\n }\n}\n```\n\nIf you use an another server-side library you can still take advantage of *class-transformer* and *class-validator*. You just need to call the validate function manually in your routes, for example for restify you can write:\n\n```\nimport {validate } from \"class-validator\";\nimport {plainToClass} from \"class-transformer\";\n// ... more code\n\nserver.post('/hello', function create(req, res, next) {\n let bodyJSON = parseBodyTheWayYouWant(req.body);\n let post = plainToClass(bodyJSON);\n validate(post)\n return next();\n});\n```\n\n========================================\n\nCode:\n```text\nselect\n```\n\n```text\nselect property, property2\n```\n\n```js\n@Column({ select: false })\npassword: string;\n```\n\n```js\nconst user = await getRepository(User)\n .createQueryBuilder()\n .addSelect('password')\n .getOne()\n```\n\n```text\nselect: false\n```\n\n```text\nimport { Entity, Column, PrimaryGeneratedColumn, Index, OneToMany } from \"typeorm\";\nimport { Exclude, Expose } from \"class-transformer\";\nimport { IsNotEmpty, IsEmail, MinLength, MaxLength, Min, Max, IsNumber, IsString } from \"class-validator\";\n\n@Entity()\nexport class User extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n @IsNotEmpty()\n @IsEmail()\n @Index({ unique: true })\n email: string;\n\n @Exclude()\n @Column()\n passwordHash: string;\n\n @Column()\n @IsNotEmpty()\n @IsString()\n firstName: string;\n\n @Column()\n @IsNotEmpty()\n @IsString()\n lastName: string;\n\n @Column({ type: 'integer', default: Gender.NotSpecified })\n @IsNumber()\n @Min(1)\n @Max(3)\n gender: Gender;\n\n\n @Expose()\n get admin() {\n return this.role == Role.Admin;\n }\n\n @Expose()\n get stylist() {\n return this.role == Role.Stylist;\n }\n}\n```\n\n```text\nimport {validate } from \"class-validator\";\nimport {plainToClass} from \"class-transformer\";\n// ... more code\n\nserver.post('/hello', function create(req, res, next) {\n let bodyJSON = parseBodyTheWayYouWant(req.body);\n let post = plainToClass(bodyJSON);\n validate(post)\n return next();\n});\n```\n\n```text\n@Exclude\n```\n\n```text\nasync findUsers(){\n const users:User[] = await userRepository.find();\n\n return users.map(user => { \n delete user.password;\n delete user.salt;\n return user;\n }) ;\n}\n```\n\n```text\nasync findUserById(id){\n const user:User = await userRepository.findOne(id);\n delete user.password;\n return user;\n}\n```\n\n```text\nconst data = await this.a.create(A);\nawait this.a.save(data);\nreturn await this.a.findOneBy({ xx });\n```\n\n```text\n@Column({select:false}) // Key points for database queries [await this.a.findOneBy({ xx })]\nxxx: string\n```\n\n========================================\n\nComments:\n- This looks promising. But this is a non-documented feature right now, correct? At least not documented in TypeORM\n- I totally miss read your question. I have updated my answer to clarify this is the part or routing-conrollers which you really should use btw. Awesome product, and two goes well. (Take a look at typedi as well.)\n- Too bad I'm using restifyjs and not Koa or Expressjs\n- updated my answer with how to use it with different enviroments\n- goolged. found this. went to upvote. Apparently I already upvoted years ago, lol\n- This is the correct answer to the question. Here is a link to the docs: hidden-columns. Nonetheless the accepted answer is a valid solution.\n- Is there a way to achieve this with a @VirtualColumn ?","metadata":{"transformedAt":"2026-08-18T18:33:44.684Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":215,"estimatedTokens":1296}}35{"id":"stack-52155315","source":"stackoverflow","questionId":52155315,"title":"TypeORM cannot find entities if entity directory was not set in configuration files","tags":["javascript","typescript","typeorm"],"text":"Title: TypeORM cannot find entities if entity directory was not set in configuration files\nTags: javascript, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using TypeORM with the fallowing configuration file: ormconfig.json\n\n```\n{\n\"type\": \"mysql\",\n\"host\": \"localhost\",\n\"port\": 3306,\n\"username\": \"root\",\n\"password\": \"my-secret-pw\",\n\"database\": \"mytestdb\",\n}\n```\n\nMy Entities files are stored on the ./src/bar/entity directory.\nI always get the following error:\n\n RepositoryNotFoundError: No repository for \"myTable\" was found. Looks like this entity is not registered in current \"default\" connection?\n\nThe Entity is found when I manually add the directory to the configuration file:\n\n```\n{\n...\n\"entities\": [\"src/bar/entity/**/*.ts\"]\n}\n```\n\nMy Entity is defined like:\n\n```\n@Entity('myTable')\nexport default class MyTable {\n @PrimaryGeneratedColumn()\n public id: number;\n ...\n```\n\nHow can I allow the TypeORM to find those entities without setting manually in the configuration file for each directory?\n\n========================================\n\nTop Answer:\nFor me it helped to include also `src` directory to `ormconfig.json`:\n\n```\n\"entities\": [\n \"dist/**/*.entity{.ts,.js}\",\n \"src/**/*.entity{.ts,.js}\"\n ],\n```\n\n========================================\n\nCode:\n```text\n{\n\"type\": \"mysql\",\n\"host\": \"localhost\",\n\"port\": 3306,\n\"username\": \"root\",\n\"password\": \"my-secret-pw\",\n\"database\": \"mytestdb\",\n}\n```\n\n```text\n{\n...\n\"entities\": [\"src/bar/entity/**/*.ts\"]\n}\n```\n\n```text\n@Entity('myTable')\nexport default class MyTable {\n @PrimaryGeneratedColumn()\n public id: number;\n ...\n```\n\n```text\n{\n...\n\"entities\": [\"src/bar/entities/**/*.ts\"]\n}\n```\n\n```text\nimport {User} from \"./payment/entity/User\";\nimport {Post} from \"./blog/entity/Post\";\n\n{\n...\n\"entities\": [User, Post]\n}\n```\n\n```text\nentities\n```\n\n```text\n{\n ...\n \"entities\": [\"src/**/*{.entity.ts}\"],\n}\n```\n\n```text\nfoo.entity.ts\n```\n\n```text\nfoo.service.ts\n```\n\n```text\n{\n ...\n entities: [join(__dirname, '/../**/**.entity{.ts,.js}')],\n}\n```\n\n```text\n\"entities\": [\n \"dist/**/*.entity{.ts,.js}\",\n \"src/**/*.entity{.ts,.js}\"\n ],\n```\n\n```text\nsrc\n```\n\n```text\normconfig.json\n```\n\n```text\nentities: [\n this.isProduction() ? \n path.join(__dirname, '../**/**.entity{.ts,.js}') : '**/*.entity{.ts,.js}',\n],\n\n// ....\n\nprivate isProduction(): boolean {\n const mode = this.configService.get('NODE_ENV');\n return mode !== 'development';\n}\n```\n\n```js\nentities: [\n path.join(\n __dirname,\n process.env.NODE_ENV === 'development' ?\n '/**/*.entity{.ts,.js}' :\n '/**/*.entity.js', // afaik building stuffs are js-only\n ),\n]\n```\n\n```js\n//app.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n ...\n autoLoadEntities: true,\n }),\n ],\n})\nexport class AppModule {}\n```\n\n```js\n//user.module.ts\n@Module({\n \n imports: [\n /* Here, User and ForgotPasswordToken entities are being registered */\n TypeOrmModule.forFeature([User, ForgotPasswordToken])\n ],\n providers: [UsersService],\n controllers: [UsersController],\n})\nexport class UsersModule {}\n```\n\n```text\nautoLoadEntities: true\n```\n\n```text\nforFeature()\n```\n\n```text\nforFeature()\n```\n\n```text\n/../**/*.entity.{ts,js}\n```\n\n========================================\n\nComments:\n- The second option is not possible using a configuration file, am I correct?. How can i load those entities separately?\n- I think you mean it's not possible with `ormconfig.json` just declare the file as `ormconfig.js` which module.exports the config object. typeorm.io/#/using-ormconfig/using-ormconfigjs\n- It makes nosense to have different floders for enties if you divided projects into app. Normally If project gonna huge I will prefer to make db as seperate mini-project and have my all entities in one entity folder only. and sub divide that entity folder according to app name\n- For me, removing the slash like so: `${__dirname}../**/*.entity{.ts,.js}` made it work. I'm the project in a monorepo, so that might be why it was needed in the first place.\n- simplifying {src, dist}/**/*.entity{.ts,.js}\n- It showed the following error in me `SyntaxError: Cannot use import statement outside a module`\n- interesting -- why was this necessary\n- Note that during testing, `NODE_ENV` will be `test`. And your `isProduction` will return `true`","metadata":{"transformedAt":"2026-08-18T18:33:44.684Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":226,"estimatedTokens":1097}}36{"id":"stack-62879810","source":"stackoverflow","questionId":62879810,"title":"EntityMetadataNotFound: No metadata for \"Task\" was found - NestJS","tags":["javascript","node.js","orm","nestjs","typeorm"],"text":"Title: EntityMetadataNotFound: No metadata for \"Task\" was found - NestJS\nTags: javascript, node.js, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am learning the NestJS course from Udemy https://www.udemy.com/course/nestjs-zero-to-hero.\n\nAnd I am stuck with a strange issue and I have tried many things but nothing seems to be working. Here is the issue and complete code that I have.\n\n**Error that I am getting**\n\nhttps://i.sstatic.net/sW23F.png\n\n**My ORM configuration file:**\n\nhttps://i.sstatic.net/Zl7z2.png\n\n**Task Entity File: **\nhttps://i.sstatic.net/uWoKC.png\n\n**Finally I am importing the configuration file in tasks.module.ts file**\nhttps://i.sstatic.net/GPgG6.png\n\nPeople facing there issue have resolved it with different fixes,\n\n- Some said that we might be adding misspelled file name or path in configuration that might have caused this issue.\n\n- Some said that changing from npm to yarn has fixed the issue.\n\n- And few also said that the issue is with ORM itself.\n\nI have tried all possible solutions that are available over the internet but was not able to fix this. Its been quite few days now and I am looking for a helping hand or savior on stack overflow.\n\nMeanwhile, I will try to see a few more possibilities that could help but if you have faced this issue do let me know the possible solutions.\n\n========================================\n\nTop Answer:\n```\nentities: [__dirname + '/../**/*.entity.ts']\n```\n\nto\n\n```\nentities: [__dirname + '/../**/*.entity.js']\n```\n\nin **typeorm.config.ts**\n\nit works on me\n\n========================================\n\nCode:\n```text\n@Entity()\n```\n\n```text\nTask\n```\n\n```text\n// base.entity.ts\nimport { PrimaryGeneratedColumn, Column, UpdateDateColumn, CreateDateColumn } from 'typeorm';\n\nexport abstract class BaseEntity {\n@PrimaryGeneratedColumn('uuid')\nid: string;\n\n@Column({ type: 'boolean', default: true })\nisActive: boolean;\n\n@Column({ type: 'boolean', default: false })\nisArchived: boolean;\n\n@CreateDateColumn({ type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })\ncreateDateTime: Date;\n\n@Column({ type: 'varchar', length: 300 })\ncreatedBy: string;\n\n@UpdateDateColumn({ type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })\nlastChangedDateTime: Date;\n\n@Column({ type: 'varchar', length: 300 })\nlastChangedBy: string;\n\n@Column({ type: 'varchar', length: 300, nullable: true })\n internalComment: string | null;\n}\n```\n\n```text\nentities: [__dirname + '/../**/*.entity.ts']\n```\n\n```text\nentities: [__dirname + '/../**/*.entity.js']\n```\n\n```text\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nexport const TypeORMConfig: TypeOrmModuleOptions = {\n type: 'postgres',\n url: process.env.DATABASE_URL,\n synchronize: true,\n entities: [__dirname + '/../**/*.entity.ts'],\n migrationsTableName: 'Migrations_History',\n};\n```\n\n```text\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nexport const TypeORMConfig: TypeOrmModuleOptions = {\n type: 'postgres',\n url: process.env.DATABASE_URL,\n synchronize: true,\n entities: [__dirname + '/../**/*.entity{.ts,.js}'],\n migrationsTableName: 'Migrations_History',\n};\n```\n\n```text\n.js\n```\n\n```text\n.ts\n```\n\n```text\ntypeorm.config.ts\n```\n\n```text\nentities: [__dirname + '../**/*.entity{.ts,.js}']\n```\n\n```js\n@Module({\n imports: [\n TasksModule,\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'postgres',\n database: 'userdata',\n autoLoadEntities: true,\n synchronize: true,\n\n }),\n ],\n \n})\nexport class AppModule { }\n```\n\n```text\nautoLoadEntities: true,\n```\n\n```text\nentities: ['dist/src/**/*.entity{.ts,.js}'],\n```\n\n```text\nimport { Device } from \"@core/entities/device\";\nimport { User } from \"@core/entities/user\";\n\nexport const AppDataSource = new DataSource({\n type: \"postgres\",\n url: process.env.POSTGRES_URL_NON_POOLING,\n entities: [Device, User], // <-------- \n logging: true,\n});\n```\n\n========================================\n\nComments:\n- In the future, please post actual code snippets and not screenshots. Please take a look at this link.\n- @JayMcDoniel sure. Will make sure to add code's. I added screenshot as i knew that something small might be an issue and I had my code on github . just in case if someone wanted to debug I would have given the github link. But will make sure that i add code\n- You didn't add code.\n- Hi Jay. Thank you it helped. Sometimes I feel like an idiot. Not sure how I missed it.\n- didnt work for me even tho i have @Entity. same issue, No metadata was found\n- Hi Sunny. Thank you for your answer. Not sure how did I miss that.\n- set typeOrmCOnfig entities: [`dist/**/**/*.entity{.ts,.js}`], // try this\n- we can do the ORM configurations in **app.module** file and Try with the above approach. For me, it works fine","metadata":{"transformedAt":"2026-08-18T18:33:44.684Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":194,"estimatedTokens":1207}}37{"id":"stack-57459643","source":"stackoverflow","questionId":57459643,"title":"TypeORM: Dynamically set database schema for EntityManager (or repositories) at runtime?","tags":["postgresql","orm","multi-tenant","nestjs","typeorm"],"text":"Title: TypeORM: Dynamically set database schema for EntityManager (or repositories) at runtime?\nTags: postgresql, orm, multi-tenant, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\n**Situation:**\n\nFor our SaaS API we use schema-based multitenancy, which means every customer (~tenant) has its own separate schema within the same (postgres) database, without interfering with other customers. Each schema consists of the same underlying entity-model. \n\nEverytime a new customer is registered to the system, a new isolated schema is automatically created within the db. This means, the schema is created at runtime and not known in advance. The customer's schema is named according to the customer's domain.\n\nFor every request that arrives at our API, we extract the user's tenancy-affiliation from the JWT and determine which db-schema to use to perform the requested db-operations for this tenant.\n\n**Problem**\n\nAfter having established a connection to a (postgres) database via TypeORM (e.g. using createConnection), our only chance to set the schema for a db-operation is to resort to the `createQueryBuilder`:\n\n```\nconst orders = await this.entityManager\n .createQueryBuilder()\n .select()\n .from(`${tenantId}.orders`, 'order') // This means, we are forced to use the `QueryBuilder` as it does not seem to be possible to set the schema when working with the EntityManager API (or the Repository API).\n\nHowever, we want/need to use these APIs, because they are much simpler to write, require less code and are also less error-prone, since they do not rely on writing queries \"manually\" employing a string-based syntax.\n\n**Question**\n\nIn case of TypeORM, is it possible to somehow set the db-schema when working with the `EntityManager` or repositories?\n\nSomething like this?\n\n```\n// set schema when instantiating manager\nconst manager = connection.createEntityManager({ schema: tenantDomain });\n\n// should find all matching \"order\" entities within schema\nconst orders = manager.find(Order, { priority: 4 })\n\n// should find a matching \"item\" entity within schema using same manager\nconst item = manager.findOne(Item, { id: 321 })\n```\n\n**Notes:**\n\n- The db-schema needs to be set in a request-scoped way to avoid setting the schema for other requests, which may belong to other customers. Setting the schema for the whole connection is not an option.\n\n- We are aware that one could create a whole new connection and set the schema for this connection, but we want to reuse the existing connection. So simply creating a new connection to set the schema is not an option.\n\n========================================\n\nTop Answer:\nHere is a global overview of the issues with schema-based multitenancy along with a complete walkthrough a Github repo for it.\n\nMost of the time, you may want to use Postgres Row Security Policy instead. It gives most of the benefits of schema-based multitenancy (especially on developer experience), without the issues related to the multiplication of connections.\n\n========================================\n\nCode:\n```js\nconst orders = await this.entityManager\n .createQueryBuilder()\n .select()\n .from(`${tenantId}.orders`, 'order') // <--- setting schema-prefix here\n .where(\"order.priority = 4\")\n .getMany();\n```\n\n```js\n// set schema when instantiating manager\nconst manager = connection.createEntityManager({ schema: tenantDomain });\n\n// should find all matching \"order\" entities within schema\nconst orders = manager.find(Order, { priority: 4 })\n\n// should find a matching \"item\" entity within schema using same manager\nconst item = manager.findOne(Item, { id: 321 })\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\nQueryBuilder\n```\n\n```text\nEntityManager\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\nquery()\n```\n\n```text\nthis.photoRepository.useSchema('customer1').find()\n```\n\n```text\ngetConnection().changeDefaultSchema('myschema')\n```\n\n```text\nTypeOrmModule.forRootAsync(dynamicCreatedDbConfig)\n```\n\n========================================\n\nComments:\n- I'm having the exact same setup in my project, each tenant has its own schema, each schema looks the same and the connection needs to be request-scoped. I’m going the way which you don’t want to, meaning creating a new connection for each customer. What is your intention not to do it that way? Performance might be a reason, but currently I’m not running into any problems with to many database connections. Data security shouldn’t be an issue, doing it your way doesn’t differ from the way I do it: const manager = ConnectionUtils.createConnection(schema).createEntityManager‌​();\n- Would you just use a Model Driven solution, with one entity class per tenant that you generate at each tenant change? Keeping business code in an abstract class and specifying the schema in the entity decorator in subclasses?\n- Hi @JudgeFudge many thanks for your feedback! May I ask, how many requests does your backend receive per minute, and how many concurrent connections are usually kept open simultaneously? Also, at which point do you close the db-connection? Do you keep them idle or do you close them once the response is sent to the client via a middleware? The reason I don't want to open new connections is to avoid unnecessary resource usage (memory/CPU), moreover, I do not see the point in reestablishing a connection if – theoretically speaking – we can set a different schema with TypeORM... really annoying :(\n- @zenbeni Unfortunately \"specifying the schema in the entity decorator in subclasses\" is not possible. As I mentioned, the schema is created at runtime and I cannot create an entity per tenant and set decorators at compile time, since the tenants are not known in advance.\n- @B12Toaster I looked through the TypeORM sources to find a way to set the schema dynamically, but there seems to be no easy way (the way you find is the less dirty way I guess). I have about 50 tenants und the number of requests is not that high (around 50 requests per tenant per hour), so I can’t tell you much about scaling. So I think we have two options: Create a change request (maybe do it on your own) or find more about the performance while having many connections. Since I’m also very interested in this topic, I might try some test scenarios in my app. I will keep you up to date.\n- HI @B12Toaster have you get the answer somehow? I had exactly the same questions and TypeORM team aren't responding... Just wondering if you found any nice solution.\n- @WinterTime nope not yet. I saw your Issue at github, thanks for opening it, will link it in the OP if that is okay for you? Currently, I am creating one connection per tenant and we will try to keep the tenant number per server below 100. But still experimenting with this. Here is an interesting article that provides some information about how many connections are possible with postgres and how much memory is consumed: citusdata.com/blog/2017/05/10/scaling-connections-in-postgre‌​s\n- @B12Toaster after creating schema how do you run initial migration. I want to implement your method but stuck got stuck there.\n- @FelixK. Not directly related to your question but how do you create tables for new schema? I mean when a new tenant is registered you must be creating new schema for it through code. How do you then replicate all tables for new schema?\n- sorry, but this does not answer my question.\n- Wondering if there is any update on Typeorm supporting multi tenancy for a single DB?\n- i wonder why typeorm doesn't have a clean method for something so common\n- Is there any updates on this topic? Does TypeORM still cannot switch schema at runtime?\n- getConnection() is deprecated\n- @Felix K. , isn't the link provided(first one) in this answer the solution appropriate? It the connection in the pool exists , then it's not supposed to be recreated right?\n- isn't the link provided in this answer (the first one) the solution appropriate? It the connection in the pool exists , then it's not supposed to be recreated right?","metadata":{"transformedAt":"2026-08-18T18:33:44.684Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":129,"estimatedTokens":1999}}38{"id":"stack-65222981","source":"stackoverflow","questionId":65222981,"title":"typeorm synchronize in production","tags":["node.js","typeorm"],"text":"Title: typeorm synchronize in production\nTags: node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn Typeorm there is a feature called `synchronize`. You can synchronize entities with a database, so there is no need for migirations. But as you know `synchronize` is dangerous for production.\n\nHere is the question, when should I use the `synchronize` feature? Imagine at first (in the development environment) I started using the `synchronize` feature. If I disable it in production while I have no migration, how should my production database will going to be created?\n\nAlso, I'm going to deliver the project on some milestones. Should I disable it at the first milestone or at the end? And for long time maintenance, should I use `synchronize` disabled and use migration after the first production release?\n\nAny idea would be appreciated.\n\n========================================\n\nTop Answer:\nSynchronize is a great option to get up an running, but in my opinion you should always default to creating migrations. This is because it will enforce you to run your development environment similar to production, which is always key. You want to make your Dev environment run like production.\n\n`migration:generate` is a great middle ground to building your migration files from your entities.\n\n========================================\n\nCode:\n```text\nsynchronize\n```\n\n```text\nsynchronize\n```\n\n```text\nsynchronize\n```\n\n```text\nsynchronize\n```\n\n```text\nsynchronize\n```\n\n```text\nmigration:generate\n```\n\n========================================\n\nComments:\n- I'm also wondering what should be the process ... Do you think we may use something else than typeorm migrations ? Because I just tried, and I'm having a bug for nullable fields ...\n- Hi, thanks for sharing. But I know about migrations and all the commands. Mostly, my question was about when and in which stage to use migirations.","metadata":{"transformedAt":"2026-08-18T18:33:44.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":52,"estimatedTokens":471}}39{"id":"stack-64412515","source":"stackoverflow","questionId":64412515,"title":"How to show generated SQL / raw SQL in TypeORM queryBuilder","tags":["sql","typeorm"],"text":"Title: How to show generated SQL / raw SQL in TypeORM queryBuilder\nTags: sql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI developed `typeorm` `querybuilder`. For the purpose of debugging, I'd like to show the generated SQL query.\n\nI tested `printSql()` method, but it didn't show any SQL query.\n\n```\nconst Result = await this.attendanceRepository\n .createQueryBuilder(\"attendance\")\n .innerJoin(\"attendance.child\", \"child\")\n .select([\"attendance.childId\",\"child.class\",\"CONCAT(child.firstName, child.lastName)\"])\n .where(\"attendance.id= :id\", { id: id })\n .printSql()\n .getOne()\n\nconsole.log(Result);\n```\n\nIt returned the following:\n\n```\nAttendance { childId: 4, child: Child { class: 'S' } }\n```\n\nMy desired result is to get the generated SQL query.\n\nIs there any wrong point? Is there any good way to get the SQL query?\n\n========================================\n\nTop Answer:\n`printSql` can also be used, but it will only print when `logging` is enabled.\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n ...options\n logging: true\n }),\n ],\n})\n\nawait this.attendanceRepository\n .createQueryBuilder(\"attendance\")\n .innerJoin(\"attendance.child\", \"child\")\n .select([\"attendance.childId\",\"child.class\",\"CONCAT(child.firstName, child.lastName)\"])\n .where(\"attendance.id= :id\", { id: id })\n .printSql();\n```\n\n========================================\n\nCode:\n```text\nconst Result = await this.attendanceRepository\n .createQueryBuilder(\"attendance\")\n .innerJoin(\"attendance.child\", \"child\")\n .select([\"attendance.childId\",\"child.class\",\"CONCAT(child.firstName, child.lastName)\"])\n .where(\"attendance.id= :id\", { id: id })\n .printSql()\n .getOne()\n\nconsole.log(Result);\n```\n\n```text\nAttendance { childId: 4, child: Child { class: 'S' } }\n```\n\n```text\ntypeorm\n```\n\n```text\nquerybuilder\n```\n\n```text\nprintSql()\n```\n\n```js\nconst sql1 = await this.attendanceRepository\n .createQueryBuilder(\"attendance\")\n .innerJoin(\"attendance.child\", \"child\")\n .select([\"attendance.childId\",\"child.class\",\"CONCAT(child.firstName, child.lastName)\"])\n .where(\"attendance.id= :id\", { id: id })\n .getQuery();\nconsole.log(sql1);\n```\n\n```js\nconst sql2 = await this.attendanceRepository\n .createQueryBuilder(\"attendance\")\n .innerJoin(\"attendance.child\", \"child\")\n .select([\"attendance.childId\",\"child.class\",\"CONCAT(child.firstName, child.lastName)\"])\n .where(\"attendance.id= :id\", { id: id })\n .getSql();\nconsole.log(sql2);\n```\n\n```text\n.getQuery()\n```\n\n```text\n.getSql()\n```\n\n```text\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n ...options\n logging: true\n }),\n ],\n})\n\nawait this.attendanceRepository\n .createQueryBuilder(\"attendance\")\n .innerJoin(\"attendance.child\", \"child\")\n .select([\"attendance.childId\",\"child.class\",\"CONCAT(child.firstName, child.lastName)\"])\n .where(\"attendance.id= :id\", { id: id })\n .printSql();\n```\n\n```text\nprintSql\n```\n\n```text\nlogging\n```\n\n========================================\n\nComments:\n- try getQuery(); instead of getOne();\n- and what about the other functions like `repo.find()`??\n- @MuhammadAwais for those there isn't a given method to retrieve the generated SQL, if it's just for debugging purposes you can enable `logging: true` in your DataSource options, which will log any query made to the database\n- this option no longer exists ?","metadata":{"transformedAt":"2026-08-18T18:33:44.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":146,"estimatedTokens":829}}40{"id":"stack-50361948","source":"stackoverflow","questionId":50361948,"title":"SyntaxError: Unexpected token import TypeORM entity","tags":["typescript","typeorm"],"text":"Title: SyntaxError: Unexpected token import TypeORM entity\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nSo, I am working with TypeORM and am getting an odd error when I transpile my TypeScript to JavaScript. I am receiving the following error:\n\n```\n(function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, ManyToOne, OneToMany, TreeChildren, TreeParent, JoinColumn, Column, Tree, TreeLevelColumn } from \"typeorm\";\n ^^^^^^\n\nSyntaxError: Unexpected token import\nat createScript (vm.js:80:10)\nat Object.runInThisContext (vm.js:139:10)\nat Module._compile (module.js:616:28)\nat Object.Module._extensions..js (module.js:663:10)\nat Module.load (module.js:565:32)\nat tryModuleLoad (module.js:505:12)\nat Function.Module._load (module.js:497:3)\nat Module.require (module.js:596:17)\nat require (internal/module.js:11:18)\nat Function.PlatformTools.load (C:\\Users\\*redacted*\\Workspace\\experimental\\*redacted*\\node_modules\\typeorm\\platform\\PlatformTools.js:126:28)\n```\n\nMy `tsconfig.json`:\n\n```\n{\n \"compilerOptions\": {\n \"lib\": [\n \"es5\",\n \"es6\"\n ],\n \"target\": \"es5\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"outDir\": \"./build\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"sourceMap\": true\n },\n \"exclude\": [\n \"client\"\n ]\n}\n```\n\nMy `package.json`:\n\n```\n{\n \"name\": \"*redacted*\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"dev\": \"nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec ts-node src/index.ts\",\n \"start\": \"tsc && node ./build/index.js\",\n \"migrate\": \"ts-node ./node_modules/typeorm/cli.js migration:generate\"\n },\n \"author\": \"*redacted*\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"bcryptjs\": \"^2.4.3\",\n \"body-parser\": \"^1.18.3\",\n \"class-validator\": \"^0.8.5\",\n \"express\": \"^4.16.3\",\n \"jwt-simple\": \"^0.5.1\",\n \"morgan\": \"^1.9.0\",\n \"pg\": \"^7.4.3\",\n \"reflect-metadata\": \"^0.1.10\",\n \"typeorm\": \"0.2.5\"\n },\n \"devDependencies\": {\n \"@types/bcryptjs\": \"^2.4.1\",\n \"@types/body-parser\": \"^1.17.0\",\n \"@types/express\": \"^4.11.1\",\n \"@types/jwt-simple\": \"^0.5.33\",\n \"@types/node\": \"^8.10.15\",\n \"ts-node\": \"3.3.0\",\n \"typescript\": \"2.5.2\"\n }\n}\n```\n\nThe file throwing the error:\n\n```\nimport { Entity, PrimaryGeneratedColumn, ManyToOne, OneToMany, TreeChildren, TreeParent, JoinColumn, Column, Tree, TreeLevelColumn } from \"typeorm\";\nimport { User } from \"./User\";\nimport { Debate } from \"./Debate\";\n\n@Entity()\n@Tree(\"closure-table\")\nexport class Comment {\n\n @PrimaryGeneratedColumn(\"uuid\")\n id: string;\n\n @Column()\n text: string;\n\n @ManyToOne(type => User)\n user: User;\n\n @ManyToOne(type => Debate, debate => debate.comments)\n debate: Debate;\n\n @TreeChildren()\n children: Comment[];\n\n @TreeParent()\n parent: Comment;\n}\n```\n\nWhat I have tried:\n\n- I have tried updating my node.js to the latest (version 8.11.2)\n\n- I have tried changing the \"lib\" settings in my tsconfig.json in various combinations of \"es5\", \"es6\", and \"es7\"\n\n- I have tried changing the \"target\" for my tsconfig.json for the targets listed in the above bullet point.\n\n- I have tried changing the import statements in my entity files from `import (lib) from (module)` to `const (lib) require (module)\";` However, this causes more issues and doesn't work well.\n\nI have been googling for this issue extensively and it has left me scratching my head. Any and all help would be greatly appreciated.\n\n========================================\n\nTop Answer:\nYou can also use `ts-node` to run typeorm, which will allow you to run `ts` files, and which will allow you to avoid compiling and running separate `js` files.\n\nPer this github comment, you can do the following:\n\n 1.- Install ts-node and typescript globally:\n\n \n `$ npm install -g ts-node typescript`\n\n \n 2.- Execute the typeorm command with ts-node:\n\n \n `$ ts-node ./node_modules/.bin/typeorm migrations:generate -n`\n\nIf you're on windows, you'll have problems with that. Per this comment, you'll want to directly reference `cli.js`:\n\n `ts-node node_modules\\typeorm\\cli.js`\n\n========================================\n\nCode:\n```text\n(function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, ManyToOne, OneToMany, TreeChildren, TreeParent, JoinColumn, Column, Tree, TreeLevelColumn } from \"typeorm\";\n ^^^^^^\n\nSyntaxError: Unexpected token import\nat createScript (vm.js:80:10)\nat Object.runInThisContext (vm.js:139:10)\nat Module._compile (module.js:616:28)\nat Object.Module._extensions..js (module.js:663:10)\nat Module.load (module.js:565:32)\nat tryModuleLoad (module.js:505:12)\nat Function.Module._load (module.js:497:3)\nat Module.require (module.js:596:17)\nat require (internal/module.js:11:18)\nat Function.PlatformTools.load (C:\\Users\\*redacted*\\Workspace\\experimental\\*redacted*\\node_modules\\typeorm\\platform\\PlatformTools.js:126:28)\n```\n\n```text\n{\n \"compilerOptions\": {\n \"lib\": [\n \"es5\",\n \"es6\"\n ],\n \"target\": \"es5\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"outDir\": \"./build\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"sourceMap\": true\n },\n \"exclude\": [\n \"client\"\n ]\n}\n```\n\n```text\n{\n \"name\": \"*redacted*\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"dev\": \"nodemon --watch 'src/**/*.ts' --ignore 'src/**/*.spec.ts' --exec ts-node src/index.ts\",\n \"start\": \"tsc && node ./build/index.js\",\n \"migrate\": \"ts-node ./node_modules/typeorm/cli.js migration:generate\"\n },\n \"author\": \"*redacted*\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"bcryptjs\": \"^2.4.3\",\n \"body-parser\": \"^1.18.3\",\n \"class-validator\": \"^0.8.5\",\n \"express\": \"^4.16.3\",\n \"jwt-simple\": \"^0.5.1\",\n \"morgan\": \"^1.9.0\",\n \"pg\": \"^7.4.3\",\n \"reflect-metadata\": \"^0.1.10\",\n \"typeorm\": \"0.2.5\"\n },\n \"devDependencies\": {\n \"@types/bcryptjs\": \"^2.4.1\",\n \"@types/body-parser\": \"^1.17.0\",\n \"@types/express\": \"^4.11.1\",\n \"@types/jwt-simple\": \"^0.5.33\",\n \"@types/node\": \"^8.10.15\",\n \"ts-node\": \"3.3.0\",\n \"typescript\": \"2.5.2\"\n }\n}\n```\n\n```text\nimport { Entity, PrimaryGeneratedColumn, ManyToOne, OneToMany, TreeChildren, TreeParent, JoinColumn, Column, Tree, TreeLevelColumn } from \"typeorm\";\nimport { User } from \"./User\";\nimport { Debate } from \"./Debate\";\n\n\n@Entity()\n@Tree(\"closure-table\")\nexport class Comment {\n\n @PrimaryGeneratedColumn(\"uuid\")\n id: string;\n\n @Column()\n text: string;\n\n @ManyToOne(type => User)\n user: User;\n\n @ManyToOne(type => Debate, debate => debate.comments)\n debate: Debate;\n\n @TreeChildren()\n children: Comment[];\n\n @TreeParent()\n parent: Comment;\n}\n```\n\n```text\ntsconfig.json\n```\n\n```text\npackage.json\n```\n\n```text\nimport (lib) from (module)\n```\n\n```text\nconst (lib) require (module)\";\n```\n\n```text\n{\n \"type\": \"postgres\",\n \"host\": \"**********************\",\n \"port\": 5432,\n \"username\": \"**************\",\n \"password\": \"*************\",\n \"database\": \"*************\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n // changed this\n\n \"dist/entity/*.js\"\n ],\n \"migrations\": [\n \"src/migration/**/*.ts\"\n ],\n \"subscribers\": [\n \"src/subscriber/**/*.ts\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\n```text\nts-node\n```\n\n```text\nts\n```\n\n```text\njs\n```\n\n```text\n$ npm install -g ts-node typescript\n```\n\n```text\n$ ts-node ./node_modules/.bin/typeorm migrations:generate -n\n```\n\n```text\ncli.js\n```\n\n```text\nts-node node_modules\\typeorm\\cli.js\n```\n\n```text\n.js\n```\n\n```text\n.ts\n```\n\n========================================\n\nComments:\n- does it mean we need a ormconfig.json file when we are runing the dev environment and a different one when we publish the build application in a hosting provider only because the path where the entities are stored?\n- what would be the advantages of not compiling the files to run `js` files?\n- @MikeBarnes none that I can think of. Beware of running in production with ts-node, there's a flag that you need to pass so it doesnt do a type analysis on your files, otherwise it will hog a whole lot of memory in your server. I am not 100% sure that ts-node is production ready, but I may be wrong.\n- @oskar132 yeah, I thought this might be an issue. thanks!","metadata":{"transformedAt":"2026-08-18T18:33:44.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":347,"estimatedTokens":2148}}41{"id":"stack-51994541","source":"stackoverflow","questionId":51994541,"title":"NestJS + TypeORM: Use two or more databases?","tags":["javascript","node.js","nestjs","typeorm"],"text":"Title: NestJS + TypeORM: Use two or more databases?\nTags: javascript, node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying since 2 days to solve this, perhaps I'm simply missing the point here.\n\nMy goal was to write a NestJS app (with TypeORM included) which serves a RestAPI for 2 or 3 of my little projects, instead of writing a NestJS-App for every single one of them.\n\nSo far so good, the app is ready, works well with the single projects (which resides in subfolders with their entities, controllers, services, modules), but I can't get it to run with all of them.\n\nThe point seems to be the configuration, I'm using `ormconfig.json`:\n\n```\n[ {\n \"name\": \"Project1\",\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"\",\n \"password\": \"\",\n \"database\": \"\",\n \"synchronize\": false,\n \"entities\": [\"project1/*.entity.ts\"],\n \"subscribers\": [\"project1/*.subscriber.ts\"],\n \"migrations\": [\"project1/migrations/*.ts\"],\n \"cli\": { \"migrationsDir\": \"project1/migrations\" }\n}, {\n \"name\": \"project2\",\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"\",\n \"password\": \"\",\n \"database\": \"\",\n \"synchronize\": false,\n \"entities\": [\"project2/*.entity.ts\"],\n \"subscribers\": [\"project2/*.subscriber.ts\"],\n \"migrations\": [\"project2/migrations/*.ts\"],\n \"cli\": { \"migrationsDir\": \"project2/migrations\"\n } ]\n```\n\nThe error message says:\n\n [ExceptionHandler] Cannot find connection default because its not defined in any orm configuration files\n\nOf course \"default\" couldn't be found, because I'm providing two configs with unique names different to \"default\".\n\nIn **ApplicationModule** I could provide the name of the connection, like this:\n\n```\nTypeOrmModule.forRoot( { name: \"project1\" } ),\n```\n\nbut then it would work only for one project.\n\nI could mix all in one config, but then I would have everything in one database, same user for all and perhaps mix up the entities...\n\nCan someone give me a hint how to solve this?\nPerhaps with `getConnection()` in every module, but how to start the ApplicationModule then?\n\nKind regards,\n\nsagerobert\n\n========================================\n\nTop Answer:\nYou need to explicitly pass the connection name at the same level inside **TypeOrmModule.forRoot({ name: 'db1Connection' })** incase you are using multiple database connections.\n\n```\nTypeOrmModule.forRootAsync({\n name: DB1_CONNECTION,\n imports: [ConfigModule],\n useClass: TypeormDb1ConfigService,\n}),\n\nTypeOrmModule.forRootAsync({\n name: DB2_CONNECTION,\n imports: [ConfigModule],\n useClass: TypeormDb2ConfigService,\n})\n```\n\n========================================\n\nCode:\n```text\n[ {\n \"name\": \"Project1\",\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"<username>\",\n \"password\": \"<pwd>\",\n \"database\": \"<database>\",\n \"synchronize\": false,\n \"entities\": [\"project1/*.entity.ts\"],\n \"subscribers\": [\"project1/*.subscriber.ts\"],\n \"migrations\": [\"project1/migrations/*.ts\"],\n \"cli\": { \"migrationsDir\": \"project1/migrations\" }\n}, {\n \"name\": \"project2\",\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"<another-username>\",\n \"password\": \"<another-pwd>\",\n \"database\": \"<another-database>\",\n \"synchronize\": false,\n \"entities\": [\"project2/*.entity.ts\"],\n \"subscribers\": [\"project2/*.subscriber.ts\"],\n \"migrations\": [\"project2/migrations/*.ts\"],\n \"cli\": { \"migrationsDir\": \"project2/migrations\"\n } ]\n```\n\n```text\nTypeOrmModule.forRoot( { name: \"project1\" } ),\n```\n\n```text\normconfig.json\n```\n\n```text\ngetConnection(<name>)\n```\n\n```text\nimports: [\n ...,\n TypeOrmModule.forRoot({\n name: 'Project1',\n type: 'mysql',\n host: 'localhost',\n port: 3306,\n username: '<username>',\n password: '<pwd>',\n database: '<database>',\n synchronize: false,\n entities: ['project1/*.entity.ts'],\n subscribers: ['project1/*.subscriber.ts'],\n migrations: ['project1/migrations/*.ts'],\n cli: { migrationsDir: 'project1/migrations' },\n }),\n TypeOrmModule.forRoot({\n name: 'project2',\n type: 'mysql',\n host: 'localhost',\n port: 3306,\n username: '<another-username>',\n password: '<another-pwd>',\n database: '<another-database>',\n synchronize: false,\n entities: ['project2/*.entity.ts'],\n subscribers: ['project2/*.subscriber.ts'],\n migrations: ['project2/migrations/*.ts'],\n cli: { migrationsDir: 'project2/migrations' },\n })\n]\n```\n\n```text\normconfig.json\n```\n\n```text\ndefault\n```\n\n```text\napp.module.ts\n```\n\n```text\normconfig.json\n```\n\n```text\nTypeOrmModule.forRootAsync({\n name: DB1_CONNECTION,\n imports: [ConfigModule],\n useClass: TypeormDb1ConfigService,\n}),\n\nTypeOrmModule.forRootAsync({\n name: DB2_CONNECTION,\n imports: [ConfigModule],\n useClass: TypeormDb2ConfigService,\n})\n```\n\n```js\n@Module({\n imports: [TypeOrmModule.forFeature([Entity1, Entity2]), //This will use default connection\n TypeOrmModule.forRoot({name: 'con1'}), // This will register globaly con1\n TypeOrmModule.forRoot({name: 'con2'}), // This will register globaly con2\n controllers: [...],\n providers: [...],\n exports: [...]\n})\n```\n\n```text\n\"name\":\"default\"\n```\n\n```text\normconfig.json\n```\n\n```text\normconfig.json\n```\n\n```js\nimport parseBoolean from '@eturino/ts-parse-boolean';\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\nimport * as dotenv from 'dotenv';\nimport { join } from 'path';\n\ndotenv.config();\n\nexport = [\n {\n //name: 'default',\n type: 'mssql',\n host: process.env.DEFAULT_DB_HOST,\n username: process.env.DEFAULT_DB_USERNAME,\n password: process.env.DEFAULT_DB_PASSWORD,\n database: process.env.DEFAULT_DB_NAME,\n options: {\n instanceName: process.env.DEFAULT_DB_INSTANCE,\n enableArithAbort: false,\n },\n logging: parseBoolean(process.env.DEFAULT_DB_LOGGING),\n dropSchema: false,\n synchronize: false,\n migrationsRun: parseBoolean(process.env.DEFAULT_DB_RUN_MIGRATIONS),\n migrations: [join(__dirname, '..', 'model/migration/*.{ts,js}')],\n cli: {\n migrationsDir: 'src/model/migration',\n },\n entities: [\n join(__dirname, '..', 'model/entity/default/**/*.entity.{ts,js}'),\n ],\n } as TypeOrmModuleOptions,\n {\n name: 'other',\n type: 'mssql',\n host: process.env.OTHER_DB_HOST,\n username: process.env.OTHER_DB_USERNAME,\n password: process.env.OTHER_DB_PASSWORD,\n database: process.env.OTHER_DB_NAME,\n options: {\n instanceName: process.env.OTHER_DB_INSTANCE,\n enableArithAbort: false,\n },\n logging: parseBoolean(process.env.OTHER_DB_LOGGING),\n dropSchema: false,\n synchronize: false,\n migrationsRun: false,\n entities: [],\n } as TypeOrmModuleOptions,\n];\n```\n\n```js\nimport configuration from '@config/configuration';\nimport validationSchema from '@config/validation';\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { LoggerService } from '@shared/logger/logger.service';\nimport { UsersModule } from '@user/user.module';\nimport { AppController } from './app.controller';\nimport ormconfig = require('./config/ormconfig'); //path mapping doesn't work here\n\n@Module({\n imports: [\n ConfigModule.forRoot({\n cache: true,\n isGlobal: true,\n validationSchema: validationSchema,\n load: [configuration],\n }),\n TypeOrmModule.forRoot(ormconfig[0]), //default\n TypeOrmModule.forRoot(ormconfig[1]), //other db\n LoggerService,\n UsersModule,\n ],\n controllers: [AppController],\n})\nexport class AppModule {}\n```\n\n```json\n\"scripts\": {\n ...\n \"typeorm\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config ./src/config/ormconfig.ts\",\n \"typeorm:migration:generate\": \"npm run typeorm -- migration:generate -n\",\n \"typeorm:migration:run\": \"npm run typeorm -- migration:run\"\n },\n```\n\n```text\nsrc/\n├── app.controller.ts\n├── app.module.ts\n├── config\n│ ├── configuration.ts\n│ ├── ormconfig.ts\n│ └── validation.ts\n├── main.ts\n├── model\n│ ├── entity\n│ ├── migration\n│ └── repository\n├── route\n│ └── user\n└── shared\n └── logger\n```\n\n```text\n@Module({\n imports: [\n ConfigModule.forRoot({\n isGlobal: true,\n load: [\n database,\n databaseAllo #<= my second database\n ]\n }),\n TypeOrmModule.forRootAsync({\n useFactory: (configs: ConfigService) => configs.get(\"db_config\"),\n inject: [ConfigService],\n }),\n TypeOrmModule.forRootAsync({\n name:\"db_allo\", #<= create connection to my second db\n useFactory: (configs: ConfigService) => configs.get(\"db_config_allo\"),\n inject: [ConfigService],\n }),\n AuthModule,\n JwtAuthModule\n ],\n controllers: []\n})\nexport class AppModule {}\n```\n\n```text\n@Module({\n imports: [\n TypeOrmModule.forFeature([AlloMpcTable], \"db_allo\" #<= call connection again),\n ],\n providers: [\n AlloRepository\n ],\n exports: [AlloRepository],\n controllers: [],\n})\nexport class AlloModule {}\n```\n\n```text\n@Injectable()\nexport class AlloRepository extends BaseRepository<AlloMpcTable> {\n constructor(\n @InjectRepository(AlloMpcTable, \"db_allo\") #<= you need to call connection again\n private readonly allo: Repository<AlloMpcTable>,\n ) {\n super(allo)\n }\n\n public async Find(id: number): Promise<AlloMpcTable> {\n return await this.allo.findOne(id)\n }\n\n}\n```\n\n```text\nexport const DB_CONNECTION_1 = 'conn1';\n\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n name: DB_CONNECTION_1,\n ...\n })\n ],\n ...\n)\nexport class AppModule {}\n```\n\n```text\n@Module({\n imports: [\n TypeOrmModule.forFeature(\n [MyRepo],\n DB_CONNECTION_1,\n ),\n ],\n providers: [MyRepo],\n})\n```\n\n```text\n@Injectable()\nexport class MyRepo {\n constructor(\n @InjectRepository(MyOrmEntity, DB_CONNECTION_1)\n private readonly repo: Repository<MyOrmEntity>,\n ) {}\n}\n```\n\n```text\napp.module.ts\n```\n\n```text\nconstants.ts\n```\n\n```text\nNo repository found for\n```\n\n```text\nwas found. Looks like this entity is not registered in current \"default\" connection.\n```\n\n```text\nexport const DB_CONNECTION_1 = 'conn1';\n```\n\n```text\napp.module.ts\n```\n\n```text\nconstants.ts\n```\n\n========================================\n\nComments:\n- Thanks a lot, that seems to solve this issue! Just one another question: before this block, in the `...,` section, do you import the Modules for each 'project' (like `Project1Module, Project2Module`) or additionally something else?\n- Sorry, missed your comment. No, I couldn't think of any special import.\n- Out of interest ... How did you run the migrations?\n- By defining as you said, I didn't get any error. But the program always run by default database. Have any idea what else should be checked?\n- @SorayaAnvari When you use the `forFeature` import, are you also passing the `name` of the connection: `TypeOrmModule.forFeature([Album], 'albumsConnection')`?\n- I wrote TypeOrmModule.forRoot with both databases in app.module. Then added TypeOrmModule.forFeature(Entities, 'connectionname') in each.separated module. My program has the same host with different databases. I created a module to handle each database request. I don't know what is missing.\n- @SorayaAnvari, Have you been able to solve the issue. I have also similar situation. Thank you!\n- You just saved my day sir. `TypeOrmModule.forRootAsync` has the worst API interface I have ever witnessed.\n- @PubuduDodangoda I think that the problem is not the api, is that the docs has only one small phrase mentioning this that only clicked when I read Frozenex reply. It makes sense how they do it, but it should be clearer in the docs","metadata":{"transformedAt":"2026-08-18T18:33:44.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":461,"estimatedTokens":2899}}42{"id":"stack-71557301","source":"stackoverflow","questionId":71557301,"title":"How to workraound this TypeORM error, \"EntityRepository is deprecated , use Repository.extend function instead\"?","tags":["nestjs","typeorm"],"text":"Title: How to workraound this TypeORM error, \"EntityRepository is deprecated , use Repository.extend function instead\"?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHowever, I can't find any Repository.extend method in Repository class and there's nothing about it in the documentation. How to solve this?\n\ntypeorm version: \"^0.3.0\"\n\nI'm using nest js and trying to create a custom repository.\n\n========================================\n\nTop Answer:\nWith the current version of TypeORM, it's possible to implement a custom repository in the following way utilizing DataSource.\n\n```\n// user.repository.ts\n@Injectable()\nexport class UsersRepository extends Repository {\n constructor(private dataSource: DataSource) {\n super(UsersEntity, dataSource.createEntityManager());\n }\n\n async getById(id: string) {\n return this.findOne({ where: { id } });\n }\n // ...\n}\n```\n\nThe repository is then injected into the service.\n\n```\n// user.service.ts\nexport class UserService {\n constructor(private readonly userRepository: UserRepository) {}\n\n async getById(id: string): Promise {\n return this.userRepository.getById(id);\n }\n // ...\n}\n```\n\nand the module has imports for the feature and the repository as a provider.\n\n```\n// user.module.ts\n@Module({\n imports: [\n TypeOrmModule.forFeature([UserEntity])],\n // ...\n ],\n providers: [UserService, UserRepository],\n // ...\n})\nexport class UserModule {}\n```\n\n========================================\n\nCode:\n```text\nnpm install @nestjs/typeorm@next\n```\n\n```text\n// typeorm-ex.decorator.ts\n\nimport { SetMetadata } from \"@nestjs/common\";\n\nexport const TYPEORM_EX_CUSTOM_REPOSITORY = \"TYPEORM_EX_CUSTOM_REPOSITORY\";\n\nexport function CustomRepository(entity: Function): ClassDecorator {\n return SetMetadata(TYPEORM_EX_CUSTOM_REPOSITORY, entity);\n}\n```\n\n```text\n// typeorm-ex.module.ts\n\nimport { DynamicModule, Provider } from \"@nestjs/common\";\nimport { getDataSourceToken } from \"@nestjs/typeorm\";\nimport { DataSource } from \"typeorm\";\nimport { TYPEORM_EX_CUSTOM_REPOSITORY } from \"./typeorm-ex.decorator\";\n\nexport class TypeOrmExModule {\n public static forCustomRepository<T extends new (...args: any[]) => any>(repositories: T[]): DynamicModule {\n const providers: Provider[] = [];\n\n for (const repository of repositories) {\n const entity = Reflect.getMetadata(TYPEORM_EX_CUSTOM_REPOSITORY, repository);\n\n if (!entity) {\n continue;\n }\n\n providers.push({\n inject: [getDataSourceToken()],\n provide: repository,\n useFactory: (dataSource: DataSource): typeof repository => {\n const baseRepository = dataSource.getRepository<any>(entity);\n return new repository(baseRepository.target, baseRepository.manager, baseRepository.queryRunner);\n },\n });\n }\n\n return {\n exports: providers,\n module: TypeOrmExModule,\n providers,\n };\n }\n}\n```\n\n```text\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mssql',\n ...\n entities: [Photo],\n }),\n TypeOrmExModule.forCustomRepository([PhotoRepository]),\n ...\n ],\n controllers: [AppController],\n providers: [\n AppService\n ],\n})\nexport class AppModule { }\n```\n\n```text\n@CustomRepository(Photo)\nexport class PhotoRepository extends Repository<Photo> {\n public async getAllPhoto() {\n const query = this.createQueryBuilder('photo')\n .where('photo.isPublished = :isPublished', { isPublished: true })\n const photos = await query.getMany()\n return photos\n }\n}\n```\n\n```text\n9.0.0-next.2\n```\n\n```text\n0.3.6\n```\n\n```text\nexport const UserRepository = dataSource.getRepository(User).extend({...})\n```\n\n```text\nyarn add @nestjs/typeorm@next\n```\n\n```js\n@EntityRepository(Person)\n export class PersonRepository extends Repository<Person> {...}\n```\n\n```js\n@Injectable()\n export class PersonRepository {\n constructor(private dataSource: DataSource) { }\n\n exampleQueryBuilder() {\n return this.dataSource\n .getRepository(Person)\n .createQueryBuilder() ...\n }\n```\n\n```js\n@Injectable()\n export class PersonService {\n constructor(\n @Inject(PersonRepository)\n private readonly personRepository: PersonRepository,\n ) {}\n```\n\n```text\nimport { DataSource } from 'typeorm';\nrequire('dotenv').config();\n\nexport const AppDataSource = new DataSource({\n type: 'mongodb',\n url: process.env.MONGO_URI,\n useNewUrlParser: true,\n synchronize: true,\n logging: true,\n database: process.env.DB_DATABASE,\n entities: ['dist/entities/*.js'],\n useUnifiedTopology: true,\n});\n\nAppDataSource.initialize()\n .then(() => {\n console.log('Data Source has been initialized!');\n })\n .catch((err) => {\n console.error('Error during Data Source initialization', err);\n });\n```\n\n```text\nimport { AppDataSource } from '@CustomDataSource';\nimport { Product } from '@Entities';\nimport { CreateProductDto, UpdateProductDto } from '@Products';\n\nconst dataSource = AppDataSource;\nexport const ProductRepository = \ndataSource.getMongoRepository(Product).extend({\nasync findOneById(id: number): Promise<Product> {\n const product = await ProductRepository.findOne({ where: { id }});\n return product;\n },\nasync findMany(): Promise<Product[]> {\n const products = await ProductRepository.find();\n return products;\n },\n});\n```\n\n```text\ndatasource.ts\n```\n\n```text\normconfig.js\n```\n\n```text\nTypeORMModule.forFeature([])\n```\n\n```text\nthis\n```\n\n```text\nProductRepository\n```\n\n```text\nimport { Provider, Type } from '@nestjs/common';\nimport { getDataSourceToken, getRepositoryToken } from '@nestjs/typeorm';\nimport { DataSource, DataSourceOptions, Repository } from 'typeorm';\n\nexport function provideCustomRepository<T>(\n entity: Type<T>,\n repository: Type<Repository<T>>,\n dataSource?: DataSource | DataSourceOptions | string\n): Provider {\n return {\n provide: getRepositoryToken(entity),\n inject: [getDataSourceToken(dataSource)],\n useFactory(dataSource: DataSource) {\n const baseRepository = dataSource.getRepository(entity);\n return new repository(\n baseRepository.target,\n baseRepository.manager,\n baseRepository.queryRunner\n );\n },\n };\n}\n```\n\n```html\n<script src=\"https://gist.github.com/rhutchison/a530d89c37f1978a48dcee4bf2418cb7.js\"></script>\n```\n\n```text\nprovideCustomRepository\n```\n\n```js\n// user.repository.ts\n@Injectable()\nexport class UsersRepository extends Repository<UsersEntity> {\n constructor(private dataSource: DataSource) {\n super(UsersEntity, dataSource.createEntityManager());\n }\n\n async getById(id: string) {\n return this.findOne({ where: { id } });\n }\n // ...\n}\n```\n\n```js\n// user.service.ts\nexport class UserService {\n constructor(private readonly userRepository: UserRepository) {}\n\n async getById(id: string): Promise<User> {\n return this.userRepository.getById(id);\n }\n // ...\n}\n```\n\n```js\n// user.module.ts\n@Module({\n imports: [\n TypeOrmModule.forFeature([UserEntity])],\n // ...\n ],\n providers: [UserService, UserRepository],\n // ...\n})\nexport class UserModule {}\n```\n\n```text\nimport { Injectable, NotFoundException } from '@nestjs/common';\nimport { Task } from './task.entity';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\n\n@Injectable()\nexport class TasksService {\n constructor(\n @InjectRepository(Task)\n private taskRepository: Repository<Task>\n ) {}\n\n async getTasksById(id: number): Promise<Task> {\n const found = await this.taskRepository.findOne({ where: { id: id \n }});\n }\n}\n```\n\n```text\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Task {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column()\n title: string;\n}\n```\n\n```text\nimport { Injectable, NotFoundException } from '@nestjs/common';\nimport { DataSource, Repository } from 'typeorm';\nimport { Task } from './task.entity';\n\n@Injectable()\nexport class TasksRepository extends Repository<Task> {\n constructor(private dataSource: DataSource) {\n super(Task, dataSource.createEntityManager());\n }\n\n async getById(id: string): Promise<Task> {\n const found = await this.findOneBy({ id });\n\n if (!found) {\n throw new NotFoundException(`Task with ID \"${id}\" not found`);\n }\n\n return found;\n }\n}\n```\n\n```text\nimport {\n Controller,\n Get,\n Param,\n} from '@nestjs/common';\nimport { TasksService } from './tasks.service';\nimport { Task } from './task.entity';\n\n@Controller('tasks')\nexport class TasksController {\n constructor(private tasksService: TasksService) {}\n\n @Get('/:id')\n getTaskById(@Param('id') id: string): Promise<Task> {\n return this.tasksService.getTaskById(id);\n }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Task } from './task.entity';\nimport { TasksController } from './tasks.controller';\nimport { TasksRepository } from './tasks.repository';\nimport { TasksService } from './tasks.service';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Task])],\n controllers: [TasksController],\n providers: [TasksService, TasksRepository],\n})\nexport class TasksModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TasksModule } from './tasks/tasks.module';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [\n TasksModule,\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'postgres',\n database: 'task-management',\n autoLoadEntities: true,\n synchronize: true,\n }),\n ],\n})\nexport class AppModule {}\n```\n\n```js\n// some-entity.repository.ts\nimport { EntityRepository, Repository } from 'typeorm';\nimport { SomeEntity } from './entities/some-entity.entity'; // Adjust path as necessary\nimport { Injectable } from '@nestjs/common';\nimport { DataSource } from 'typeorm';\n\n@Injectable()\nexport class SomeEntityRepository extends Repository<SomeEntity> {\n constructor(private dataSource: DataSource) {\n super();\n this.manager = dataSource.createEntityManager();\n }\n\n // You can add custom repository methods here if needed\n}\n```\n\n```js\n// some-entity.module.ts\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { SomeEntityController } from './controllers/some-entity.controller'; // Adjust path as necessary\nimport { SomeEntityService } from './services/some-entity.service'; // Adjust path as necessary\nimport { SomeEntityRepository } from './repositories/some-entity.repository'; // Adjust path as necessary\nimport { SomeEntity } from './entities/some-entity.entity'; // Adjust path as necessary\n\n@Module({\n imports: [\n TypeOrmModule.forFeature([SomeEntity, SomeEntityRepository]),\n // Other modules or imports\n ],\n controllers: [SomeEntityController],\n providers: [SomeEntityService, SomeEntityRepository], // Include SomeEntityRepository as a provider if needed\n exports: [SomeEntityRepository], // Export SomeEntityRepository if needed\n})\nexport class SomeEntityModule {}\n```\n\n```js\n// some-entity.service.ts\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\nimport { SomeEntity } from './entities/some-entity.entity'; // Adjust path as necessary\nimport { SomeEntityRepository } from './repositories/some-entity.repository'; // Adjust path as necessary\n\n@Injectable()\nexport class SomeEntityService {\n constructor(\n @InjectRepository(SomeEntityRepository)\n private someEntityRepository: SomeEntityRepository,\n ) {}\n\n // Implement service methods using someEntityRepository\n}\n```\n\n```text\nSomeEntity\n```\n\n```text\nEntityRepository\n```\n\n```text\nSomeEntity\n```\n\n```text\nRepository<SomeEntity>\n```\n\n```text\nSomeEntityRepository\n```\n\n```text\nSomeEntityRepository\n```\n\n```text\nSomeEntityService\n```\n\n```js\n@Injectable()\nexport class TaskRepository extends Repository<Task> {\n constructor(private dataSource: DataSource) {\n super(Task, dataSource.createEntityManager());\n }\n\n async createTask(createTaskDto: CreateTaskDto): Promise<Task> {\n const { title, description } = createTaskDto;\n const task = this.create({\n title,\n description,\n status: TaskStatus.OPEN,\n });\n await this.save(task);\n return task;\n }\n}\n```\n\n```js\nexport class TasksService {\n private tasks: Task[] = [];\n\n constructor(@Inject(TaskRepository) private readonly taskRepository: TaskRepository) {}\n\n async createTask(createTaskDto: CreateTaskDto): Promise<Task> {\n return this.taskRepository.createTask(createTaskDto);\n }\n}\n```\n\n```js\nimport { Module } from \"@nestjs/common\";\nimport { TasksController } from \"./tasks.controller\";\nimport { TasksService } from \"./tasks.service\";\nimport { TypeOrmModule } from \"@nestjs/typeorm\";\nimport { TaskRepository } from \"./dto/task.repository\";\nimport { Task } from \"./dto/task.entity\";\n\n@Module({\n imports: [TypeOrmModule.forFeature([Task])],\n controllers: [TasksController],\n providers: [TasksService, TaskRepository],\n})\nexport class TasksModule {}\n```\n\n```text\n\"@nestjs/typeorm\": \"^10.0.2\"\n```\n\n```text\n\"typeorm\": \"^0.3.20\"\n```\n\n========================================\n\nComments:\n- I guess it's better to use `typeorm@0.2` for now. Also, see this PR: github.com/nestjs/typeorm/pull/384\n- doesnt help the old implementation of extending repositories suing @Entityrepository decorator\n- To those arriving here from Google: this certainly works, but is much more complicated than this solution\n- This approach is much simpler and cleaner. It also works for those who were extending from the `AbstractRepository` in earlier versions of TypeORM.\n- Just tried this with nestjs v10.2.7, nestjs/typeorm v10.0.0 and typeorm v0.3.17 and it works. Cleanest solution to this that I've seen yet.\n- In `user.service.ts`, the constructor is missing to define the @Inject(UserRepository). It should be like this: `constructor(@Inject(UserRepository) private readonly userRepository: UserRepository) {}` Before that, I had tried following the code snippet, but it did not work until I added `@Inject(UserRepository)` by following the comment below of Zoltan Rakottyai","metadata":{"transformedAt":"2026-08-18T18:33:44.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":46,"totalLines":593,"estimatedTokens":3538}}43{"id":"stack-64401212","source":"stackoverflow","questionId":64401212,"title":"How to select specific columns in typeorm querybuilder","tags":["sql","typescript","typeorm"],"text":"Title: How to select specific columns in typeorm querybuilder\nTags: sql, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI tried to select specific columns by joining tables in typeorm.\n\nWhen I see following materials there is sample code.\n\nhttps://orkhan.gitbook.io/typeorm/docs/select-query-builder#joining-relations\n\n```\nconst user = await createQueryBuilder(\"user\")\n .leftJoinAndSelect(\"user.photos\", \"photo\")\n .where(\"user.name = :name\", { name: \"Timber\" })\n .getOne();\n```\n\n```\nimport {Entity, PrimaryGeneratedColumn, Column, OneToMany} from \"typeorm\";\nimport {Photo} from \"./Photo\";\n\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToMany(type => Photo, photo => photo.user)\n photos: Photo[];\n}\n```\n\n```\nimport {Entity, PrimaryGeneratedColumn, Column, ManyToOne} from \"typeorm\";\nimport {User} from \"./User\";\n\n@Entity()\nexport class Photo {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n url: string;\n\n @ManyToOne(type => User, user => user.photos)\n user: User;\n}\n```\n\nfor example my desired result is following.`where user.name ==\"Timber\"`\n\n```\n{\nid: user.id\nname: user.name\nurl: photo.url\n}\n```\n\nAre there any good way to achieve this ?\n\nThanks\n\n========================================\n\nTop Answer:\nWhen you want to select particular columns you have to use getRawOne like below,\n\n```\nconst user = await createQueryBuilder(\"user\")\n .leftJoinAndSelect(\"user.photos\", \"photo\")\n .select(['user.id', 'user.name', 'photo.url']) \n .where(\"user.name = :name\", { name: \"Timber\" })\n .getRawOne();\n```\n\n========================================\n\nCode:\n```text\nconst user = await createQueryBuilder(\"user\")\n .leftJoinAndSelect(\"user.photos\", \"photo\")\n .where(\"user.name = :name\", { name: \"Timber\" })\n .getOne();\n```\n\n```text\nimport {Entity, PrimaryGeneratedColumn, Column, OneToMany} from \"typeorm\";\nimport {Photo} from \"./Photo\";\n\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToMany(type => Photo, photo => photo.user)\n photos: Photo[];\n}\n```\n\n```text\nimport {Entity, PrimaryGeneratedColumn, Column, ManyToOne} from \"typeorm\";\nimport {User} from \"./User\";\n\n@Entity()\nexport class Photo {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n url: string;\n\n @ManyToOne(type => User, user => user.photos)\n user: User;\n}\n```\n\n```text\n{\nid: user.id\nname: user.name\nurl: photo.url\n}\n```\n\n```text\nwhere user.name ==\"Timber\"\n```\n\n```text\nconst user = await createQueryBuilder(\"user\")\n .leftJoinAndSelect(\"user.photos\", \"photo\")\n .select(['user.id', 'user.name', 'photo.url']) // added selection\n .where(\"user.name = :name\", { name: \"Timber\" })\n .getOne();\n```\n\n```text\n{\n id: 1,\n name: 'Timber',\n photos: [{ url: 'someurl1' }, ..., { url: 'someurlN' }]\n}\n```\n\n```text\nconst user = await createQueryBuilder(\"user\")\n .leftJoinAndSelect(\"user.photos\", \"photo\")\n .select(['user.id', 'user.name', 'photo.url']) \n .where(\"user.name = :name\", { name: \"Timber\" })\n .getRawOne();\n```\n\n========================================\n\nComments:\n- How to assign alias for those selected columns? I tried `.select(['user.id', 'user.name', 'photo.url'],['userId','username','url'])`, but this approach did not work\n- @AkhilMohandas try `.select(['user.id AS userId', 'user.name AS username', 'photo.url AS url'])`\n- @ArtOlshansky I have tried `'delivery.delivery_type AS type'` with `getOne`. unable to get alias. its working with getRawOne().but I need getOne(). stackoverflow.com/q/72901411/4909563\n- Make sure to not put the aliases in quotation marks. E.g. this doesn't work: .select([\"user\".\"id\", \"user\".\"name\"]). Doing this only works with getRawOne(). For the mapping to work, the aliases must not be in quotes.\n- Just wanna complete this answers: In my experience, it does not matter if you wanna use `getRawMany`, `getRawOne`, or `execute`, or other methods. You need to keep in mind that for some reason you need to chain your `select` at the end of the methods -- `createQueryBuilder(\"tb\").leftJoinAndSelect(\"tb.tb2\", \"tb2\").otherMethods().select([/* fields */]).getOne();`","metadata":{"transformedAt":"2026-08-18T18:33:44.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":171,"estimatedTokens":1041}}44{"id":"stack-64337340","source":"stackoverflow","questionId":64337340,"title":"How can I get soft deleted entity from typeorm postgreSQL?","tags":["node.js","typescript","postgresql","express","typeorm"],"text":"Title: How can I get soft deleted entity from typeorm postgreSQL?\nTags: node.js, typescript, postgresql, express, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to get soft deleted doc from `postgreSQL` database using `typeorm` `find, findOne or query builder get/getMany` methods, but it always return undefined. Is there a way to get deleted value?\n\nBy the docs it should only set a timestamp for `deletedAt`, and it definitely works, because I can update same record using update where from query builder.\n\n========================================\n\nTop Answer:\nActually referring to the findOptions doc you can pass the `withDeleted` boolean that will retrieve the soft deleted rows.\n\nfor example:\n\n```\nconst result = await this.repo.find({ where: { id }, withDeleted: true })\n```\n\n========================================\n\nCode:\n```text\npostgreSQL\n```\n\n```text\ntypeorm\n```\n\n```text\nfind, findOne or query builder get/getMany\n```\n\n```text\ndeletedAt\n```\n\n```text\nconst query = await this.manager\n .getRepository(FolderEntity)\n .withDeleted() \n .createQueryBuilder('folder')\n .leftJoinAndSelect('folder.subStatus', 'status')\n .getMany()\n```\n\n```text\n.withDeleted()\n```\n\n```text\nconst deletedEntity = await connection\n .getRepository(Entity)\n .query(`SELECT * FROM Entity where id = '${deletedEntityId}'`)\n```\n\n```text\nconst result = await this.repo.find({ where: { id }, withDeleted: true })\n```\n\n```text\nwithDeleted\n```\n\n```js\nconst queryBuilder = await this.yourRepository.createQueryBuilder('entity');\nqueryBuilder.withDeleted();\nqueryBuilder.where(`entity.deleted_at IS NOT NULL`)};\n```\n\n```text\nawait getManager().transaction(async (em) => {\n await em.update(Faqs, { id }, { updatedAt: userId });\n await em.softDelete(Faqs, id);\n});\n```\n\n```js\nimport { IsNull, Not } from 'typeorm';\n\n//...\nthis.yourRepository.find({\n where: {\n deletedAt: Not(IsNull()),\n },\n withDeleted: true,\n});\n```\n\n```text\nfind\n```\n\n```text\nfindOne\n```\n\n========================================\n\nComments:\n- This is odd. Your proposed solution is not the *only* solution\n- Yes, I've proposed a solution that I've found by myself, but after the month the better answer came and I accepted the new one by @BunyamiN as the better one.\n- This is great! Thanks. Would've helped me when I needed it, but I will definitely remember it later on :)","metadata":{"transformedAt":"2026-08-18T18:33:44.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":105,"estimatedTokens":595}}45{"id":"stack-61273794","source":"stackoverflow","questionId":61273794,"title":"Differences between entity manager and repository typeorm","tags":["node.js","typeorm"],"text":"Title: Differences between entity manager and repository typeorm\nTags: node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nI don't understand the differences between Entity manager and Repository in typeorm. They seem to do the same thing. If it's the same, why two different API exists. If not what are the differences and when we use them.\n\n========================================\n\nTop Answer:\nIt does exactly the same thing just an alias\n\neither you do\n\n**Option 1:**\n\n```\nconst manager = getManager();\nmanager.find(Methodology);\nmanager.find(Infrastructure);\nmanager.find(Safety);\n```\n\n**Option 2:**\n\n```\ngetRepository(Methodology).find();\ngetRepository(Infrastructure).find();\ngetRepository(Safety).find();\n```\n\n========================================\n\nCode:\n```text\nconst manager = getManager();\n// ...\nconst user = manager.create(User); // same as const user = new User();\n\nconst repository = connection.getRepository(User);\n// ...\nconst user = repository.create(); // same as const user = new User();\n```\n\n```text\nconst manager = getManager();\nmanager.find(Methodology);\nmanager.find(Infrastructure);\nmanager.find(Safety);\n```\n\n```text\ngetRepository(Methodology).find();\ngetRepository(Infrastructure).find();\ngetRepository(Safety).find();\n```\n\n========================================\n\nComments:\n- Are there any other differences? e.g. performance?","metadata":{"transformedAt":"2026-08-18T18:33:44.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":61,"estimatedTokens":340}}46{"id":"stack-66168437","source":"stackoverflow","questionId":66168437,"title":"TypeORM findOne with nested relations","tags":["javascript","node.js","postgresql","typeorm"],"text":"Title: TypeORM findOne with nested relations\nTags: javascript, node.js, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am having some issues performing a nested find query with TypeORM. Here's the basic code:\n\n```\nconst { completionId } = req?.params;\n const user = req.user;\n\n const retrievedCompletion = await getRepository(\n CompletionGoogleSearch\n ).findOne({\n relations: ['run', 'run.user'],\n where: {\n id: completionId,\n // run: { user: { id: user.id } }, // This is the code that breaks the function\n },\n });\n\n console.log(retrievedCompletion?.run.user.id);\n console.log(user.id);\n```\n\nIt looks to me like there's nothing out of order, and that the query should run. Any idea on what I am doing wrong? I know I can get around this issue by writing a querybuilder query or using raw SQL–I am just curious to understand if there's a flaw in my code.\n\n========================================\n\nTop Answer:\ntypeorm added the ability to use nested object\n\n```\nuserRepository.find({\n relations: {\n profile: true,\n photos: true,\n videos: {\n videoAttributes: true,\n },\n },\n});\n```\n\non this way, you can fetch the data without using eager.\n\nYou can find more information here\n\n========================================\n\nCode:\n```js\nconst { completionId } = req?.params;\n const user = req.user;\n\n const retrievedCompletion = await getRepository(\n CompletionGoogleSearch\n ).findOne({\n relations: ['run', 'run.user'],\n where: {\n id: completionId,\n // run: { user: { id: user.id } }, // This is the code that breaks the function\n },\n });\n\n console.log(retrievedCompletion?.run.user.id);\n console.log(user.id);\n```\n\n```text\n@OneToOne(() => User, User=> User.run, {\n eager:true\n })\n user: User;\n```\n\n```text\neager:true\n```\n\n```text\nrun.user\n```\n\n```text\nCompletionGoogleSearch\n```\n\n```text\nrelations: ['run']\n```\n\n```text\nuserRepository.find({\n relations: {\n profile: true,\n photos: true,\n videos: {\n videoAttributes: true,\n },\n },\n});\n```\n\n```text\nnode_modules/typeorm/find-options/FindOptionsUtils.js\n```\n\n```text\njoinAlreadyAdded\n```\n\n========================================\n\nComments:\n- The lastest typeorm version now support this.\n- Your answer is also correct. I tried with my application and it worked with no issues. If I want to go with less json fields then I will choose @Yoav St his approach.\n- your answer is correct. I tried with my application and it worked with no issues.\n- I honestly don't understand this answer. It doesn't even contain an entire query, the `where` clause is missing.","metadata":{"transformedAt":"2026-08-18T18:33:44.685Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":119,"estimatedTokens":646}}47{"id":"stack-57099863","source":"stackoverflow","questionId":57099863,"title":"SpyOn TypeORM repository to change the return value for unit testing NestJS","tags":["nestjs","typeorm"],"text":"Title: SpyOn TypeORM repository to change the return value for unit testing NestJS\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI would like to unittest corner cases for my TypeORM database calls. I have already mocked all my TypeORM repositories with valid data. But I would like to SpyOn the repository and change the return value form TypeORM. How do I do that?\n\n```\nimport {INestApplication} from '@nestjs/common';\nimport {Test} from '@nestjs/testing';\nimport {CommonModule} from '@src/common/common.module';\nimport {AuthService} from './auth.service';\nimport {Repository} from 'typeorm';\nimport {V3User} from '@src/database/entity/user.v3entity';\n \ndescribe('AuthService', () => {\n let service: AuthService;\n let app: INestApplication;\n \n beforeEach(async () => {\n const module = await Test.createTestingModule({\n imports: [CommonModule.forRoot(`${process.env.DEV_ENV}`)],\n providers: [\n AuthService, \n {provide: 'V3USER_REPOSITORY', useValue: mockRepositoryV3User()},\n ],\n }).compile();\n \n app = module.createNestApplication();\n await app.init();\n \n service = module.get(AuthService);\n });\n \n\n \n it('test auth service - with non existing user in v3 db', async () => {\n \n jest.spyOn(?????? , 'findOne').mockImplementation(() => undefined);\n \n const res = await service.loginUser(\"bad token\");\n \n await expect(service.tokenBasedAuth('example bad token'))\n .rejects.toThrow('bad token exception');\n });\n});\n```\n\nI mock the database like this for normal test cases:\n\n```\nexport const mockRepositoryV3User = () => ({\n metadata: {\n columns: [],\n relations: [],\n },\n findOne: async () =>\n Promise.resolve({\n id: 3,\n email: 'email@example.com',\n first_name: 'david',\n last_name: 'david',\n last_login: '2019-07-15',\n date_joined: '2019-07-15',\n }),\n});\n```\n\n========================================\n\nCode:\n```js\nimport {INestApplication} from '@nestjs/common';\nimport {Test} from '@nestjs/testing';\nimport {CommonModule} from '@src/common/common.module';\nimport {AuthService} from './auth.service';\nimport {Repository} from 'typeorm';\nimport {V3User} from '@src/database/entity/user.v3entity';\n \ndescribe('AuthService', () => {\n let service: AuthService;\n let app: INestApplication;\n \n beforeEach(async () => {\n const module = await Test.createTestingModule({\n imports: [CommonModule.forRoot(`${process.env.DEV_ENV}`)],\n providers: [\n AuthService, \n {provide: 'V3USER_REPOSITORY', useValue: mockRepositoryV3User()},\n ],\n }).compile();\n \n app = module.createNestApplication();\n await app.init();\n \n service = module.get<AuthService>(AuthService);\n });\n \n\n \n it('test auth service - with non existing user in v3 db', async () => {\n \n jest.spyOn(?????? , 'findOne').mockImplementation(() => undefined);\n \n const res = await service.loginUser(\"bad token\");\n \n await expect(service.tokenBasedAuth('example bad token'))\n .rejects.toThrow('bad token exception');\n });\n});\n```\n\n```js\nexport const mockRepositoryV3User = () => ({\n metadata: {\n columns: [],\n relations: [],\n },\n findOne: async () =>\n Promise.resolve({\n id: 3,\n email: 'email@example.com',\n first_name: 'david',\n last_name: 'david',\n last_login: '2019-07-15',\n date_joined: '2019-07-15',\n }),\n});\n```\n\n```js\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Photo {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ length: 500 })\n name: string;\n\n @Column('text')\n description: string;\n\n @Column()\n filename: string;\n\n @Column('int')\n views: number;\n\n @Column()\n isPublished: boolean;\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\nimport { Photo } from './photo.entity';\n\n@Injectable()\nexport class PhotoService {\n constructor(\n @InjectRepository(Photo)\n private readonly photoRepository: Repository<Photo>,\n ) {}\n\n async findAll(): Promise<Photo[]> {\n return await this.photoRepository.find();\n }\n}\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { PhotoService } from './photo.service';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport { Photo } from './photo.entity';\nimport { Repository } from 'typeorm';\n\ndescribe('PhotoService', () => {\n let service: PhotoService;\n // declaring the repo variable for easy access later\n let repo: Repository<Photo>;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n PhotoService,\n {\n // how you provide the injection token in a test instance\n provide: getRepositoryToken(Photo),\n // as a class value, Repository needs no generics\n useClass: Repository,\n },\n ],\n }).compile();\n\n service = module.get<PhotoService>(PhotoService);\n // Save the instance of the repository and set the correct generics\n repo = module.get<Repository<Photo>>(getRepositoryToken(Photo));\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n\n it('should return for findAll', async () => {\n // mock file for reuse\n const testPhoto: Photo = {\n id: 'a47ecdc2-77d6-462f-9045-c440c5e4616f',\n name: 'hello',\n description: 'the description',\n isPublished: true,\n filename: 'testFile.png',\n views: 5,\n };\n // notice we are pulling the repo variable and using jest.spyOn with no issues\n jest.spyOn(repo, 'find').mockResolvedValueOnce([testPhoto]);\n expect(await service.findAll()).toEqual([testPhoto]);\n });\n});\n```\n\n```sh\n▶ npm run test -- photo.service\n\n> nestjs-playground@0.0.1 test ~/Documents/code/nestjs-playground\n> jest \"photo.service\"\n\n PASS src/photo/photo.service.spec.ts\n PhotoService\n ✓ should be defined (17ms)\n ✓ should return for findAll (4ms) < -- test passes with no problem\n\nTest Suites: 1 passed, 1 total\nTests: 2 passed, 2 total\nSnapshots: 0 total\nTime: 3.372s, estimated 4s\nRan all test suites matching /photo.service/i.\n```\n\n```text\nPhotoEntity\n```\n\n```text\nPhotoService\n```\n\n```text\nuseClass: Repository\n```\n\n========================================\n\nComments:\n- Excellent. Works flawlessly.\n- How to test if the query was like .createQueryBuilder('image').offset(pagination.offset).limit‌​(pagination.limit).g‌​etManyAndCount();\n- For something like that, you'd need a lot of `mockReturnThis()` kind of jest functions with a final one with `mockresolvedValue()`. You'll probably end up having several mocks or spies, one for each that is chained minus the final on, so a `jest.spyOn(repo, 'createQueryBuilder')`, a `jest.spyOn(repo, 'offset'), etc, and your repo should probably set up an initial`createQueryBuilder` method. To go more in depth, this question should really be asked as a separate question\n- I'm following your approach but on line `.mockResolvedValueOnce([testPhoto])` I keep getting `Type MyEntity is not assignable to type never` - did you have that issue?\n- @asus as discussed on Discord, you were trying to use `mockResolvedValueOnce` on a synchronous function. Instead, you should use `mockReturnValueOnce`.\n- @JayMcDoniel for some reason I am getting this error `Error: Cannot spy the find property because it is not a function; undefined given instead` I am sure I followed your steps\n- @MFarahat make a reproducing repository on GitHub, or a Gist. It's not gonna be possible to trouble shoot it in the comments. Terrible formatting\n- @JayMcDoniel heres the repo github.com/mfarahat/backend-demo/tree/feature/customer/src/…\n- @JayMcDoniel Thank you very much for the solution, banged my head around this issue for 3 days straight before stumbling across your answer :)\n- @JayMcDoniel Thank you very much. I was getting mad about this issue and Corona LockDown. You saved me.\n- @JayMcDoniel i got the msg of TypeError: Right-hand side of 'instanceof' is not an object, i guess is module resolve issue, would you mind to ur repo to me\n- THANK YOU. I was beating my head against the wall trying to do this with `automock`, but this way *works*.","metadata":{"transformedAt":"2026-08-18T18:33:44.685Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":270,"estimatedTokens":2085}}48{"id":"stack-60363353","source":"stackoverflow","questionId":60363353,"title":"TypeORM OneToMany causes \"ReferenceError: Cannot access '' before initialization\"","tags":["typescript","nestjs","typeorm","nrwl-nx"],"text":"Title: TypeORM OneToMany causes \"ReferenceError: Cannot access '' before initialization\"\nTags: typescript, nestjs, typeorm, nrwl-nx\nSource: Stack Overflow\n\nQuestion:\nI have two entities: **User** and **Habit**. \nA user can create multiple Habits, thus I use a **OneToMany** relation on the User (and **ManyToOne** on the Habit, respectively).\n\n### User Entity\n\n```\nimport {Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, BeforeInsert, BeforeUpdate, OneToMany} from \"typeorm\";\nimport * as bcrypt from \"bcryptjs\";\nimport { Habit } from \"../habits/habits.entity\";\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn(\"uuid\")\n id: string;\n\n @Column()\n name: string;\n\n @Column()\n email: string;\n\n @Column()\n password: string;\n\n @OneToMany(type => Habit, habit => habit.author)\n habits: Habit[];\n\n @CreateDateColumn()\n dateCreated: Date;\n\n @UpdateDateColumn()\n dateUpdated: Date;\n\n @BeforeInsert()\n @BeforeUpdate()\n async hashPassword(): Promise {\n this.password = await bcrypt.hash(this.password,10);\n }\n\n async comparePassword(password: string): Promise {\n return bcrypt.compare(password, this.password);\n }\n\n constructor(props: any) {\n Object.assign(this, props);\n }\n}\n```\n\n### Habit Entity\n\n```\nimport {Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn, ManyToOne} from \"typeorm\";\nimport { User } from \"../users/users.entity\";\n\n@Entity()\nexport class Habit {\n @PrimaryGeneratedColumn(\"uuid\")\n id: string;\n\n @Column()\n name: string;\n\n @Column({ nullable: true})\n description?: string;\n\n @ManyToOne(type => User, user => user.habits)\n author: User;\n\n @CreateDateColumn()\n dateCreated: Date;\n\n @UpdateDateColumn()\n dateUpdated: Date;\n\n constructor(props: Partial) {\n Object.assign(this, props);\n }\n}\n```\n\n### Problem\n\nWhen setting up the above relation I receive the following error\n\n```\nWARNING in Circular dependency detected:\napps\\api\\src\\habits\\habits.entity.ts -> apps\\api\\src\\users\\users.entity.ts -> apps\\api\\src\\habits\\habits.entity.ts\n\nWARNING in Circular dependency detected:\napps\\api\\src\\users\\users.entity.ts -> apps\\api\\src\\habits\\habits.entity.ts -> apps\\api\\src\\users\\users.entity.ts\n\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"User\", function() { return User; });\n ^\nReferenceError: Cannot access 'User' before initialization\n at Module.User (...\\dist\\apps\\api\\main.js:1782:96)\n at Module../apps/api/src/habits/habits.entity.ts (...\\dist\\apps\\api\\webpack:\\apps\\api\\src\\habits\\habits.entity.ts:42:13)\n at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n at Module../apps/api/src/users/users.entity.ts (...\\dist\\apps\\api\\main.js:1790:79)\n at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n at Module../apps/api/src/config/db-config.service.ts (...\\dist\\apps\\api\\main.js:1038:77)\n at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n at Module../apps/api/src/config/config.module.ts (...\\dist\\apps\\api\\main.js:978:76)\n at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n at Module../apps/api/src/app/app.module.ts (...\\dist\\apps\\api\\main.js:147:79)\n```\n\n### Note\n\nI use **Nx** and have created a **NestJS** app.\nThe TypeOrm version is **\"^0.2.22\"** and the @nestjs/typeorm version is **\"^6.2.0\"**\n\nMy **tsconfig** is as follows:\n\n```\n{\n \"compileOnSave\": false,\n \"compilerOptions\": {\n \"rootDir\": \".\",\n \"sourceMap\": true,\n \"declaration\": false,\n \"moduleResolution\": \"node\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"importHelpers\": true,\n \"target\": \"es2015\",\n \"module\": \"esnext\",\n \"typeRoots\": [\"node_modules/@types\"],\n \"lib\": [\"es2018\", \"dom\"],\n \"skipLibCheck\": true,\n \"skipDefaultLibCheck\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"@awhile/contracts\": [\"libs/contracts/src/index.ts\"],\n \"@awhile/ui\": [\"libs/ui/src/index.ts\"]\n }\n },\n \"exclude\": [\"node_modules\", \"tmp\"]\n}\n```\n\nI have tried to use a **ManyToMany** relation and it worked. Also, on a separate NestJS app (without Nx) I cannot reproduce this reference error.\nChanging the ECMAScript **target** version in the **tsconfig.json** also did not work.\n\nBoth entities are only used in their services and are not instantiated anywhere else.\n\nI appreciate any help. Thank you in advance.\n\n========================================\n\nTop Answer:\nUse the `Relation` type wrapper to avoid circular dependency issues, as described here.\n\nFor example:\n\n```\nimport {Entity, OneToMany, Relation} from \"typeorm\";\nimport {Habit} from \"../habits/habits.entity\";\n\n@Entity()\nexport class User {\n ...\n\n @OneToMany(type => Habit, habit => habit.author)\n habits: Relation[];\n\n ...\n}\n```\n\n========================================\n\nCode:\n```ts\nimport {Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, BeforeInsert, BeforeUpdate, OneToMany} from \"typeorm\";\nimport * as bcrypt from \"bcryptjs\";\nimport { Habit } from \"../habits/habits.entity\";\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn(\"uuid\")\n id: string;\n\n @Column()\n name: string;\n\n @Column()\n email: string;\n\n @Column()\n password: string;\n\n @OneToMany(type => Habit, habit => habit.author)\n habits: Habit[];\n\n @CreateDateColumn()\n dateCreated: Date;\n\n @UpdateDateColumn()\n dateUpdated: Date;\n\n @BeforeInsert()\n @BeforeUpdate()\n async hashPassword(): Promise<void> {\n this.password = await bcrypt.hash(this.password,10);\n }\n\n async comparePassword(password: string): Promise<boolean> {\n return bcrypt.compare(password, this.password);\n }\n\n constructor(props: any) {\n Object.assign(this, props);\n }\n}\n```\n\n```ts\nimport {Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn, ManyToOne} from \"typeorm\";\nimport { User } from \"../users/users.entity\";\n\n@Entity()\nexport class Habit {\n @PrimaryGeneratedColumn(\"uuid\")\n id: string;\n\n @Column()\n name: string;\n\n @Column({ nullable: true})\n description?: string;\n\n @ManyToOne(type => User, user => user.habits)\n author: User;\n\n @CreateDateColumn()\n dateCreated: Date;\n\n @UpdateDateColumn()\n dateUpdated: Date;\n\n constructor(props: Partial<Habit>) {\n Object.assign(this, props);\n }\n}\n```\n\n```bash\nWARNING in Circular dependency detected:\napps\\api\\src\\habits\\habits.entity.ts -> apps\\api\\src\\users\\users.entity.ts -> apps\\api\\src\\habits\\habits.entity.ts\n\nWARNING in Circular dependency detected:\napps\\api\\src\\users\\users.entity.ts -> apps\\api\\src\\habits\\habits.entity.ts -> apps\\api\\src\\users\\users.entity.ts\n\n\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"User\", function() { return User; });\n ^\nReferenceError: Cannot access 'User' before initialization\n at Module.User (...\\dist\\apps\\api\\main.js:1782:96)\n at Module../apps/api/src/habits/habits.entity.ts (...\\dist\\apps\\api\\webpack:\\apps\\api\\src\\habits\\habits.entity.ts:42:13)\n at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n at Module../apps/api/src/users/users.entity.ts (...\\dist\\apps\\api\\main.js:1790:79)\n at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n at Module../apps/api/src/config/db-config.service.ts (...\\dist\\apps\\api\\main.js:1038:77)\n at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n at Module../apps/api/src/config/config.module.ts (...\\dist\\apps\\api\\main.js:978:76)\n at __webpack_require__ (...\\dist\\apps\\api\\webpack:\\webpack\\bootstrap:19:1)\n at Module../apps/api/src/app/app.module.ts (...\\dist\\apps\\api\\main.js:147:79)\n```\n\n```json\n{\n \"compileOnSave\": false,\n \"compilerOptions\": {\n \"rootDir\": \".\",\n \"sourceMap\": true,\n \"declaration\": false,\n \"moduleResolution\": \"node\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"importHelpers\": true,\n \"target\": \"es2015\",\n \"module\": \"esnext\",\n \"typeRoots\": [\"node_modules/@types\"],\n \"lib\": [\"es2018\", \"dom\"],\n \"skipLibCheck\": true,\n \"skipDefaultLibCheck\": true,\n \"baseUrl\": \".\",\n \"paths\": {\n \"@awhile/contracts\": [\"libs/contracts/src/index.ts\"],\n \"@awhile/ui\": [\"libs/ui/src/index.ts\"]\n }\n },\n \"exclude\": [\"node_modules\", \"tmp\"]\n}\n```\n\n```text\n{\n \"extends\": \"../../tsconfig.json\",\n \"compilerOptions\": {\n \"types\": [\"node\", \"jest\"],\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"module\": \"commonjs\",\n \"target\": \"esnext\"\n },\n \"include\": [\"**/*.ts\"]\n}\n```\n\n```text\n\"paths\": {\n \"@entities\":[\"app/src/entities/index.ts\"]\n}\n```\n\n```text\nexport * from './user.entity';\nexport * from './habit.entity';\n```\n\n```text\nimport { User, Habit } from '@entities';\n```\n\n```text\ncompilerOptions\n```\n\n```js\nimport {Entity, OneToMany, Relation} from \"typeorm\";\nimport {Habit} from \"../habits/habits.entity\";\n\n@Entity()\nexport class User {\n ...\n\n @OneToMany(type => Habit, habit => habit.author)\n habits: Relation<Habit>[];\n\n ...\n}\n```\n\n```text\nRelation\n```\n\n```text\nexport class CreateUser {\n @IsNotEmpty()\n userName: string\n @IsNotEmpty()\n photoURL: string\n @IsNotEmpty()\n displayName: string\n ...\n @IsDefined()\n @IsNotEmptyObject()\n @ValidateNested()\n @Type(() => CreateStreakConfig)\n streakConfig: CreateStreakConfig\n}\n\nexport class CreateStreakConfig {\n @IsNotEmpty()\n minimumDistance: number\n @IsNotEmpty()\n unitOfDistanceType: typeof STREAK_CONFIG_UNIT_OF_DISTANCE_MILES | typeof STREAK_CONFIG_UNIT_OF_DISTANCE_KILOMETERS\n}\n```\n\n```text\nexport class CreateStreakConfig {\n @IsNotEmpty()\n minimumDistance: number\n @IsNotEmpty()\n unitOfDistanceType: typeof STREAK_CONFIG_UNIT_OF_DISTANCE_MILES | typeof STREAK_CONFIG_UNIT_OF_DISTANCE_KILOMETERS\n}\n\nexport class CreateUser {\n @IsNotEmpty()\n userName: string\n @IsNotEmpty()\n photoURL: string\n @IsNotEmpty()\n displayName: string\n ...\n @IsDefined()\n @IsNotEmptyObject()\n @ValidateNested()\n @Type(() => CreateStreakConfig)\n streakConfig: CreateStreakConfig\n}\n```\n\n```json\n{\n \"$schema\": \"https://json.schemastore.org/nest-cli\",\n \"collection\": \"@nestjs/schematics\",\n \"sourceRoot\": \"src\",\n \"compilerOptions\": {\n \"deleteOutDir\": true,\n \"webpack\": true\n }\n}\n```\n\n```text\nimport {\n Entity,\n Column,\n PrimaryGeneratedColumn,\n OneToOne,\n JoinColumn,\n Relation,\n} from \"typeorm\"\nimport { Photo } from \"./Photo\"\n\n@Entity()\nexport class PhotoMetadata {\n /* ... other columns */\n\n @OneToOne(() => Photo, (photo) => photo.metadata)\n @JoinColumn()\n photo: Relation<Photo>\n}\n```\n\n```text\n@ManyToOne(() => EntityName, (ett) => ett.property)\nval: typeof EntityName;\n```\n\n```text\n@OneToMany('Habit', 'author')\nhabits: Habit[];\n```\n\n========================================\n\nComments:\n- This is indeed the case, after reordering my classes error disappeared. This is wrong, it shouldn't depend on the order, as with any javascript code where hoisting works.\n- I tried to get a vue electron app to work with typeorm. Error was: ReferenceError, can not use variable before declaration on an entity. That did the trick for me. Thanks!\n- Using this on an auto generated schema. Lots of hand work, but much less than creating the schema from scratch;\n- How do you make `paths` work with `ts-loader`?\n- This ended up working for my use case.\n- Adding `Relation` helped when I moved the project to use ESM modules.\n- It works with `OneToOne` as well. Greate!\n- While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review\n- A lot of thx!!!","metadata":{"transformedAt":"2026-08-18T18:33:44.686Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":457,"estimatedTokens":2922}}49{"id":"stack-64681418","source":"stackoverflow","questionId":64681418,"title":"Orderby on multiple columns using typeorm","tags":["mysql","sql","orm","sql-order-by","typeorm"],"text":"Title: Orderby on multiple columns using typeorm\nTags: mysql, sql, orm, sql-order-by, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn my application, I am using `MySQL` and `typeorm` and want to do `orderBy` using multiple columns. I searched so many places for it but did not get any solution.\n\nExample:\nI have two columns in a table user and respective User Entity\n\n________________________________________\n| id | name | createDate | createdTime |\n----------------------------------------\n| 1 | Sai | 2020-12-12 | 12:20:30 |\n........................................\n| 2 | Ravi | 2020-12-13 | 13:20:30 |\n........................................\n\nHere, I want to orderBy createdDate and CreateTime both using `typeorm` something like below.\n\n```\nCM.getRepository(User)\n .createQueryBuilder('user')\n .select([\"name\", \"id\"])\n .orderBy('user.createdDate', 'ASC')\n .AndOrderBy('user.createdTime', 'ASC')\n```\n\nPlease help me solve this.\n\nThank you...\n\n========================================\n\nTop Answer:\nHere is a shorthand version if you do not want to user Query Builder.\n\n```\nconst users = await User.find({\n where: { userId },\n order: { createdAt: \"ASC\", createdTime: \"ASC\" },\n });\n```\n\nIt will sort based on the first column createdAt first, then the second. column createdTime.\n\n========================================\n\nCode:\n```text\n________________________________________\n| id | name | createDate | createdTime |\n----------------------------------------\n| 1 | Sai | 2020-12-12 | 12:20:30 |\n........................................\n| 2 | Ravi | 2020-12-13 | 13:20:30 |\n........................................\n```\n\n```text\nCM.getRepository(User)\n .createQueryBuilder('user')\n .select([\"name\", \"id\"])\n .orderBy('user.createdDate', 'ASC')\n .AndOrderBy('user.createdTime', 'ASC')\n```\n\n```text\nMySQL\n```\n\n```text\ntypeorm\n```\n\n```text\norderBy\n```\n\n```text\ntypeorm\n```\n\n```text\n/**\n * Adds ORDER BY condition in the query builder.\n */\naddOrderBy(sort: string, order?: \"ASC\" | \"DESC\", nulls?: \"NULLS FIRST\" | \"NULLS LAST\"): this;\n```\n\n```text\nCM.getRepository(User)\n .createQueryBuilder('user')\n .select([\"name\", \"id\"])\n .orderBy('user.createdDate', 'ASC')\n .addOrderBy('user.createdTime', 'ASC')\n```\n\n```text\nAndOrderBy\n```\n\n```text\naddOrderBy\n```\n\n```text\nconst users = await User.find({\n where: { userId },\n order: { createdAt: \"ASC\", createdTime: \"ASC\" },\n });\n```\n\n========================================\n\nComments:\n- Although this code might answer the question, I recommend that you also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.\n- Does this guarantee which of the two columns take precedence, ie. `createdAt` first. If they are equal, sort by `crreatedTime`?","metadata":{"transformedAt":"2026-08-18T18:33:44.686Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":118,"estimatedTokens":723}}50{"id":"stack-59645009","source":"stackoverflow","questionId":59645009,"title":"How to return only some columns of a relations with Typeorm","tags":["postgresql","typescript","typeorm"],"text":"Title: How to return only some columns of a relations with Typeorm\nTags: postgresql, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nOk, I'm having trouble with getting the relations with typeorm. When I run the service it returns all the data from the relation, and I want only specific fields, like id and name.\n\nHere's my code:\n\n```\nasync findById(id: string): Promise {\nreturn await this.repository.findOne({\n where: { id },\n relations: ['userId', 'offerId'],\n });\n}\n```\n\nHere's the JSON output:\n\n```\n{\n\"id\": \"da0fd04e-17c6-4412-b342-a4361d191468\",\n\"createdAt\": \"2020-01-07T19:48:30.840Z\",\n\"userId\": {\n \"id\": \"bdc00227-569f-44b5-9bdd-c8de03661ebd\",\n \"name\": \"Alexandre Vieira\",\n \"cpf\": \"10443771430\",\n \"email\": \"av.souza2018@gmail.com\",\n \"password\": \"asjdsifjdsfasf\",\n \"imagePath\": \"/me.png\",\n \"active\": true,\n \"lastLogin\": \"2020-01-07T19:40:26.850Z\",\n \"createdAt\": \"2020-01-07T19:40:26.850Z\",\n \"updatedAt\": \"2020-01-07T19:40:26.850Z\"\n},\n\"offerId\": {\n \"id\": \"e399560c-d2c2-4f4e-b2b1-94cae3af3779\",\n \"offerDrescription\": \"Nova oferta top\",\n \"discountCoupon\": \" Desconto top\",\n \"discountValidity\": \"2020-01-07T14:18:19.803Z\",\n \"discountPercentage\": 20,\n \"discountQuantityLimit\": 50,\n \"createdAt\": \"2020-01-07T19:45:33.589Z\",\n \"updatedAt\": \"2020-01-07T19:45:33.589Z\"\n }\n}\n```\n\nHere's the output I want:\n\n```\n{\n\"id\": \"da0fd04e-17c6-4412-b342-a4361d191468\",\n\"createdAt\": \"2020-01-07T19:48:30.840Z\",\n\"userId\": {\n \"id\": \"bdc00227-569f-44b5-9bdd-c8de03661ebd\",\n \"name\": \"Alexandre Vieira\",\n \n},\n\"offerId\": {\n \"id\": \"e399560c-d2c2-4f4e-b2b1-94cae3af3779\",\n \"offerDrescription\": \"Nova oferta top\",\n \n }\n}\n```\n\n========================================\n\nTop Answer:\nYou can do it like this if you rather use the repository API instead of the queryBuilder\n\n```\nreturn await this.repository.findOne({\n where: { id },\n select: {\n userId: {\n id: true,\n name: true\n },\n offerId: {\n id: true,\n offerDrescription: true\n }\n },\n relations: {\n userId: true,\n offerId: true,\n }\n});\n```\n\n========================================\n\nCode:\n```text\nasync findById(id: string): Promise<UsersUseOfferHistoric> {\nreturn await this.repository.findOne({\n where: { id },\n relations: ['userId', 'offerId'],\n });\n}\n```\n\n```text\n{\n\"id\": \"da0fd04e-17c6-4412-b342-a4361d191468\",\n\"createdAt\": \"2020-01-07T19:48:30.840Z\",\n\"userId\": {\n \"id\": \"bdc00227-569f-44b5-9bdd-c8de03661ebd\",\n \"name\": \"Alexandre Vieira\",\n \"cpf\": \"10443771430\",\n \"email\": \"av.souza2018@gmail.com\",\n \"password\": \"asjdsifjdsfasf\",\n \"imagePath\": \"/me.png\",\n \"active\": true,\n \"lastLogin\": \"2020-01-07T19:40:26.850Z\",\n \"createdAt\": \"2020-01-07T19:40:26.850Z\",\n \"updatedAt\": \"2020-01-07T19:40:26.850Z\"\n},\n\"offerId\": {\n \"id\": \"e399560c-d2c2-4f4e-b2b1-94cae3af3779\",\n \"offerDrescription\": \"Nova oferta top\",\n \"discountCoupon\": \" Desconto top\",\n \"discountValidity\": \"2020-01-07T14:18:19.803Z\",\n \"discountPercentage\": 20,\n \"discountQuantityLimit\": 50,\n \"createdAt\": \"2020-01-07T19:45:33.589Z\",\n \"updatedAt\": \"2020-01-07T19:45:33.589Z\"\n }\n}\n```\n\n```text\n{\n\"id\": \"da0fd04e-17c6-4412-b342-a4361d191468\",\n\"createdAt\": \"2020-01-07T19:48:30.840Z\",\n\"userId\": {\n \"id\": \"bdc00227-569f-44b5-9bdd-c8de03661ebd\",\n \"name\": \"Alexandre Vieira\",\n \n},\n\"offerId\": {\n \"id\": \"e399560c-d2c2-4f4e-b2b1-94cae3af3779\",\n \"offerDrescription\": \"Nova oferta top\",\n \n }\n}\n```\n\n```ts\nawait getRepository(Foo).createQueryBuilder('foo')\n .where({ id: 1})\n .select(['foo.id', 'foo.createdAt', 'bar.id', 'bar.name'])\n .leftJoin('foo.bars', 'bar') // bar is the joined table\n .getMany();\n```\n\n```text\nfindOne\n```\n\n```text\nselect: ['id', 'createdAt']\n```\n\n```text\nrelations\n```\n\n```text\n...findOne({\n relations: [\"userId\", \"offerId\"],\n select: {\n id: true,\n createdAt: true,\n userId: {\n id: true,\n name: true,\n },\n offerId: {\n id: true,\n offerDrescription: true,\n },\n },\n ...\n where: {...},\n})\n```\n\n```js\nreturn await this.repository.findOne({\n where: { id },\n select: {\n userId: {\n id: true,\n name: true\n },\n offerId: {\n id: true,\n offerDrescription: true\n }\n },\n relations: {\n userId: true,\n offerId: true,\n }\n});\n```\n\n========================================\n\nComments:\n- got any solution for this ? don't want to. use createQueryBuilder()\n- What is `foo`??\n- `foo` is an alias for `Foo` table\n- It works from version **0.3.0**\n- This does not seem to work for many-to-one relations? (e.g. `select: { offers: { id: true } }`)\n- @Alex because relations: [\"userId\", \"offerId\"] is missing in query option\n- this answer is the best\n- This did not work for me as is, but with some modifications I got it to work. I had to specify the primitive property name as well as the relation name. So in this case to expand user while selecting only `id` and `name` I had to have a `userId: true` and a `user: { id: true, name: true}`","metadata":{"transformedAt":"2026-08-18T18:33:44.686Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":222,"estimatedTokens":1235}}51{"id":"stack-54535867","source":"stackoverflow","questionId":54535867,"title":"Is there a way to use configService in App.Module.ts?","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: Is there a way to use configService in App.Module.ts?\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am building RESTful service with NestJs, I have followed the example to build configurations for different environments. It works well for most code. However I am wondering if I can use it in my `app.module.ts`?\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mongodb',\n host: `${config.get('mongo_url') || 'localhost'}`,\n port: 27017,\n username: 'a',\n password: 'b',\n database: 'my_db',\n entities: [__dirname + '/MyApp/*.Entity{.ts,.js}'],\n synchronize: true}),\n MyModule,\n ConfigModule,\n ],\n controllers: [],\n providers: [MyService],\n})\nexport class AppModule { }\n```\n\nAs you can see I do want to move the MongoDb Url info outside the code and I am thinking to leverage `.env` files. But after some attempts, it does not seem to work.\n\nOf course I can use `${process.env.MONGODB_URL || 'localhost'}` instead, and set the environment variables. I'm still curious if I can make the `configService` work.\n\n========================================\n\nTop Answer:\nBetter to use MongooseModule function from the same package for config and properties as given below:\n\n```\nMongooseModule.forRootAsync({\n imports: [ConfigModule],\n useFactory: (configService: ConfigService) => ({\n uri: `mongodb://${configService.get(\n 'MONGODB_USERNAME',\n )}:${configService.get('MONGODB_PASSWORD')}@${configService.get(\n 'MONGODB_HOST',\n )}:27017/nest?authSource=admin`,\n }),\n inject: [ConfigService],\n}),\n```\n\n========================================\n\nCode:\n```text\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mongodb',\n host: `${config.get('mongo_url') || 'localhost'}`,\n port: 27017,\n username: 'a',\n password: 'b',\n database: 'my_db',\n entities: [__dirname + '/MyApp/*.Entity{.ts,.js}'],\n synchronize: true}),\n MyModule,\n ConfigModule,\n ],\n controllers: [],\n providers: [MyService],\n})\nexport class AppModule { }\n```\n\n```text\napp.module.ts\n```\n\n```text\n.env\n```\n\n```text\n${process.env.MONGODB_URL || 'localhost'}\n```\n\n```text\nconfigService\n```\n\n```text\nTypeOrmModule.forRootAsync({\n imports: [ConfigModule],\n useFactory: (configService: ConfigService) => ({\n type: 'mongodb',\n host: configService.databaseHost,\n port: configService.databasePort,\n username: configService.databaseUsername,\n password: configService.databasePassword,\n database: configService.databaseName,\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n }),\n inject: [ConfigService],\n}),\n```\n\n```text\nMongooseModule.forRootAsync({\n imports: [ConfigModule],\n useFactory: (configService: ConfigService) => ({\n uri: `mongodb://${configService.get(\n 'MONGODB_USERNAME',\n )}:${configService.get('MONGODB_PASSWORD')}@${configService.get(\n 'MONGODB_HOST',\n )}:27017/nest?authSource=admin`,\n }),\n inject: [ConfigService],\n}),\n```\n\n========================================\n\nComments:\n- Why must use `inject` into it ?\n- @soroush configService is a dependency that will be used to resolve to env variables and passed to typeorm, so nest is passing the configService into the usefactory so it can be used.","metadata":{"transformedAt":"2026-08-18T18:33:44.686Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":127,"estimatedTokens":811}}52{"id":"stack-62646494","source":"stackoverflow","questionId":62646494,"title":"NestJS - [TypeOrmModule] Unable to connect to the database. Retrying ER_PARSE_ERROR","tags":["nestjs","typeorm"],"text":"Title: NestJS - [TypeOrmModule] Unable to connect to the database. Retrying ER_PARSE_ERROR\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nCannot able to connect database with correct connection info, followed documentation to connect database from https://docs.nestjs.com/techniques/database\n\n**Database connected on SQLYog**\n\nhttps://i.sstatic.net/2ecFX.png\n\nFollowing same database information in **app.module.ts**\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mysql',\n host: 'localhost',\n port: 3306,\n username: 'root',\n password: null,\n database: 'the_local_db',\n entities: [\n Table_one,\n ],\n // entities: ['../typeorm/entities/*.ts'],\n\n synchronize: true,\n }),\n StaffModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\nError Details\n\n`[Nest] 5528 - 06/30/2020, 1:39:51 AM [ExceptionHandler] ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''\"'' at line 1 +18m\nQueryFailedError: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''\"'' at line 1\n\nat new QueryFailedError (C:\\Users\\UserName\\ProjectName\\nrwl\\src\\error\\QueryFailedError.ts:9:9)\nat Query. (C:\\Users\\UserName\\ProjectName\\nrwl\\src\\driver\\mysql\\MysqlQueryRunner.ts:167:37)\nat Query. (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\Connection.js:526:10)\nat Query._callback (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\Connection.js:488:16)\nat Query.Sequence.end (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\protocol\\sequences\\Sequence.js:83:24)\nat Query.ErrorPacket (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\protocol\\sequences\\Query.js:92:8)\nat Protocol._parsePacket (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\protocol\\Protocol.js:291:23)\nat Parser._parsePacket (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\protocol\\Parser.js:433:10)\nat Parser.write (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\protocol\\Parser.js:43:10)\nat Protocol.write (C:\\Users\\UserName\\ProjectName\\nrwl\\node_modules\\mysql\\lib\\protocol\\Protocol.js:38:16)`\n\n========================================\n\nTop Answer:\nCheck if you have synchronize connection option set to true in database configuration. Make it to false.\nIt worked for me.\n\n========================================\n\nCode:\n```text\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mysql',\n host: 'localhost',\n port: 3306,\n username: 'root',\n password: null,\n database: 'the_local_db',\n entities: [\n Table_one,\n ],\n // entities: ['../typeorm/entities/*.ts'],\n\n synchronize: true,\n }),\n StaffModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mysql',\n host: 'localhost',\n username: 'root',\n password: null,\n database: 'the_local_db',\n entities: [\n Table_one,\n ],\n // entities: ['../typeorm/entities/*.ts'],\n\n synchronize: true,\n }),\n StaffModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\n$ npm install mysql2 --save\n```\n\n```text\n$ npm uninstall mysql --save\n```\n\n```text\nmysql2\n```\n\n```text\nmysql\n```\n\n```text\nmysql\n```\n\n```text\nTypeOrmModule.forRoot({\n type: 'mysql',\n host: '127.0.0.1',\n port: 3306,\n username: 'test',\n password: '123456',\n database: 'nest',\n entities: [\"dist/**/*.entity{.ts,.js}\"],\n synchronize: true,\n dropSchema:true })\n```\n\n```text\ndbConfig: {\n type: 'mongodb',\n url: process.env.MONGO_CONNECTION_STRING,\n ssl: true,\n useUnifiedTopology: true,\n autoLoadEntities: true,\n synchronize: false,\n logging: true,\n}\n```\n\n```text\nMONGO_CONNECTION_STRING: mongodb://ussername:password@host_name:port/?authSource=admin\n```\n\n```text\nuseNewUrlParser: true\n```\n\n```text\nusername\n```\n\n```text\npassword\n```\n\n```text\nlocalhost\n```\n\n```text\n127.0.0.1\n```\n\n```text\nipv6\n```\n\n```text\nlocalhost\n```\n\n```text\n::1\n```\n\n```text\n127.0.0.1\n```\n\n```text\nERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)...\napi | Error: connect ECONNREFUSED 192.168.80.2:3306\n```\n\n```text\nversion: \"3\"\nservices:\n api:\n build:\n context: ../\n dockerfile: ./docker/files/dev.Dockerfile\n container_name: \"api\"\n env_file:\n - ./env/api.env\n depends_on:\n - database\n ports:\n - \"3000:3000\"\n volumes:\n - /usr/src/app/node_modules\n - ../app/:/usr/src/app/\n working_dir: /usr/src/app\n command: [\"npm\", \"run\", \"start:dev\"]\n\n database:\n image: mysql:8\n restart: unless-stopped\n container_name: database\n env_file:\n - ./env/db.env\n volumes:\n - db1:/var/lib/mysql //Provious db (change 1)\n ports:\n - \"3307:3306\"\n\n\nvolumes:\n db1: //Provious db (change 2)\n```\n\n```js\nTypeOrmModule.forRoot({\n // other options\n synchronize: true,\n // other options\n}),\n```\n\n```text\nsynchronize: true\n```\n\n```text\n@Column\n```\n\n```text\n@Column\n```\n\n========================================\n\nComments:\n- You should include the code of your Table_one entity. PS. In the title you mention a different error than in the question text.\n- Table_one entity already imported at top of file, but not shown here.\n- This worked for me, instead of loading the entities like this entities: [__dirname + '/../**/*.entity{.ts,.js}'], Import the entity in an array. I don't know the rationale behind it, and I would love some explanation too.\n- The important part is uninstall mysql. Great answer.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.\n- Hi, it worked for me. But if I need to run in synchronized mode I've to set it to true right? For that is there any ways or work arounds?\n- @Vaddadi if it is set to true - it might be for a reason. like in my case\n- It was the problem in my case too, thank you @Vaddadi\n- Also worked for my NestJS, TypeORM and CockroachDB setup!\n- Context on why this could be the reason: github.com/node-fetch/node-fetch/issues/…\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:44.686Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":273,"estimatedTokens":1752}}53{"id":"stack-55248938","source":"stackoverflow","questionId":55248938,"title":"TypeORM and Postgres competing naming styles","tags":["postgresql","typeorm"],"text":"Title: TypeORM and Postgres competing naming styles\nTags: postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nWe are using TypeORM and Postgresql and I'm curious about naming conventions.\n\nGiven that there are perfectly appropriate styles and naming conventions for databases that are separate from the perfectly good ones used for Javascript, is it considered better practice to force databases to use the code convention or to force code to use the database convention, or to translate everything?\n\nFor example:\n\nIt's common practice to use the SQl style defined in Joe Celko's SQL Programming Style for the database. This advocates for snake_case for the column names.\n\nIt's also common practice to name variables in camelCase when programming in JavaScript and all the documentation on typeorm.\n\nSo, when these two worlds collide, is it best practice to force one to the other or to translate every multi-word entity in the definitions to do the mapping.\n\nThis isn't really a question of **how** to do that but rather **if** there is a common practice one way of the other.\n\nThe three possibilities for a column representing User Id are:\n\n```\n1: Translate everything\n@Column( { name: user_id } )\nuserId: number;\n\n2: Use the database convention in the code\n@Column()\nuser_id: number;\n\n3: Use the coding convention in the database\n@Column()\nuserId: number\n```\n\n========================================\n\nCode:\n```text\n1: Translate everything\n@Column( { name: user_id } )\nuserId: number;\n\n2: Use the database convention in the code\n@Column()\nuser_id: number;\n\n3: Use the coding convention in the database\n@Column()\nuserId: number\n```\n\n```text\nnpm i --save typeorm-naming-strategies\n```\n\n```text\nconst SnakeNamingStrategy = require('typeorm-naming-strategies')\n .SnakeNamingStrategy;\n\nmodule.exports = {\n name: 'development',\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n ...\n namingStrategy: new SnakeNamingStrategy(),\n}\n```\n\n========================================\n\nComments:\n- Opinion (like everything else will be): snake-case in the database, camel-case in JavaScript. SQL folds unquoted identifiers to upper case (PostgreSQL folds to lower case though) so you have to quote column names for mixed case (i.e. say `\"userId\"` rather than `userId` in your SQL). ORMs should quote things for you but you'll have to do it yourself for any hand-written snippets of SQL. All the quotes tend to make the SQL ugly and hard to read (IMO).\n- This looks like a very useful package. I haven't tried it yet, but will give it a try.","metadata":{"transformedAt":"2026-08-18T18:33:44.686Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":75,"estimatedTokens":637}}54{"id":"stack-60336439","source":"stackoverflow","questionId":60336439,"title":"TypeORM select entity, except some, where id not equal condition","tags":["typescript","typeorm"],"text":"Title: TypeORM select entity, except some, where id not equal condition\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI Have two entities:\n\n```\n@Entity()\n export class Point {\n \n @PrimaryGeneratedColumn('uuid')\n id: string;\n \n // some other stuff\n \n }\n\n @Entity()\n export class Product {\n \n @PrimaryGeneratedColumn('uuid')\n id: string;\n \n @IsOptional()\n @ManyToMany(() => Point)\n @JoinTable()\n prohibitedToSaleOn: Point[];\n \n }\n```\n\nI want to get products, where any object from `prohibitedToSaleOn` (array of `Point`'s) fulfills the condition\n\npoint.id != {idWhatIWant}\n\nSo, in final I want to get all product, not banned from sales in selected point. I do something like this:\n\n```\nreturn this.productRepository.createQueryBuilder('product')\n .leftJoin('product.prohibitedToSaleOn', 'point')\n .where('point.id != :id', {id})\n .getMany();\n```\n\nBut it doesn't work (it should not at all)\n\nI need help with the right request. Thanks =)\n\nP.S. I use PostgreSQL\n\n========================================\n\nTop Answer:\nI find that the most simple way to do this is to use `typeorm`'s `Not` Operator, like this:\n\n```\nreturn this.productRepository.find( { where: id: Not('some_id') } );\n```\n\nDocumentation about `Not`:\n\nFind Options Operator. Used to negate expression. Example: { title: not(\"hello\") } will return entities where title not equal to \"hello\".\n\nRead more here\n\n========================================\n\nCode:\n```text\n@Entity()\n export class Point {\n \n @PrimaryGeneratedColumn('uuid')\n id: string;\n \n // some other stuff\n \n }\n\n\n @Entity()\n export class Product {\n \n @PrimaryGeneratedColumn('uuid')\n id: string;\n \n @IsOptional()\n @ManyToMany(() => Point)\n @JoinTable()\n prohibitedToSaleOn: Point[];\n \n }\n```\n\n```text\nreturn this.productRepository.createQueryBuilder('product')\n .leftJoin('product.prohibitedToSaleOn', 'point')\n .where('point.id != :id', {id})\n .getMany();\n```\n\n```text\nprohibitedToSaleOn\n```\n\n```text\nPoint\n```\n\n```text\n.where('point.id != :id', {id})\n```\n\n```text\nfind({where: {id: Not(id)}})\n```\n\n```text\nNot\n```\n\n```text\nreturn this.productRepository.createQueryBuilder('product')\n .leftJoin('product.prohibitedToSaleOn', 'point', 'point.id != :id', {id})\n .getMany();\n```\n\n```text\nreturn this.productRepository.createQueryBuilder('product')\n .leftJoin('product.prohibitedToSaleOn', 'point', '(point.id != :id OR point.id IS NULL)', {id})\n .getMany();\n```\n\n```text\nWHERE\n```\n\n```text\njoin\n```\n\n```text\nprohibitedToSaleOn\n```\n\n```text\nreturn this.productRepository.find( { where: id: Not('some_id') } );\n```\n\n```text\ntypeorm\n```\n\n```text\nNot\n```\n\n```text\nNot\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.686Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":161,"estimatedTokens":688}}55{"id":"stack-54885935","source":"stackoverflow","questionId":54885935,"title":"How to save relation in @ManyToMany in typeORM","tags":["javascript","node.js","orm","nestjs","typeorm"],"text":"Title: How to save relation in @ManyToMany in typeORM\nTags: javascript, node.js, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThere are 2 entities named `Article` and `Classification`. And the relation of them is `@ManyToMany`.\n\nHere's my question: How to save the relation?\n\nMy code as below:\n\n```\n@Entity()\n export class Article {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @CreateDateColumn()\n createTime: Date;\n\n @UpdateDateColumn()\n updateTime: Date;\n\n @Column({\n type: 'text',\n })\n content: string;\n\n @Column({\n default: 0,\n })\n likeAmount: number;\n\n @Column({\n default: 0,\n })\n commentAmount: number;\n }\n\n @Entity()\n export class Classification {\n @PrimaryGeneratedColumn()\n id: number;\n\n @CreateDateColumn()\n createTime: Date;\n\n @UpdateDateColumn()\n updateTime: Date;\n\n @Column()\n name: string;\n\n @ManyToMany(type => Article)\n @JoinTable()\n articles: Article[];\n }\n```\n\nI can save the `Article` and `Classification` successful. But I'm not sure how to save the relation of them.\n\nI have tried to save the relation via below code:\n\n```\nasync create(dto: ArticleClassificationDto): Promise {\n const article = this.repository.save(dto);\n article.then(value => {\n console.log(value);//console the object article\n value.classification.forEach(item => {\n const classification = new Classification();\n classification.id = item.id;\n classification.articles = [];\n classification.articles.push(value);\n this.classificationService.save(classification);\n })\n });\n console.log(article);\n return null;\n }\n```\n\nAnd the post data strcture like that\n\n```\n{\n \"name\":\"artile name\",\n \"content\":\"article content\",\n \"classification\":[{\n \"id\":4\n },{\n \"id\":3\n }]\n }\n```\n\nAt the beginning, it works.\n\nhttps://i.sstatic.net/7yrPB.png\n\nBut when I post the data again, the old record was replaced rather create another record.\n\nhttps://i.sstatic.net/HBFlc.png\n\nWhat should I do next?\n\nJust look below code please.\n\n```\nasync create(dto: ArticleClassificationDto): Promise {\n this.repository.save(dto).then(article => {\n article.classification.forEach(item => {\n this.ClassificationRepository.findOne(\n {\n // the privous method is get all the articles from databse and push into this array\n // relations: ['articles'],\n where: { id: item }// now I change the data strcture, just contains id instead of {id}\n }\n ).then(classification => {\n // console.log(article);\n console.log(classification);\n // cmd will show ' UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'push' of undefined' withous below line code. But if I init the array manually,the old record will be replaced again.\n // classification.articles = [];\n classification.articles.push(article);\n this.ClassificationRepository.save(classification);\n });\n })\n })\n return null;\n }\n```\n\n========================================\n\nTop Answer:\nin my case i have user and role, 1st you have to initialize your manytomany in your entities :\n\nin user entity :\n\n```\n@ManyToMany((type) => Role, {\n cascade: true,\n })\n @JoinTable({\n name: \"users_roles\",\n joinColumn: { name: \"userId\", referencedColumnName: \"id\" },\n inverseJoinColumn: { name: \"roleId\" }\n })\n roles: Role[];\n```\n\nin role entity :\n\n```\n//Many-to-many relation with user\n @ManyToMany((type) => User, (user) => user.roles)\n users: User[];\n```\n\nin my service i create a new entity from my data then i added role data to my new entity object :\n\n```\nlet entity = await this.userRepository.create(data);\nlet entity2 = {\n ...entity,\n roles: data.selectedRoles,\n };\nconst user = await this.userRepository.save(entity2);\n```\n\nthis is the exemple in typeorm website :\n\n```\nconst category1 = new Category();\ncategory1.name = \"animals\";\nawait connection.manager.save(category1);\n\nconst category2 = new Category();\ncategory2.name = \"zoo\";\nawait connection.manager.save(category2);\n\nconst question = new Question();\nquestion.title = \"dogs\";\nquestion.text = \"who let the dogs out?\";\nquestion.categories = [category1, category2];\nawait connection.manager.save(question);\n```\n\n========================================\n\nCode:\n```text\n@Entity()\n export class Article {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @CreateDateColumn()\n createTime: Date;\n\n @UpdateDateColumn()\n updateTime: Date;\n\n @Column({\n type: 'text',\n })\n content: string;\n\n @Column({\n default: 0,\n })\n likeAmount: number;\n\n @Column({\n default: 0,\n })\n commentAmount: number;\n }\n\n @Entity()\n export class Classification {\n @PrimaryGeneratedColumn()\n id: number;\n\n @CreateDateColumn()\n createTime: Date;\n\n @UpdateDateColumn()\n updateTime: Date;\n\n @Column()\n name: string;\n\n @ManyToMany(type => Article)\n @JoinTable()\n articles: Article[];\n }\n```\n\n```text\nasync create(dto: ArticleClassificationDto): Promise<any> {\n const article = this.repository.save(dto);\n article.then(value => {\n console.log(value);//console the object article\n value.classification.forEach(item => {\n const classification = new Classification();\n classification.id = item.id;\n classification.articles = [];\n classification.articles.push(value);\n this.classificationService.save(classification);\n })\n });\n console.log(article);\n return null;\n }\n```\n\n```text\n{\n \"name\":\"artile name\",\n \"content\":\"article content\",\n \"classification\":[{\n \"id\":4\n },{\n \"id\":3\n }]\n }\n```\n\n```text\nasync create(dto: ArticleClassificationDto): Promise<any> {\n this.repository.save(dto).then(article => {\n article.classification.forEach(item => {\n this.ClassificationRepository.findOne(\n {\n // the privous method is get all the articles from databse and push into this array\n // relations: ['articles'],\n where: { id: item }// now I change the data strcture, just contains id instead of {id}\n }\n ).then(classification => {\n // console.log(article);\n console.log(classification);\n // cmd will show ' UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'push' of undefined' withous below line code. But if I init the array manually,the old record will be replaced again.\n // classification.articles = [];\n classification.articles.push(article);\n this.ClassificationRepository.save(classification);\n });\n })\n })\n return null;\n }\n```\n\n```text\nArticle\n```\n\n```text\nClassification\n```\n\n```text\n@ManyToMany\n```\n\n```text\nArticle\n```\n\n```text\nClassification\n```\n\n```text\nclassification.articles = [article1, article2];\nawait this.classificationRepository.save(classification);\n```\n\n```text\n@ManyToMany(type => Article, article => article.classifications, { cascade: true })\n```\n\n```text\nasync create(dto: ArticleClassificationDto): Promise<any> {\n let article = await this.repository.create(dto);\n article = await this.repository.save(article);\n const classifications = await this.classificationRepository.findByIds(article.classification, {relations: ['articles']});\n for (const classification of classifications) {\n classification.articles.push(article);\n }\n return this.classificationRepository.save(classifications);\n}\n```\n\n```text\narticles\n```\n\n```text\ncascade\n```\n\n```text\ntrue\n```\n\n```text\n@ManyToMany((type) => Role, {\n cascade: true,\n })\n @JoinTable({\n name: \"users_roles\",\n joinColumn: { name: \"userId\", referencedColumnName: \"id\" },\n inverseJoinColumn: { name: \"roleId\" }\n })\n roles: Role[];\n```\n\n```text\n//Many-to-many relation with user\n @ManyToMany((type) => User, (user) => user.roles)\n users: User[];\n```\n\n```text\nlet entity = await this.userRepository.create(data);\nlet entity2 = {\n ...entity,\n roles: data.selectedRoles,\n };\nconst user = await this.userRepository.save(entity2);\n```\n\n```text\nconst category1 = new Category();\ncategory1.name = \"animals\";\nawait connection.manager.save(category1);\n\nconst category2 = new Category();\ncategory2.name = \"zoo\";\nawait connection.manager.save(category2);\n\nconst question = new Question();\nquestion.title = \"dogs\";\nquestion.text = \"who let the dogs out?\";\nquestion.categories = [category1, category2];\nawait connection.manager.save(question);\n```\n\n========================================\n\nComments:\n- I have tried your method. And it didn't work for me. I have updated my question, can u help next?\n- This is a different problem now: You are posting the `classifications` with their `id`'s. `id` is the `PrimaryGeneratedColumn` of the `classification` entity. If you want to create a new object, you must not include the primary column, otherwise the entity will be updated instead of created if the primary column (`id`) already exists.\n- But I just wanna save the relation of them. Not save the entity `Classification`.I do wanna create a new object, but not `classification`, just new relation of `classification` and `article`.And I need the `id` of `Classification` automatically generated with an auto-increment value when I insert a new `Classification`. I'm not clear how to realize my target?\n- Ok, so all entities already exist; you just want to create the relation between the entities!? Then just load your classification entity from the database `findOne(classificationId)`, assign the articles to the classification entity you loaded from the database and then save the classification entity.\n- I have done as what u said. But there was something wrong with it. I have posted the code in the question.\n- You are creating a new entity `const classification = new Classification();` instead of loading the existing one from the database.\n- Are you sure the code you watched is below `Just look below code please`?\n- Let us continue this discussion in chat.\n- thx, I have tried to add ManyToMany in Article,Now I have ManyToMany in Article and Classification,but still not work for me. And I tried another solution: find all articles that classification contains, just like `classification{id:4,articles:[article1,article2]}`,then `classification.articles.push(newArticle)`.Then it works. But I know this is a terrible solution.\n- I guess I figure it out. When I create a object of Classification. And set its id. In that time, the articles is empty. So I push one article in it, the typeorm will think it has only one article even if it has a lot of articles in database? So the previous solution is right?\n- Mh, I'm afraid I can't completely what you're doing. :-/ However, you should *either* create a new entity without setting an `id` or load an existing entity from the database with its `id`.\n- emm,sorry to bother u, cause my english is not good. How about chatting in the linking now you posted yesterday?","metadata":{"transformedAt":"2026-08-18T18:33:44.686Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":409,"estimatedTokens":2730}}56{"id":"stack-65041545","source":"stackoverflow","questionId":65041545,"title":"How can i use longitude and latitude with typeorm and postgres","tags":["postgresql","nestjs","typeorm"],"text":"Title: How can i use longitude and latitude with typeorm and postgres\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nMy current entity looks like this:\n\n```\nimport { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Landmark extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column()\n longitude: number \n\n @Column()\n latitude: number \n}\n```\n\nBut i wonder if there is a better way to do this, with a special postgres type, that works with typeorm.\n\n========================================\n\nTop Answer:\nExtending JosephHall Answer\n\nUsed postgres,postgis,typeORM,@types/geojson, Nest JS\n\n```\nimport { Column, Entity, Index, PrimaryGeneratedColumn} from 'typeorm';\nimport { Point } from 'geojson';\n\n@Entity({ name: 't_test_location' })\nexport class TestLocation {\n @PrimaryGeneratedColumn('increment')\n pk_id: number;\n \n @Column({ type: 'varchar', name: 's_city' })\n city: string;\n\n @Index({ spatial: true })\n @Column({\n type: 'geography',\n spatialFeatureType: 'Point', \n srid: 4326,\n nullable: true,\n })\n location:Point\n}\n```\n\nService class\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { TestLocation } from 'src/model/testlocation.entity';\nimport { getManager, QueryBuilder, Repository } from 'typeorm';\nimport { Geometry, Point } from 'geojson';\n@Injectable()\nexport class LocationService {\n constructor(\n @InjectRepository(TestLocation) private readonly repo: Repository,\n ) {}\n\n public async getAll() {\n return await this.repo.find();\n }\n\n public async create(location:TestLocation){\n const pointObject :Point= {\n type: \"Point\",\n coordinates: [location.long,location.lat]\n };\n location.location = pointObject;\n return await this.repo.save(location)\n }\n```\n\nController\n\n```\nimport { Body, Controller, Get, Post } from '@nestjs/common';\nimport { TestLocation } from 'src/model/testlocation.entity';\nimport { LocationService } from './location.service';\n\n@Controller('location')\nexport class LocationController {\n constructor(private serv: LocationService) {}\n\n @Get()\n public async getAll() {\n return await this.serv.getAll();\n }\n @Post()\n createLocation(@Body() location : TestLocation): void{\n this.serv.create(location);\n }\n}\n```\n\n========================================\n\nCode:\n```js\nimport { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Landmark extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column()\n longitude: number \n\n @Column()\n latitude: number \n}\n```\n\n```text\nimport { Geometry } from 'geojson';\n...\n@Column\nlocation: Geometry\n```\n\n```text\nUPDATE customers SET location = 'point(37.7, 122.4)' where id = 123;\n```\n\n```text\n-- Assuming you have a lat and lon columns on the `customers` table that you are migrating to the PostGIS geometry(point) type\nUPDATE customers SET location = ST_MakePoint(lat, lon) where id = 123;\n```\n\n```text\n@types/geojson\n```\n\n```text\nGeometry\n```\n\n```text\nlatitude\n```\n\n```text\nlongitude\n```\n\n```text\nlocation\n```\n\n```text\npoint()\n```\n\n```text\nGeometry\n```\n\n```text\nlocation\n```\n\n```text\ncustomers\n```\n\n```text\ngeometry(point)\n```\n\n```text\nlocation\n```\n\n```text\ngeometry(point)\n```\n\n```text\nST_MakePoint\n```\n\n```text\nimport { Column, Entity, Index, PrimaryGeneratedColumn} from 'typeorm';\nimport { Point } from 'geojson';\n\n@Entity({ name: 't_test_location' })\nexport class TestLocation {\n @PrimaryGeneratedColumn('increment')\n pk_id: number;\n \n @Column({ type: 'varchar', name: 's_city' })\n city: string;\n\n @Index({ spatial: true })\n @Column({\n type: 'geography',\n spatialFeatureType: 'Point', \n srid: 4326,\n nullable: true,\n })\n location:Point\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { TestLocation } from 'src/model/testlocation.entity';\nimport { getManager, QueryBuilder, Repository } from 'typeorm';\nimport { Geometry, Point } from 'geojson';\n@Injectable()\nexport class LocationService {\n constructor(\n @InjectRepository(TestLocation) private readonly repo: Repository<TestLocation>,\n ) {}\n\n public async getAll() {\n return await this.repo.find();\n }\n\n public async create(location:TestLocation){\n const pointObject :Point= {\n type: \"Point\",\n coordinates: [location.long,location.lat]\n };\n location.location = pointObject;\n return await this.repo.save(location)\n }\n```\n\n```text\nimport { Body, Controller, Get, Post } from '@nestjs/common';\nimport { TestLocation } from 'src/model/testlocation.entity';\nimport { LocationService } from './location.service';\n\n@Controller('location')\nexport class LocationController {\n constructor(private serv: LocationService) {}\n\n @Get()\n public async getAll() {\n return await this.serv.getAll();\n }\n @Post()\n createLocation(@Body() location : TestLocation): void{\n this.serv.create(location);\n }\n}\n```\n\n========================================\n\nComments:\n- Why do you import `Geometry`? I don't see it used anywhere.\n- @SergeyYarotskiy Yes, no need to import. Updated the answer. Thank you!!\n- getting error `QueryFailedError: type \"geography\" does not exist` what is the reason ?\n- @rickster the reason for that because the postgis extension not added to the postgres so the pg does not identifying this special type that is provided by the postgis extension","metadata":{"transformedAt":"2026-08-18T18:33:44.686Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":268,"estimatedTokens":1354}}57{"id":"stack-61361008","source":"stackoverflow","questionId":61361008,"title":"TypeORM insert with relationId","tags":["javascript","orm","typeorm"],"text":"Title: TypeORM insert with relationId\nTags: javascript, orm, typeorm\nSource: Stack Overflow\n\nQuestion:\nI use TypeORM, and simply I want to insert a row by using `relationId`. But it's not working as I expected.\n\nHere is my entity:\n\n```\n@Entity()\nexport default class Address extends BaseEntity {\n\n @Column({\n type: 'varchar',\n length: 255,\n })\n public title: number;\n\n @Column({\n type: 'varchar',\n length: 2000,\n })\n public value: number;\n\n @ManyToOne(type => User, user => user)\n @JoinColumn({ name: 'userId' })\n public user: User;\n\n @RelationId((address: Address) => address.user)\n public userId: number;\n\n}\n```\n\nWhen I try to add like the below example, it adds `null` `userId` which I do not expect\n\n```\n{\n \"title\": \"My home address\",\n \"value\": \"Lorep Ipsum Sit Amet\",\n \"userId\": 4\n}\n```\n\nhttps://i.sstatic.net/vTthw.png\n\nWhen I change the payload, everything works perfectly.\n\n```\n{\n \"title\": \"Ev adresim\",\n \"value\": \"Nova Suites\",\n \"user\": 4\n}\n```\n\nI do not want to use a payload like the above. I addicted to define a descriptive variable naming. Thanks for all contribution and all answer from now.\n\n========================================\n\nTop Answer:\nAs Noam has pointed out, you cannot use the `@RelationId()` decorated property to assign a relation. Instead you should use the relation itself.\n\nIf you have an instance of the object like `user` below, you can pass it straight away. For the offer I had only ID, I've been able to work around this limitation though by creating an object with just an `id` property. Now I don't have to retrieve the whole object from the DB which would be waste of resources.\n\n```\nsubscriptionRepository\n .insert({\n offer: {id: offerId},\n user: user,\n })\n```\n\nFor your reference, this is an excerpt of my entity definition.\n\n```\n@Entity()\nexport class Subscription {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(\n () => Offer,\n (offer: Offer) => offer.subscriptions\n )\n offer: Offer;\n\n @ManyToOne(\n () => User,\n (user: User) => user.subscriptions\n )\n user: User;\n}\n```\n\n========================================\n\nCode:\n```text\n@Entity()\nexport default class Address extends BaseEntity {\n\n @Column({\n type: 'varchar',\n length: 255,\n })\n public title: number;\n\n @Column({\n type: 'varchar',\n length: 2000,\n })\n public value: number;\n\n @ManyToOne(type => User, user => user)\n @JoinColumn({ name: 'userId' })\n public user: User;\n\n @RelationId((address: Address) => address.user)\n public userId: number;\n\n}\n```\n\n```text\n{\n \"title\": \"My home address\",\n \"value\": \"Lorep Ipsum Sit Amet\",\n \"userId\": 4\n}\n```\n\n```text\n{\n \"title\": \"Ev adresim\",\n \"value\": \"Nova Suites\",\n \"user\": 4\n}\n```\n\n```text\nrelationId\n```\n\n```text\nnull\n```\n\n```text\nuserId\n```\n\n```text\n@ManyToOne(type => User, user => user)\n@JoinColumn({ name: 'userId' })\npublic user: User;\n\n@Column()\npublic userId: number;\n```\n\n```text\n@RelationId\n```\n\n```text\n@Column\n```\n\n```js\nsubscriptionRepository\n .insert({\n offer: {id: offerId},\n user: user,\n })\n```\n\n```js\n@Entity()\nexport class Subscription {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(\n () => Offer,\n (offer: Offer) => offer.subscriptions\n )\n offer: Offer;\n\n @ManyToOne(\n () => User,\n (user: User) => user.subscriptions\n )\n user: User;\n}\n```\n\n```text\n@RelationId()\n```\n\n```text\nuser\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- Thanks for the answer mate. Actually, I had tried this solution but It didn't worked. It gaves me an error which is `error: Error: UNKNOWN_CODE_PLEASE_REPORT: Referencing column 'userId' and referenced column 'id' in foreign key constraint 'FK_d25f1ea79e282cc8a42bd616aa3' are incompatible.` I have dropped the table as well, but it doesnt work as I expected. That means it doesnt add foreignkey automatically\n- I checked the error that the terminal was saying. I realized that when we define the properties of userId column the same with the referenced table's Id. It works fine. Could you update your answer according to this. When you update the answer, I am going to mark your answer. Thereby, people who faced same issue able to find their problem as well. It should be like this --> `@Column({ type: 'integer', unsigned: true, }) public userId: number;` due to the fact that in my base entity class, I defined primary id's as a unsigned\n- Ok, glad I could helped. I updated the answer, but I'm not 100% sure what you meant.\n- You're totally right. Actually, The answer is given by @JudgeFudge is almost correct. I have commented on some parts. When he/she changed her/his answer, I am going to approve that answer.\n- @HalilİbrahimÖzdoğan Your question changed? The answer I gave wasn't relevant? how did you solve the issue?\n- no mate your answer is relevant as well. That's why I have upvoted your answer as well.","metadata":{"transformedAt":"2026-08-18T18:33:44.686Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":219,"estimatedTokens":1226}}58{"id":"stack-53553523","source":"stackoverflow","questionId":53553523,"title":"TypeORM subqueries","tags":["sql","oracle-database","typeorm","typeorm-datamapper"],"text":"Title: TypeORM subqueries\nTags: sql, oracle-database, typeorm, typeorm-datamapper\nSource: Stack Overflow\n\nQuestion:\nBased on typeORM docs on using subqueries, there are explained how to create subqueries.\nExample:\n\n```\nconst qb = await getRepository(Post).createQueryBuilder(\"post\");\nconst posts = qb\n .where(\"post.title IN \" + qb.subQuery().select(\"user.name\").from(User, \"user\").where(\"user.registered = :registered\").getQuery())\n .setParameter(\"registered\", true)\n .getMany();\n```\n\nBut there is no equivalent as to what the SQL would be.\n\nSupposed that I have the query which contains subqueries like the following:\n\n```\nSELECT a, TO_CHAR (MAX (jointable.f), 'MON YYYY') as f,\n t3.c, t3.d, t1.e\nFROM table1 t1 \nLEFT JOIN table2 t2 ON t2.e = t1.e\nJOIN table3 t3 ON t3.d = t2.d\nJOIN\n (SELECT f, t4.g, t5.e, t6.h\n FROM table4 t4 \n JOIN table5 t5 ON t4.g = t5.g\n JOIN table6 t6 ON t6.g = t4.g\n AND (t6.i = 2\n OR (t6.i = 1 AND j = 1)\n )\n WHERE t4.k = 4\n ) jointable ON t1.e = jointable.e\nWHERE jointable.h = :h\nAND(:d = 3 OR \n t3.\"d\" = :d\n )\nGROUP BY a, t3.c, t3.d, t1.e\nORDER BY a ASC\n```\n\nHow should I use the typeORM query builder function for the SQL query above?\n\nAssuming that I had created entities related to all table being used on the query above.\n\n========================================\n\nCode:\n```text\nconst qb = await getRepository(Post).createQueryBuilder(\"post\");\nconst posts = qb\n .where(\"post.title IN \" + qb.subQuery().select(\"user.name\").from(User, \"user\").where(\"user.registered = :registered\").getQuery())\n .setParameter(\"registered\", true)\n .getMany();\n```\n\n```text\nSELECT a, TO_CHAR (MAX (jointable.f), 'MON YYYY') as f,\n t3.c, t3.d, t1.e\nFROM table1 t1 \nLEFT JOIN table2 t2 ON t2.e = t1.e\nJOIN table3 t3 ON t3.d = t2.d\nJOIN\n (SELECT f, t4.g, t5.e, t6.h\n FROM table4 t4 \n JOIN table5 t5 ON t4.g = t5.g\n JOIN table6 t6 ON t6.g = t4.g\n AND (t6.i = 2\n OR (t6.i = 1 AND j = 1)\n )\n WHERE t4.k = 4\n ) jointable ON t1.e = jointable.e\nWHERE jointable.h = :h\nAND(:d = 3 OR \n t3.\"d\" = :d\n )\nGROUP BY a, t3.c, t3.d, t1.e\nORDER BY a ASC\n```\n\n```text\nconst subquery = await getManager()\n .createQueryBuilder(table4, 't4')\n .select('\"t4\".f')\n .addSelect('\"t4\".g')\n .addSelect('\"t5\".e')\n .addSelect('\"t6\".h')\n .innerJoin(table5, 't5', '\"t4\".g = \"t5\".g')\n .innerJoin(table6, 't6', '\"t6\".g = \"t4\".g')\n .where('\"t4\".k = 4 AND (\"t6\".i = 2 OR (\"t6\".i = 1 AND \"t6\".j = 1))');\n\n model = await getManager()\n .createQueryBuilder(table1, 't1')\n .select('\"t1\".a')\n .addSelect(\"TO_CHAR (MAX (jointable.f), 'MON YYYY')\", 'f')\n .addSelect('\"t3\".c')\n .addSelect('\"t3\".d')\n .addSelect('\"t1\".e')\n .leftJoin('table2', 't2', '\"t2\".e = \"t1\".e')\n .innerJoin(table3, 't3', '\"t3\".d = \"t2\".d')\n .innerJoin('('+subquery.getQuery()+')', 'jointable', '\"t1\".e = jointable.e')\n .where('jointable.h = :h AND (:d = 3 OR \"t3\".d = :d)',\n { h: h, d: d })\n .groupBy('\"t1\".a, \"t3\".c, \"t3\".d, \"t1\".e')\n .orderBy('\"t1\".a', 'ASC')\n .getRawMany();\n```\n\n```text\n'('+subquery.getQuery()+')'\n```\n\n```text\nJoin\n```\n\n```text\ninner join\n```\n\n```text\n.select\n```\n\n```text\nselect\n```\n\n```text\naliases\n```\n\n```text\n.addSelect\n```\n\n```text\n, in select\n```\n\n```text\ngetOne\n```\n\n```text\ngetMany\n```\n\n```text\ngetRawOne\n```\n\n```text\ngetRawMany\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.686Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":158,"estimatedTokens":829}}59{"id":"stack-68468192","source":"stackoverflow","questionId":68468192,"title":"Difference between .limit() and .take() in TypeORM","tags":["node.js","typeorm","query-builder"],"text":"Title: Difference between .limit() and .take() in TypeORM\nTags: node.js, typeorm, query-builder\nSource: Stack Overflow\n\nQuestion:\nI am confused about different TypeORM methods with similar purposes. From TypeORM docs:\n\n- `.take()` — pagination limit. Sets maximal number of entities to take.\n\n- `.skip()` — pagination offset. Sets number of entities to skip.\n\nI poorly understand what \"pagination limit/offset\" means. But, unfortunately, I couldn't find any information about distinguishing of, for instance, `.take()` and `.limit()`. I decided to see descriptions of these methods in TypeORM's source code:\n\n- `.limit()` — Set's LIMIT - maximum number of rows to be selected. NOTE that it may not work as you expect if you are using joins. If you want to implement pagination, and you are having join in your query, then use instead take method instead.\n\n- `.offset()` — Set's OFFSET - selection offset. NOTE that it may not work as you expect if you are using joins. If you want to implement pagination, and you are having join in your query, then use instead skip method instead.\n\nWhy these two methods cannot be used for pagination? What are their purposes then? Please, could anyone provide me with clear examples of using all these 4 methods? Thanks in advance.\n\n========================================\n\nTop Answer:\nSo in any case, as for joining tables `limit` and `offset` don't always work as we would expect them to, just to be on the safe side, using `take` and `skip` instead of `limit` and `offset` would be preferable.\n\n========================================\n\nCode:\n```text\n.take()\n```\n\n```text\n.skip()\n```\n\n```text\n.take()\n```\n\n```text\n.limit()\n```\n\n```text\n.limit()\n```\n\n```text\n.offset()\n```\n\n```text\ntake\n```\n\n```text\nskip\n```\n\n```text\nlimit\n```\n\n```text\noffset\n```\n\n```text\nlimit\n```\n\n```text\noffset\n```\n\n```text\ntake\n```\n\n```text\nskip\n```\n\n```text\nlimit\n```\n\n```text\noffset\n```\n\n```js\nconst result = manager.getRepository(UserEntity)\n .createQueryBuilder('u')\n .select()\n .leftJoinAndSelect('u.orders', 'o')\n .orderBy('u.column', 'DESC')\n .limit(3); // or .take(3)\n```\n\n```text\nSELECT ... \nFROM user LEFT JOIN order ON order.user_id = user.id\nORDER BY user.column \nLIMIT 3\n```\n\n```text\nuser.id | order.id | ...other columns\n-------------------------------------\nu1 o1\nu1 o2\nu2 o3 \nu3 o4 <--- over limit\n```\n\n```text\nSELECT DISTINCT user.id FROM (\n SELECT ... FROM user JOIN order ON ...\n) LIMIT 3\n```\n\n```text\nSELECT ... \nFROM user LEFT JOIN order ON ...\nWHERE user.id IN ('u1', 'u2', 'u3')\nORDER BY u.column\n```\n\n```text\ntake\n```\n\n```text\n.limit(3)\n```\n\n```text\nuser\n```\n\n```text\nu1\n```\n\n```text\nu3\n```\n\n```text\n.take(3)\n```\n\n```text\nresult\n```\n\n```text\ntake()\n```\n\n```text\noffset()\n```\n\n```text\nskip()\n```\n\n```text\nOFFSET\n```\n\n```text\n.take()\n```\n\n```text\n.take()\n```\n\n```text\n.take()\n```\n\n========================================\n\nComments:\n- So you mean `.limit()` may possibly cause unexpected behavior? If I wish to 'limit' 3 entities A joining B, it may take 1 entity A and 3 entities B, right? But why?\n- yes, as I said, limit() include it in SQL query and take(), not... following the example above, if you run the query SELECT * FROM A a LEFT JOIN B b ON b.aId = a.id LIMIT 3, you will get three rows(AB1, AB2, AB3), then when TypeORM map it to entities, you get [{ bs: [B1, B2, B3] }]... otherwise if you use take(), the query will dont include limit SELECT * FROM A a LEFT JOIN B b ON b.aId = a.id, it will be free of get all rows that match it, map to entity and finally take the amount of entries A need... both options has not difference if there is no joins, limit is optimal if you can use\n- I like separate in two queries for the cases when I need perform joins with the goal of use limit() and offset() always, first to get the ids of entity A that satisfy the restrictions, then another for get all data of entries A with ids included in previous list, this prevent load in memory unnecessary data\n- @LeonardoDiPierro BTW Sorry for my english\n- Oh, thanks! Everything is clear.\n- Sounds like a bad idea to use take and skip with large result sets and not as an option for pagination if TypeORM loads the whole result set into memory first just to throw it away afterwards...\n- Anyone have performance insights on how `.take()` and `.skip()` behave when there is also an `order by` clause and joins? I'm seeing weird behavior where the time to resolve queries increases as the `skip` values increase... not sure why that is\n- @Sebi2020 looks like skip and take use offset and limit under the hood like a normal sql query orkhan.gitbook.io/typeorm/docs/find-options\n- specifically `limit` and `offset` are not stateful and will return the same or skip results between 'pages' if limit and offset are used for pagination and records are added/deleted between page requests. Using `take` and `skip` doesn't solve this, what exactly do you mean by `don't always work as we would expect them to`? As far as the resultant SQL query without state; `take` and `skip` are a subset of `limit` and `offset` making them less predictable and not more preferable as you put it","metadata":{"transformedAt":"2026-08-18T18:33:44.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":35,"totalLines":197,"estimatedTokens":1288}}60{"id":"stack-67481978","source":"stackoverflow","questionId":67481978,"title":"How to make complex nested where conditions with typeORM?","tags":["sql","typescript","typeorm"],"text":"Title: How to make complex nested where conditions with typeORM?\nTags: sql, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am having multiple nested where conditions and want to generate them without too much code duplication with typeORM.\n\nThe SQL where condition should be something like this:\n\n```\nWHERE \"Table\".\"id\" = $1\nAND\n\"Table\".\"notAvailable\" IS NULL\nAND\n(\n \"Table\".\"date\" > $2\n OR\n (\n \"Table\".\"date\" = $2\n AND\n \"Table\".\"myId\" > $3\n )\n)\nAND\n(\n \"Table\".\"created\" = $2\n OR\n \"Table\".\"updated\" = $4\n)\nAND\n(\n \"Table\".\"text\" ilike '%search%'\n OR\n \"Table\".\"name\" ilike '%search%'\n)\n```\n\nBut with the `FindConditions` it seems not to be possible to make them nested and so I have to use all possible combinations of `AND` in an FindConditions array. And it isn't possible to split it to `.where()` and `.andWhere()` cause `andWhere` can't use an Object Literal.\n\nIs there another possibility to achieve this query with typeORM without using Raw SQL?\n\n========================================\n\nTop Answer:\nWhen using the queryBuilder I would recommend using `Brackets`\nas stated in the Typeorm doc: https://typeorm.io/#/select-query-builder/adding-where-expression\n\nYou could do something like:\n\n```\ncreateQueryBuilder(\"user\")\n .where(\"user.registered = :registered\", { registered: true })\n .andWhere(new Brackets(qb => {\n qb.where(\"user.firstName = :firstName\", { firstName: \"Timber\" })\n .orWhere(\"user.lastName = :lastName\", { lastName: \"Saw\" })\n }))\n```\n\nthat will result with:\n\n```\nSELECT ... \nFROM users user\nWHERE user.registered = true \nAND (user.firstName = 'Timber' OR user.lastName = 'Saw')\n```\n\n========================================\n\nCode:\n```sql\nWHERE \"Table\".\"id\" = $1\nAND\n\"Table\".\"notAvailable\" IS NULL\nAND\n(\n \"Table\".\"date\" > $2\n OR\n (\n \"Table\".\"date\" = $2\n AND\n \"Table\".\"myId\" > $3\n )\n)\nAND\n(\n \"Table\".\"created\" = $2\n OR\n \"Table\".\"updated\" = $4\n)\nAND\n(\n \"Table\".\"text\" ilike '%search%'\n OR\n \"Table\".\"name\" ilike '%search%'\n)\n```\n\n```text\nFindConditions\n```\n\n```text\nAND\n```\n\n```text\n.where()\n```\n\n```text\n.andWhere()\n```\n\n```text\nandWhere\n```\n\n```text\nconst desiredEntity = await connection\n .getRepository(User)\n .createQueryBuilder(\"user\")\n .where(\"user.id = :id\", { id: 1 })\n .andWhere(\"user.date > :date OR (user.date = :date AND user.myId = :myId)\",\n { \n date: specificCreatedAtDate,\n myId: mysteryId,\n })\n .getOne();\n```\n\n```text\nconst desiredEntity = await repository.find({\n where: [{\n id: id,\n notAvailable: Not(IsNull()),\n date: MoreThan(date)\n },{\n id: id,\n notAvailable: Not(IsNull()),\n date: date\n myId: myId\n }]\n})\n```\n\n```text\nFindConditions\n```\n\n```text\nandWhere\n```\n\n```text\nfind\n```\n\n```text\nfindOptions\n```\n\n```text\nAND\n```\n\n```text\nOR\n```\n\n```text\nAND\n```\n\n```text\nOR\n```\n\n```text\nOR\n```\n\n```text\nRaw\n```\n\n```js\ncreateQueryBuilder(\"user\")\n .where(\"user.registered = :registered\", { registered: true })\n .andWhere(new Brackets(qb => {\n qb.where(\"user.firstName = :firstName\", { firstName: \"Timber\" })\n .orWhere(\"user.lastName = :lastName\", { lastName: \"Saw\" })\n }))\n```\n\n```sql\nSELECT ... \nFROM users user\nWHERE user.registered = true \nAND (user.firstName = 'Timber' OR user.lastName = 'Saw')\n```\n\n```text\nBrackets\n```\n\n```text\nasync getTasks(filterDto: GetTasksFilterDto, user: User): Promise<Task[]> {\nconst { status, search } = filterDto;\n\n/* create a query using the query builder */\n// task is what refer to the Task entity\nconst query = this.createQueryBuilder('task');\n\n// only get the tasks that belong to the user\nquery.where('task.userId = :userId', { userId: user.id });\n\n/* if status is defined then add a where clause to the query */\nif (status) {\n // :<variable-name> is a placeholder for the second object key value pair\n query.andWhere('task.status = :status', { status });\n}\n/* if search is defined then add a where clause to the query */\nif (search) {\n query.andWhere(\n /* \n LIKE: find a similar match (doesn't have to be exact)\n - https://www.w3schools.com/sql/sql_like.asp\n Lower is a sql method\n - https://www.w3schools.com/sql/func_sqlserver_lower.asp\n\n * bug: search by pass where userId; fix: () whole addWhere statement\n because andWhere stiches the where class together, add () to make andWhere with or and like into a single where statement\n */\n '(LOWER(task.title) LIKE LOWER(:search) OR LOWER(task.description) LIKE LOWER(:search))',\n // :search is like a param variable, and the search object is the key value pair. Both have to match\n { search: `%${search}%` },\n );\n}\n/* execute the query\n\n- getMany means that you are expecting an array of results\n */\nlet tasks;\ntry {\n tasks = await query.getMany();\n} catch (error) {\n this.logger.error(\n `Failed to get tasks for user \"${\n user.username\n }\", Filters: ${JSON.stringify(filterDto)}`,\n error.stack,\n );\n throw new InternalServerErrorException();\n}\nreturn tasks;\n```\n\n```text\n{ \n date: specificCreatedAtDate,\n userId: mysteryId\n}\n```\n\n```text\n.andWhere(\n new Brackets((qb) => {\n qb.where(\n 'userTable.date = :date0 AND userTable.type = :userId0',\n {\n date0: dates[0].date,\n userId0: dates[0].type,\n }\n );\n\n for (let i = 1; i < dates.length; i++) {\n qb.orWhere(\n `userTable.date = :date${i} AND userTable.userId = :userId${i}`,\n {\n [`date${i}`]: dates[i].date,\n [`userId${i}`]: dates[i].userId,\n }\n );\n }\n })\n )\n```\n\n```text\nconst userEntity = await repository.find({\n where: [{\n userId: id0,\n date: date0\n },{\n id: id1,\n userId: date1\n }\n ....\n]\n})\n```\n\n```text\nconst users = await User.find({\n where: {\n username: Like(`%${req.body?.search}%`),\n uuid: Not(req.user?.uuid),\n },\n select: {\n id: true,\n uuid: true,\n username: true,\n name: true,\n status: true,\n image: true,\n },\n });\n```\n\n```text\nres.status(200).json({message: \"The query user got it.\", users});\n```\n\n```text\nNOT\n```\n\n```text\nLIKE\n```\n\n```text\nresponse\n```\n\n```text\njson\n```\n\n========================================\n\nComments:\n- You might want to improve your question with code examples that didn't work or did not give the result you expected. Furthermore is always advisable to the relevant entity (partially) and have the current code snippet you wanted to call this query from\n- Using the queryBuilder as you sujested, how to deal with it when the properties are optional, for example, if the lastName is a optional property, the ORM will return with exception? Or he will not find the entity because the property value is undefined?\n- I think then there will be no result based on the lastName as there are no rows matching `Saw` since there are all not defined in your DB. Therefore no matching possible.","metadata":{"transformedAt":"2026-08-18T18:33:44.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":31,"totalLines":346,"estimatedTokens":1736}}61{"id":"stack-54998520","source":"stackoverflow","questionId":54998520,"title":"Multiple JOIN with TYPEORM","tags":["javascript","sql","typeorm"],"text":"Title: Multiple JOIN with TYPEORM\nTags: javascript, sql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm new on `typeorm`, maybe someone can resolve my problem.\n\nI have some query like :\n\n```\nSELECT t1.id,t2.id_2,t3.event,t3.column1,t4.column1 FROM table1 t1\nINNER JOIN table2 t2 ON t1.id = t2.id\nINNER JOIN table3 t3 ON t2.event = t3.event\nINNER JOIN table4 t4 ON t4.id = t2.id_2 WHERE t3.event = 2019\n```\n\nHow to convert this query to `typeorm`?\n\n========================================\n\nCode:\n```text\nSELECT t1.id,t2.id_2,t3.event,t3.column1,t4.column1 FROM table1 t1\nINNER JOIN table2 t2 ON t1.id = t2.id\nINNER JOIN table3 t3 ON t2.event = t3.event\nINNER JOIN table4 t4 ON t4.id = t2.id_2 WHERE t3.event = 2019\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeorm\n```\n\n```text\nawait getManager()\n .createQueryBuilder(table1, 't1')\n .select('t1.id', 't1_id')\n .addSelect('t2.id_2', 't2_id_2')\n .addSelect('t3.event', 't3_event')\n .addSelect('t4.column1', 't4_column1') // up to this point: SELECT t1.id,t2.id_2,t3.event,t3.column1,t4.column1 FROM table1 t1\n .innerJoin(table2, 't2', 't1.id = t2.id') //INNER JOIN table2 t2 ON t1.id = t2.id\n .innerJoin(table3, 't3', 't2.event = t3.event') // INNER JOIN table3 t3 ON t2.event = t3.event\n .innerJoin(table4, 't4', 't4.id = t2.id_2') // INNER JOIN table4 t4 ON t4.id = t2.id_2 \n .where('t3.event = 2019') // WHERE t3.event = 2019\n .getRawMany() // depend on what you need really\n```\n\n```text\ngetOne\n```\n\n```text\ngetMany\n```\n\n```text\ngetRawOne\n```\n\n```text\ngetRawMany\n```\n\n========================================\n\nComments:\n- If the sentence starts with `.addSelect`, you may experience aggregate problem. First .addSelect should be `.select`\n- True, I usually start with `.select` for the first one. thanks @umutyerebakmaz for noticing that.\n- If I use an injected repository to create a Query Builder, the `getMany` method returns an empty array while the `getRawMany()` method returns the expected result. Is this expected behavior of NestJS TypeORM 7.1.5?","metadata":{"transformedAt":"2026-08-18T18:33:44.687Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":72,"estimatedTokens":517}}62{"id":"stack-66117005","source":"stackoverflow","questionId":66117005,"title":"TypeORM - left joining without \"deletedAt IS NULL\"","tags":["nestjs","typeorm"],"text":"Title: TypeORM - left joining without \"deletedAt IS NULL\"\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nBeen searching this one for a while now, not sure if this is something unorthodox in the SQL world but I am trying to do a left join that counts with not null \"deletedAt\" column, but I cannot seem to find a way to do a left join which includes deletes.\n\nThis is just a dummy example that illustrates what I am trying to do, in this case I want to retrieve the person's information as well as the job's, but the job has been soft-deleted.\n\n```\nthis.createQueryBuilder('person')\n .leftJoinAndSelect('person.job', 'job')\n```\n\nThe SQL query produced by this implicitly adds \"IS NOT NULL\" on the **left join** but I have this scenario in which I need the information from a record that is indeed deleted.\n\nI haven't been able to find a way to include this as you would do it at the root level by including.\n\n```\n.withDeleted();\n```\n\nAnyone has any tips?\n\n========================================\n\nCode:\n```text\nthis.createQueryBuilder('person')\n .leftJoinAndSelect('person.job', 'job')\n```\n\n```text\n.withDeleted();\n```\n\n```text\n// Normal case: Exclude both soft-deleted 'Person' and 'Job':\n this.createQueryBuilder(\"Person\")\n .leftJoinAndSelect('Person.job', 'Job');\n\n// 'withDeleted() after the join: Include soft-deleted 'Person' BUT EXCLUDE soft-deleted 'Job':\n this.createQueryBuilder(\"Person\")\n .leftJoinAndSelect('Person.job', 'Job')\n .withDeleted();\n\n// 'withDeleted() before the join: Include both soft-deleted 'Person' and 'Job':\n this.createQueryBuilder(\"Person\")\n .withDeleted()\n .leftJoinAndSelect('Person.job', 'Job');\n```\n\n```text\n// 'withDeleted() before the join with extra condition: Exclude soft-deleted 'Person' BUT INCLUDE soft-deleted 'Job':\n this.createQueryBuilder(\"Person\")\n .withDeleted()\n .andWhere(\"Person.deletedAt Is Null\")\n .leftJoinAndSelect('Person.job', 'Job');\n```\n\n```text\n.withDeleted()\n```\n\n```text\n.leftJoinAndSelect()\n```\n\n```text\n\"Person.deletedAt IS NULL\"\n```\n\n========================================\n\nComments:\n- Try using the .getRaw methods or this.repository.manager.createQueryBuilder() with the second method you have to specify the from clause and the selected fields.\n- Hello there @Edward, thanks for the reply. I am using TypeORM 0.2.31 which appears to be the version of that thread you've linked! As per the logging, which I was luckily already using, the query always prints ' AND \"job\".\"deletedAt\" IS NULL'. I am querying using getMany: this.createQueryBuilder('person').leftJoinAndSelect('person.‌​job', 'job').getMany(); I am using postgres. I've noticed the change github.com/typeorm/typeorm/commit/… could it be metadata?\n- Hello again @FPJ: I was completely wrong: It DOES add' AND \"job\".\"deletedAt\" IS NULL' , as you said. It seems bad behaviour to me, not what I expected, and I missed it when I tested - I guess I saw what I wanted to see! Same behaviour for both TypeORM 0.2.30 and 0.2.31. I'm going to edit my answer to suggest a workaround.\n- Hey again @Edward. Completely fine, the behaviour appears to be something new if I am not mistaken. This workaround unfortunately does not work. The withDeleted is applied to \"Person\" and I actually wanted it to be added to \"Job\". The only work around I've found so far is to make a RAW query (since my actual query is pretty big), which defeats completely the purpose of TypeORM :( I just don't understand why I can't find an option to simply shut down the implicit condition applied by the left join...\n- Hi again @FPJ : I changed my answer again - The generated query seems to depend on where you place .withDeleted(). I hope you use my final idea to make it work for you.\n- I believe I missed my tests with the withDeleted positioning. I've resorted to reverting back to 0.2.30 since I am close to a release and wanted everything stable, but I do whole heartedly appreciate your explanation as I'll be taking this to my next update. Not sure of why such a big change on their end but I'm sure it'll make sense. Big thank you for the effort, you've been quite helpful!","metadata":{"transformedAt":"2026-08-18T18:33:44.687Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":81,"estimatedTokens":1049}}63{"id":"stack-66371656","source":"stackoverflow","questionId":66371656,"title":"Difference forRoot and forFeature [Nest JS]","tags":["javascript","typescript","nestjs","typeorm"],"text":"Title: Difference forRoot and forFeature [Nest JS]\nTags: javascript, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI would like to understand the difference between forRoot and forFeature in nest js dynamic modules.\n\nI also would like to understand this difference in the case of the TypeOrm dynamic module used with nestjs.\n\n========================================\n\nTop Answer:\nFrom Nest.js Discord,\n\n- `forRoot` / `forRootAsync`: configure a module **one time**. This is either for a global service, or a re-used configuration internally\n\n- `forFeature` / `forFeatureAsync`: make use of the configuration from forRoot/forRootAsync **for a specific provider**. This usually creates an injection token.\n\n- `register` / `registerAsync`: a module that can be registered **multiple times** with different configurations each time.\n\n========================================\n\nCode:\n```text\nforRoot\n```\n\n```text\nregister\n```\n\n```text\nforFeature\n```\n\n```text\nTypeOrmModule\n```\n\n```text\nforRoot()\n```\n\n```text\nconnection\n```\n\n```text\nforFeature\n```\n\n```text\n<EntityName>Repository\n```\n\n```text\nforRoot\n```\n\n```text\nforFeature\n```\n\n```text\nforRoot\n```\n\n```text\nforRootAsync\n```\n\n```text\nforFeature\n```\n\n```text\nforFeatureAsync\n```\n\n```text\nregister\n```\n\n```text\nregisterAsync\n```\n\n========================================\n\nComments:\n- Why doesn't the forRoot method here: github.com/nestjs/typeorm/blob/7.0.0/lib/typeorm.module.ts return an object with an export member?\n- @Platus, it does. What about the explanation here that kind of conflicts or expands upon what you said? gist.github.com/darwinsubramaniam/…","metadata":{"transformedAt":"2026-08-18T18:33:44.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":92,"estimatedTokens":407}}64{"id":"stack-62130381","source":"stackoverflow","questionId":62130381,"title":"How to initialize an entity passing in an object using typeorm","tags":["node.js","typescript","typeorm"],"text":"Title: How to initialize an entity passing in an object using typeorm\nTags: node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have an entity \"List\" and i want to create a new list by passing in an object into the constructor.\n\n**List.ts**\n\n```\nimport {Entity, PrimaryColumn, Column, CreateDateColumn, UpdateDateColumn, DeleteDateColumn } from \"typeorm\";\n\n@Entity()\nexport class List {\n\n @PrimaryColumn()\n id: string;\n\n @Column({type: \"varchar\", nullable: true})\n dtype: string;\n\n @Column({type: \"varchar\", nullable: true})\n title: string;\n\n @Column({type: \"varchar\"})\n user_id: string;\n\n @Column({type: \"varchar\", nullable: true})\n brand_id: string;\n\n @CreateDateColumn({type: \"timestamp\", nullable: true})\n created_at: string;\n\n @UpdateDateColumn({type: \"timestamp\", nullable: true})\n updated_at: string;\n\n @DeleteDateColumn({type: \"timestamp\", nullable: true})\n deleted_at: string;\n\n}\n```\n\n**list.test**\n\n```\nimport \"reflect-metadata\";\nimport {createConnection, getRepository} from \"typeorm\";\nimport {List} from \"./../../src/entity/lists/List\";\n\ndescribe(\"List\", () => {\n\n let connection\n beforeAll( async () => {\n connection = await createConnection();\n console.log(connection);\n });\n\n it(\"should insert a list into database\", async () => {\n\n const listRepository = getRepository(List);\n\n const list = new List({\n id: \"7e60c4ef\",\n dtype: \"brandlist\",\n title: \"OnePlus\",\n user_id: \"3aecd1b0-c34d-4427-9abd-fdacef00eaa5\",\n brand_id: \"7e60c4ef-0e6f-46c9-948b-a97d555bf4e4\",\n });\n\n })\n\n})\n```\n\nRight now i get the following\n\n Expected 0 arguments, but got 1.ts(2554)\n\nIs there a way typeorm can automatically handles this?\n\n========================================\n\nTop Answer:\nEdit: I did arrive at this thread by trying to search how to initialize a TypeORM object/class by passing attributes/body params/object. So, if you need a single object you can use the manager.\n\n```\nimport { getManager } from \"typeorm\";\n// ...\nconst manager = getManager();\nconst newUser = manager.create(User, req.body);\nconst user = await manager.save(newUser);\n```\n\nExample creating a user object and saving it from an express request dynamic body. This example is just to illustrate. Validate and sanitize your schema before passing it to the create function to avoid allowing the API user to pass any parameter like `{admin: true}` ;).\n\n```\nimport { getManager } from \"typeorm\";\ncreateConnection()\n .then(async (connection) => {\n const app = express();\n app.use(express.json());\n\n app.post(\"/users\", async (req: Request, res: Response) => {\n const manager = getManager();\n const newUser = manager.create(User, req.body);\n const user = await manager.save(newUser);\n res.json(user);\n });\n\n app.listen(4000);\n })\n .catch((error) => console.log(error));\n```\n\n========================================\n\nCode:\n```text\nimport {Entity, PrimaryColumn, Column, CreateDateColumn, UpdateDateColumn, DeleteDateColumn } from \"typeorm\";\n\n@Entity()\nexport class List {\n\n @PrimaryColumn()\n id: string;\n\n @Column({type: \"varchar\", nullable: true})\n dtype: string;\n\n @Column({type: \"varchar\", nullable: true})\n title: string;\n\n @Column({type: \"varchar\"})\n user_id: string;\n\n @Column({type: \"varchar\", nullable: true})\n brand_id: string;\n\n @CreateDateColumn({type: \"timestamp\", nullable: true})\n created_at: string;\n\n @UpdateDateColumn({type: \"timestamp\", nullable: true})\n updated_at: string;\n\n @DeleteDateColumn({type: \"timestamp\", nullable: true})\n deleted_at: string;\n\n}\n```\n\n```text\nimport \"reflect-metadata\";\nimport {createConnection, getRepository} from \"typeorm\";\nimport {List} from \"./../../src/entity/lists/List\";\n\ndescribe(\"List\", () => {\n\n let connection\n beforeAll( async () => {\n connection = await createConnection();\n console.log(connection);\n });\n\n it(\"should insert a list into database\", async () => {\n\n const listRepository = getRepository(List);\n\n const list = new List({\n id: \"7e60c4ef\",\n dtype: \"brandlist\",\n title: \"OnePlus\",\n user_id: \"3aecd1b0-c34d-4427-9abd-fdacef00eaa5\",\n brand_id: \"7e60c4ef-0e6f-46c9-948b-a97d555bf4e4\",\n });\n\n })\n\n})\n```\n\n```text\nconst listRepository = connection.getRepository(List);\n\n const list = listRepository.create({\n id: \"7e60c4ef\",\n dtype: \"brandlist\",\n title: \"OnePlus\",\n user_id: \"3aecd1b0-c34d-4427-9abd-fdacef00eaa5\",\n brand_id: \"7e60c4ef-0e6f-46c9-948b-a97d555bf4e4\",\n });\n\n const newList = await listRepository.save(list);\n```\n\n```text\nrepository.create\n```\n\n```js\nimport { getManager } from \"typeorm\";\n// ...\nconst manager = getManager();\nconst newUser = manager.create(User, req.body);\nconst user = await manager.save(newUser);\n```\n\n```js\nimport { getManager } from \"typeorm\";\ncreateConnection()\n .then(async (connection) => {\n const app = express();\n app.use(express.json());\n\n app.post(\"/users\", async (req: Request, res: Response) => {\n const manager = getManager();\n const newUser = manager.create(User, req.body);\n const user = await manager.save(newUser);\n res.json(user);\n });\n\n app.listen(4000);\n })\n .catch((error) => console.log(error));\n```\n\n```text\n{admin: true}\n```\n\n```text\nconst newList = List.create({\n id: \"7e60c4ef\",\n dtype: \"brandlist\",\n title: \"OnePlus\",\n user_id: \"3aecd1b0-c34d-4427-9abd-fdacef00eaa5\",\n brand_id: \"7e60c4ef-0e6f-46c9-948b-a97d555bf4e4\",\n})\n```\n\n========================================\n\nComments:\n- you can also use getManager().create instead to use repository mode.\n- What if your relationships are set up in the following manner typeorm.io/#/many-to-one-one-to-many-relations\n- @EmanuelePavanello I believe in this specific case typeorm will have troubles identifying, *which* entity you're trying to create actually, no? Like what if two different datatypes fit to the json provided? I believe in the case you should use `new MyEntity()` construct, which doesn't fit the question anymore.","metadata":{"transformedAt":"2026-08-18T18:33:44.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":245,"estimatedTokens":1519}}65{"id":"stack-65525851","source":"stackoverflow","questionId":65525851,"title":"How to make Inner Join to work on TypeORM?","tags":["typeorm"],"text":"Title: How to make Inner Join to work on TypeORM?\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build a simple query on TypeORM but I'm not getting the entire data using INNER JOIN. What am I doing wrong?\n\nThe SQL query runs perfectly but the typeorm one just returns me the data for the 'watcher' table.\n\n**SQL Query**\n\n```\nSELECT *\nFROM watcher w\nINNER JOIN user\nON w.userId = user.id;\n```\n\n**TypeORM**\n\n```\nasync getSystemWideWatchers(): Promise {\n const query = this.createQueryBuilder('watcher');\n const result = await query.innerJoin('user', 'u', 'watcher.userId = u.id').getMany();\n console.log(result)\n return result;\n}\n```\n\n========================================\n\nTop Answer:\nJust in case someone runs into another scenario. Adding to what Cem answered.\nIf there's no relationship defined in the database then you can do the following :\n\n```\nconst query = createQueryBuilder('user', 'u') \n.innerJoinAndMapMany(\n 'u.ObjectNameToMapDataOn',\n EntityName,// or 'tableName'\n 'IAmAlias',\n 'u.columnName= IAmAlias.columnName'\n )\n```\n\nsimilarly , innerJoinAndMapOne can be used. Depends on your case if you expect to have multiple records with joining table or single record.\n\n========================================\n\nCode:\n```text\nSELECT *\nFROM watcher w\nINNER JOIN user\nON w.userId = user.id;\n```\n\n```text\nasync getSystemWideWatchers(): Promise<any[]> {\n const query = this.createQueryBuilder('watcher');\n const result = await query.innerJoin('user', 'u', 'watcher.userId = u.id').getMany();\n console.log(result)\n return result;\n}\n```\n\n```js\n@Entity()\nexport class User {\n @PrimaryColumn()\n id: number;\n\n @Column()\n userName: string;\n\n @OneToMany(type => Watcher, watcher => watcher.user)\n watchers: Watcher[];\n}\n```\n\n```js\n@Entity()\nexport class Watcher {\n @PrimaryColumn()\n id: number;\n\n @Column()\n watcherName: string;\n\n // we can omit this (and the join condition), if userId is a foreign key\n @Column()\n userId: number;\n\n @ManyToOne(type => User, user => user.watchers)\n user: User;\n}\n```\n\n```js\n// Select a user and all their watchers\nconst query = createQueryBuilder('user', 'u')\n .innerJoinAndSelect('u.watchers', 'w'); // 'w.userId = u.id' may be omitted\nconst result = await query.getMany();\n```\n\n```js\n// Select a watcher and the user they watch\nconst query = createQueryBuilder('watcher', 'w')\n .innerJoinAndSelect('w.user', 'u'); // 'w.userId = u.id' may be omitted\nconst result = await query.getMany();\n```\n\n```text\ninnerJoinAndSelect\n```\n\n```text\ninnerJoin\n```\n\n```text\ninnerJoinAndSelect\n```\n\n```text\ngetMany\n```\n\n```text\ngetOne\n```\n\n```text\ngetRawMany\n```\n\n```text\nOneToMany\n```\n\n```text\nconst query = createQueryBuilder('user', 'u') \n.innerJoinAndMapMany(\n 'u.ObjectNameToMapDataOn',\n EntityName,// or 'tableName'\n 'IAmAlias',\n 'u.columnName= IAmAlias.columnName'\n )\n```\n\n```text\nthis.userRepository\n .createQueryBuilder('user')\n .select(['user.username as username', 'o.orderTime as orderTime'])\n .where('user.id = :id', {id})\n .andWhere('o.callerId = :id', {id})\n .innerJoin(OrderEntity, 'o')\n .getRawMany()\n```\n\n```text\ngetRow()\n```\n\n```text\ngetOne()\n```\n\n```text\ngetMany()\n```\n\n```sql\nSELECT *\nFROM watcher w\nINNER JOIN user\nON w.userId = user.id;\n```\n\n```js\nthis.userRepo\n.createQueryBuilder(\"u\")\n.leftJoin(Watcher, \"w\", \"u.id = w.userId\");\n```\n\n```text\non\n```\n\n========================================\n\nComments:\n- You probably don't have the necessary relations. I updated my answer. Could you check again?\n- Brother you got it! The entities are exactly how I had it. The problem was that I tried to join by using the `user.id` and `watcher.userId` instead of `watcher.user`. Thank you very very much! Happy new year!\n- Ah - you had the relationship but weren't using it... I'm happy it's fixed, happy new year to you too!\n- Great answer @Cem I have up question, maybe you could help me ;) The query you provided will return: `{ id: 1, userName: 'matt', watchers: [ { id: 1, watcherName: 'joe' } ] }` What if I want to map this value, eg.`{ id: 1, userName: 'matt', watchers: ['joe'] }` or from Watcher perspective, I would like to get: `{ id: 1, watcherName: 'joe', userName: 'matt' }`\n- Thanks! using `getRawMany()` worked for me instead of `getMany()`\n- For example: const res = await createQueryBuilder('profiles', 'profile') .select(['profile.*', 'user.name']) .where('profile.user.id = :userId', { userId }) .innerJoin(User, 'user', 'user.id = :userId', { userId }) .getRawMany();\n- Thanks mate getRawMany() worked , seems getMany only works when entity itself have relations like oneToMany and manyToOne but my entities don't have any relations so raw worked","metadata":{"transformedAt":"2026-08-18T18:33:44.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":199,"estimatedTokens":1190}}66{"id":"stack-55717089","source":"stackoverflow","questionId":55717089,"title":"Test NestJS Service against Actual Database","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: Test NestJS Service against Actual Database\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI would like to be able to test my Nest service against an actual database. I understand that most unit tests should use a mock object, but it also, at times, makes sense to test against the database itself.\n\nI have searched through SO and the GH issues for Nest, and am starting to reach the transitive closure of all answers. :-)\n\nI am trying to work from https://github.com/nestjs/nest/issues/363#issuecomment-360105413. Following is my Unit test, which uses a custom provider to pass the repository to my service class.\n\n```\ndescribe(\"DepartmentService\", () => {\n const token = getRepositoryToken(Department);\n let service: DepartmentService;\n let repo: Repository;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n DepartmentService,\n {\n provide: token,\n useClass: Repository\n }\n ]\n }).compile();\n\n service = module.get(DepartmentService);\n repo = module.get(token);\n });\n```\n\nEverything compiles properly, TypeScript seems happy. However, when I try to execute `create` or `save` on **my** `Repository` instance, the underlying `Repository` appears to be undefined. Here's the stack backtrace:\n\n```\nTypeError: Cannot read property 'create' of undefined\n\n at Repository.Object..Repository.create (repository/Repository.ts:99:29)\n at DepartmentService. (relational/department/department.service.ts:46:53)\n at relational/department/department.service.ts:19:71\n at Object..__awaiter (relational/department/department.service.ts:15:12)\n at DepartmentService.addDepartment (relational/department/department.service.ts:56:16)\n at Object. (relational/department/test/department.service.spec.ts:46:35)\n at relational/department/test/department.service.spec.ts:7:71\n```\n\nIt appears that the `EntityManager` instance with the TypeORM `Repository` class is not being initialized; it is the `undefined` reference that this backtrace is complaining about. \n\nHow do I get the `Repository` and `EntityManager` to initialize properly?\n\nthanks,\ntom.\n\n========================================\n\nTop Answer:\nI prefer not using `@nestjs/testing` for the sake of simplicity.\n\nFirst of all, create a reusable helper:\n\n```\n/* src/utils/testing-helpers/createMemDB.js */\nimport { createConnection, EntitySchema } from 'typeorm'\ntype Entity = Function | string | EntitySchema\n\nexport async function createMemDB(entities: Entity[]) {\n return createConnection({\n // name, // let TypeORM manage the connections\n type: 'sqlite',\n database: ':memory:',\n entities,\n dropSchema: true,\n synchronize: true,\n logging: false\n })\n}\n```\n\nThen, write test:\n\n```\n/* src/user/user.service.spec.ts */\nimport { Connection, Repository } from 'typeorm'\nimport { createMemDB } from '../utils/testing-helpers/createMemDB'\nimport UserService from './user.service'\nimport User from './user.entity'\n\ndescribe('User Service', () => {\n let db: Connection\n let userService: UserService\n let userRepository: Repository\n\n beforeAll(async () => {\n db = await createMemDB([User])\n userRepository = await db.getRepository(User)\n userService = new UserService(userRepository) // db.close())\n\n it('should create a new user', async () => {\n const username = 'HelloWorld'\n const password = 'password'\n\n const newUser = await userService.createUser({ username, password })\n expect(newUser.id).toBeDefined()\n\n const newUserInDB = await userRepository.findOne(newUser.id)\n expect(newUserInDB.username).toBe(username)\n })\n})\n```\n\nRefer to https://github.com/typeorm/typeorm/issues/1267#issuecomment-483775861\n\n========================================\n\nCode:\n```js\ndescribe(\"DepartmentService\", () => {\n const token = getRepositoryToken(Department);\n let service: DepartmentService;\n let repo: Repository<Department>;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n DepartmentService,\n {\n provide: token,\n useClass: Repository\n }\n ]\n }).compile();\n\n service = module.get<DepartmentService>(DepartmentService);\n repo = module.get(token);\n });\n```\n\n```text\nTypeError: Cannot read property 'create' of undefined\n\n at Repository.Object.<anonymous>.Repository.create (repository/Repository.ts:99:29)\n at DepartmentService.<anonymous> (relational/department/department.service.ts:46:53)\n at relational/department/department.service.ts:19:71\n at Object.<anonymous>.__awaiter (relational/department/department.service.ts:15:12)\n at DepartmentService.addDepartment (relational/department/department.service.ts:56:16)\n at Object.<anonymous> (relational/department/test/department.service.spec.ts:46:35)\n at relational/department/test/department.service.spec.ts:7:71\n```\n\n```text\ncreate\n```\n\n```text\nsave\n```\n\n```text\nRepository\n```\n\n```text\nRepository\n```\n\n```text\nEntityManager\n```\n\n```text\nRepository\n```\n\n```text\nundefined\n```\n\n```text\nRepository\n```\n\n```text\nEntityManager\n```\n\n```text\nTest.createTestingModule({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mysql',\n // ...\n }),\n TypeOrmModule.forFeature([Department])\n ]\n```\n\n```text\nTypeOrmModule\n```\n\n```js\ndescribe(\"DepartmentService\", () => {\n let service: DepartmentService;\n let repo: Repository<Department>;\n let module: TestingModule;\n\n beforeAll(async () => {\n module = await Test.createTestingModule({\n imports: [\n TypeOrmModule.forRoot(),\n TypeOrmModule.forFeature([Department])\n ],\n providers: [DepartmentService]\n }).compile();\n\n service = module.get<DepartmentService>(DepartmentService);\n repo = module.get<Repository<Department>>(getRepositoryToken(Department));\n });\n\n afterAll(async () => {\n module.close();\n });\n\n it(\"should be defined\", () => {\n expect(service).toBeDefined();\n });\n\n // ...\n}\n```\n\n```js\n/* src/utils/testing-helpers/createMemDB.js */\nimport { createConnection, EntitySchema } from 'typeorm'\ntype Entity = Function | string | EntitySchema<any>\n\nexport async function createMemDB(entities: Entity[]) {\n return createConnection({\n // name, // let TypeORM manage the connections\n type: 'sqlite',\n database: ':memory:',\n entities,\n dropSchema: true,\n synchronize: true,\n logging: false\n })\n}\n```\n\n```text\n/* src/user/user.service.spec.ts */\nimport { Connection, Repository } from 'typeorm'\nimport { createMemDB } from '../utils/testing-helpers/createMemDB'\nimport UserService from './user.service'\nimport User from './user.entity'\n\ndescribe('User Service', () => {\n let db: Connection\n let userService: UserService\n let userRepository: Repository<User>\n\n beforeAll(async () => {\n db = await createMemDB([User])\n userRepository = await db.getRepository(User)\n userService = new UserService(userRepository) // <--- manually inject\n })\n afterAll(() => db.close())\n\n it('should create a new user', async () => {\n const username = 'HelloWorld'\n const password = 'password'\n\n const newUser = await userService.createUser({ username, password })\n expect(newUser.id).toBeDefined()\n\n const newUserInDB = await userRepository.findOne(newUser.id)\n expect(newUserInDB.username).toBe(username)\n })\n})\n```\n\n```text\n@nestjs/testing\n```\n\n```js\n// ../test/db.ts\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\nimport { EntitySchema } from 'typeorm';\n\ntype Entity = Function | string | EntitySchema<any>;\n\nexport const createTestConfiguration = (\n entities: Entity[],\n): TypeOrmModuleOptions => ({\n type: 'sqlite',\n database: ':memory:',\n entities,\n dropSchema: true,\n synchronize: true,\n logging: false,\n});\n```\n\n```js\n// books.service.test.ts\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { HttpModule, HttpService } from '@nestjs/common';\nimport { TypeOrmModule, getRepositoryToken } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\nimport { BooksService } from './books.service';\nimport { Book } from './book.entity';\nimport { createTestConfiguration } from '../../test/db';\n\ndescribe('BooksService', () => {\n let module: TestingModule;\n let service: BooksService;\n let httpService: HttpService;\n let repository: Repository<Book>;\n\n beforeAll(async () => {\n module = await Test.createTestingModule({\n imports: [\n HttpModule,\n TypeOrmModule.forRoot(createTestConfiguration([Book])),\n TypeOrmModule.forFeature([Book]),\n ],\n providers: [BooksService],\n }).compile();\n\n httpService = module.get<HttpService>(HttpService);\n service = module.get<BooksService>(BooksService);\n repository = module.get<Repository<Book>>(getRepositoryToken(Book));\n });\n\n afterAll(() => {\n module.close();\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n```\n\n```text\nlet service: SampleService;\n let connection: Connection;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n imports: [AppModule, TypeOrmModule.forFeature([SampleEntity])],\n providers: [SampleService],\n }).compile();\n\n service = module.get<SampleService>(SampleService);\n connection = await module.get(getConnectionToken());\n });\n\n afterEach(async () => {\n await connection.close();\n });\n```\n\n```text\nAppModule\n```\n\n```text\nimport { INestApplication } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\n\nimport { AppModule } from '../../../app.module';\nimport { AuthService } from '../auth.service';\nimport { UserRepo } from '../../user/user.repo';\n\ndescribe('AuthService', () => {\n let app: INestApplication;\n let service: AuthService;\n let repo: UserRepo;\n\n beforeAll(async () => {\n app = await NestFactory.create(AppModule);\n service = app.get(AuthService);\n\n repo = app.get(UserRepo); // or with private access service['userRepo'];\n });\n\n afterAll(async () => {\n await app.close();\n });\n\n it('AuthService should be defined', () => {\n expect(service).toBeDefined();\n });\n\n describe('login', () => {\n it('should login user', async () => {\n const user = await service.login({ email: 'user@gmail.com', password: '12345678' });\n\n expect(user.id).toBeDefined();\n });\n });\n\n describe('userRepo', () => {\n it('should find user without errors', async () => {\n const user = await repo.findBy({ email: 'user@gmail.com' });\n\n expect(user).toBeDefined();\n });\n\n it('should throw not found exception', async () => { \n await expect(repo.findBy({ email: 'not_found_user@gmail.com' })).rejects.toThrow();\n });\n });\n});\n```\n\n```text\nimport { config as testConfig } from 'dotenv';\n\nif (process.env.NODE_ENV === 'test') {\n testConfig({ path: resolve('./.test.env') });\n}\n```\n\n========================================\n\nComments:\n- That is a huge step in the right direction! It appears that this causes a new database connection to be created each time the code runs. Is that correct? If so, is the right way to close the connection to run `module.close()`? Do you recommend setting up the module in a `beforeAll` or a `beforeEach`?\n- Yep, it's important that you close the connection. Otherwise your test will not exit and you have to force close jest. beforeAll/afterAll sound reasonable, you can also pass `KEEP_CONNECTION_ALIVE: true` to typeorm to reuse the connection.\n- It seems not working with a custom repository. Any ideas @KimKern?\n- @JeffMinsungKim I'd assume you have to set up your test the same way you set up your database in the real application (i.e. imports). If you need more support, better open a new question so that you can post your setup (app + test that doesn't work)\n- @JeffMinsungKim in my case the `forFeature` included the custom repositories. As Kime said, use the same tht you uses in your module. In my case: `imports: [TypeOrmModule.forRoot(TypeOrmConfig), TypeOrmModule.forFeature([UserRepository, MessageRepository])],`\n- Can you add how `user.service` is defined?\n- Is this working for e2e testing, I mean when I use superset, and call the endpoint. Does this work as expected?","metadata":{"transformedAt":"2026-08-18T18:33:44.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":437,"estimatedTokens":3052}}67{"id":"stack-58993405","source":"stackoverflow","questionId":58993405,"title":"How can I handle TypeORM error in NestJS?","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: How can I handle TypeORM error in NestJS?\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'd like to create a custom exception filter that handles different kinds of TypeORM errors. I've looked up the TypeORM error classes, and it seems like there's no such thing in TypeORM like MongoError.\n\nI wanted to make something similar to 1FpGLLjZSZMx6k's answer, and here's what I've done so far.\n\n```\nimport { QueryFailedError } from 'typeorm';\n\n@Catch(QueryFailedError)\nexport class QueryFailedExceptionFilter implements ExceptionFilter {\n catch(exception: QueryFailedError, host: ArgumentsHost) {\n const context = host.switchToHttp();\n const response = context.getResponse();\n const request = context.getRequest();\n const { url } = request;\n const { name } = exception;\n const errorResponse = {\n path: url,\n timestamp: new Date().toISOString(),\n message: name,\n };\n\n response.status(HttpStatus.BAD_REQUEST).json(errorResponse);\n }\n}\n```\n\nIf I need to catch another error for instance, `EntityNotFoundError`, I have to write the same code which is a very cumbersome task to do it.\n\nIt would be nice if I could handle errors by a single filter like below. Any ideas?\n\n```\n@Catch(TypeORMError)\nexport class EntityNotFoundExceptionFilter implements ExceptionFilter {\n catch(exception: MongoError, host: ArgumentsHost) {\n switch (exception.code) {\n case some error code:\n // handle error\n }\n }\n}\n```\n\n========================================\n\nTop Answer:\nTo handle different kinds of TypeOrm errors, you can switch / case the exception constructor if it matches any TypeOrm error (from node_modules\\typeorm\\error). Additionally, the (exception as any).code will provide the actual database error that occured. Notice the @catch() decorator is empty in order to catch all error types.\n\n```\nimport { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';\nimport { Request, Response } from 'express';\nimport { QueryFailedError, EntityNotFoundError, CannotCreateEntityIdMapError } from 'typeorm';\nimport { GlobalResponseError } from './global.response.error';\n\n@Catch()\nexport class GlobalExceptionFilter implements ExceptionFilter {\n catch(exception: unknown, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse();\n const request = ctx.getRequest();\n let message = (exception as any).message.message;\n let code = 'HttpException';\n\n Logger.error(message, (exception as any).stack, `${request.method} ${request.url}`);\n\n let status = HttpStatus.INTERNAL_SERVER_ERROR;\n \n switch (exception.constructor) {\n case HttpException:\n status = (exception as HttpException).getStatus();\n break;\n case QueryFailedError: // this is a TypeOrm error\n status = HttpStatus.UNPROCESSABLE_ENTITY\n message = (exception as QueryFailedError).message;\n code = (exception as any).code;\n break;\n case EntityNotFoundError: // this is another TypeOrm error\n status = HttpStatus.UNPROCESSABLE_ENTITY\n message = (exception as EntityNotFoundError).message;\n code = (exception as any).code;\n break;\n case CannotCreateEntityIdMapError: // and another\n status = HttpStatus.UNPROCESSABLE_ENTITY\n message = (exception as CannotCreateEntityIdMapError).message;\n code = (exception as any).code;\n break;\n default:\n status = HttpStatus.INTERNAL_SERVER_ERROR\n }\n\n response.status(status).json(GlobalResponseError(status, message, code, request));\n }\n}\n\nimport { Request } from 'express';\nimport { IResponseError } from './response.error.interface';\n\nexport const GlobalResponseError: (statusCode: number, message: string, code: string, request: Request) => IResponseError = (\n statusCode: number,\n message: string,\n code: string,\n request: Request\n): IResponseError => {\n return {\n statusCode: statusCode,\n message,\n code,\n timestamp: new Date().toISOString(),\n path: request.url,\n method: request.method\n };\n};\n\nexport interface IResponseError {\n statusCode: number;\n message: string;\n code: string;\n timestamp: string;\n path: string;\n method: string;\n}\n```\n\n*Note: As of new version of `typeorm` import for `EntityNotFoundError` and `CannotCreateEntityIdMapError` will be as bellow*\n\n```\nimport { QueryFailedError } from 'typeorm';\nimport { EntityNotFoundError } from 'typeorm/error/EntityNotFoundError';\nimport { CannotCreateEntityIdMapError } from 'typeorm/error/CannotCreateEntityIdMapError';\n```\n\n========================================\n\nCode:\n```js\nimport { QueryFailedError } from 'typeorm';\n\n@Catch(QueryFailedError)\nexport class QueryFailedExceptionFilter implements ExceptionFilter {\n catch(exception: QueryFailedError, host: ArgumentsHost) {\n const context = host.switchToHttp();\n const response = context.getResponse<Response>();\n const request = context.getRequest<Request>();\n const { url } = request;\n const { name } = exception;\n const errorResponse = {\n path: url,\n timestamp: new Date().toISOString(),\n message: name,\n };\n\n response.status(HttpStatus.BAD_REQUEST).json(errorResponse);\n }\n}\n```\n\n```js\n@Catch(TypeORMError)\nexport class EntityNotFoundExceptionFilter implements ExceptionFilter {\n catch(exception: MongoError, host: ArgumentsHost) {\n switch (exception.code) {\n case some error code:\n // handle error\n }\n }\n}\n```\n\n```text\nEntityNotFoundError\n```\n\n```text\n@Catch(QueryFailedError, EntityNotFoundError)\n```\n\n```text\n@Catch()\n```\n\n```text\nimport { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';\nimport { Request, Response } from 'express';\nimport { QueryFailedError, EntityNotFoundError, CannotCreateEntityIdMapError } from 'typeorm';\nimport { GlobalResponseError } from './global.response.error';\n\n@Catch()\nexport class GlobalExceptionFilter implements ExceptionFilter {\n catch(exception: unknown, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse<Response>();\n const request = ctx.getRequest<Request>();\n let message = (exception as any).message.message;\n let code = 'HttpException';\n\n Logger.error(message, (exception as any).stack, `${request.method} ${request.url}`);\n\n let status = HttpStatus.INTERNAL_SERVER_ERROR;\n \n switch (exception.constructor) {\n case HttpException:\n status = (exception as HttpException).getStatus();\n break;\n case QueryFailedError: // this is a TypeOrm error\n status = HttpStatus.UNPROCESSABLE_ENTITY\n message = (exception as QueryFailedError).message;\n code = (exception as any).code;\n break;\n case EntityNotFoundError: // this is another TypeOrm error\n status = HttpStatus.UNPROCESSABLE_ENTITY\n message = (exception as EntityNotFoundError).message;\n code = (exception as any).code;\n break;\n case CannotCreateEntityIdMapError: // and another\n status = HttpStatus.UNPROCESSABLE_ENTITY\n message = (exception as CannotCreateEntityIdMapError).message;\n code = (exception as any).code;\n break;\n default:\n status = HttpStatus.INTERNAL_SERVER_ERROR\n }\n\n response.status(status).json(GlobalResponseError(status, message, code, request));\n }\n}\n\n\nimport { Request } from 'express';\nimport { IResponseError } from './response.error.interface';\n\nexport const GlobalResponseError: (statusCode: number, message: string, code: string, request: Request) => IResponseError = (\n statusCode: number,\n message: string,\n code: string,\n request: Request\n): IResponseError => {\n return {\n statusCode: statusCode,\n message,\n code,\n timestamp: new Date().toISOString(),\n path: request.url,\n method: request.method\n };\n};\n\n\nexport interface IResponseError {\n statusCode: number;\n message: string;\n code: string;\n timestamp: string;\n path: string;\n method: string;\n}\n```\n\n```text\nimport { QueryFailedError } from 'typeorm';\nimport { EntityNotFoundError } from 'typeorm/error/EntityNotFoundError';\nimport { CannotCreateEntityIdMapError } from 'typeorm/error/CannotCreateEntityIdMapError';\n```\n\n```text\ntypeorm\n```\n\n```text\nEntityNotFoundError\n```\n\n```text\nCannotCreateEntityIdMapError\n```\n\n```js\nimport { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common';\nimport { TypeORMError } from 'typeorm';\nimport { ErrorMessage } from '../error.interface';\n\n@Catch(TypeORMError)\nexport class TypeOrmFilter implements ExceptionFilter {\n catch(exception: TypeORMError, host: ArgumentsHost) {\n const response = host.switchToHttp().getResponse();\n let message: string = (exception as TypeORMError).message;\n let code: number = (exception as any).code;\n const customResponse: ErrorMessage = {\n status: 500,\n message: 'Something Went Wrong',\n type: 'Internal Server Error',\n errors: [{ code: code, message: message }],\n errorCode: 300,\n timestamp: new Date().toISOString(),\n };\n\n response.status(customResponse.status).json(customResponse);\n }\n}\n```\n\n```text\n@Catch(TypeORMError)\nexport class EntityNotFoundExceptionFilter implements ExceptionFilter {\n catch(exception: TypeORMError, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse<Response>();\n const request = ctx.getRequest<Request>();\n let status = exception.getStatus();\n let message = '';\n switch (instanceof exception) {\n case InitializedRelationError:\n // handle error like\n staus = 1;\n message = '2';\n break;\n case AlreadyHasActiveConnectionError:\n // handle other error\n break;\n ...\n // ATTENTION other exception classes from node_modules/typeorm/errors \n ...\n default:\n // handle it like internal server error\n status = 500;\n message = 'Database exception';\n }\n \n response\n .status(status)\n .json({\n statusCode: status,\n timestamp: new Date().toISOString(),\n path: request.url,\n });\n }\n}\n```\n\n========================================\n\nComments:\n- Thanks for the response. So how am I supposed to handle different exceptions? What would be the first parameter in catch() method?\n- @JeffMinsungKim As they all extend `Error` the type can either be `Error` or an explicit list of the types `QueryFailedError | EntityNotFoundError`. If you have code specific to certain errors, you can guard this logic with `instanceof`.\n- Very useful answer! However, I'm wondering if it is secure to return the database exception to the user. Isn't it bad if potential attackers can obtain table names, foreign keys, etc. by purposely throwing exceptions?\n- How can I use it in my code?\n- Great! Useful answer.\n- Please provide more details on your solution, not only code.\n- Please , how and where to use this implementation. an answer like this doesn't do any good","metadata":{"transformedAt":"2026-08-18T18:33:44.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":352,"estimatedTokens":2783}}68{"id":"stack-71635179","source":"stackoverflow","questionId":71635179,"title":"Type 'string' has no properties in common with type 'FindOneOptions'","tags":["node.js","typescript","express","typeorm"],"text":"Title: Type 'string' has no properties in common with type 'FindOneOptions'\nTags: node.js, typescript, express, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to build a backend with express.js. I now have the following problem:\n\n```\nimport { Request, Response } from \"express\";\nimport { getManager } from \"typeorm\";\nimport { User } from \"../entity/user.entity\";\n\nexport const GetUser = async (req: Request, res: Response) => {\n const repository = getManager().getRepository(User);\n\n const { password, ...user } = await repository.findOne(req.params.id);\n\n res.send(user);\n};\n```\n\nThe following error always occurs:\n\n(parameter) req: Request>\nType 'string' has no properties in common with type 'FindOneOptions'.ts(2559)\nhttps://i.sstatic.net/kAjkc.png\nrouter.ts\n\n```\nrouter.get(\"/api/users/:id\", AuthMiddleware, GetUser);\n```\n\nuser.entity.ts\n\n```\nimport {\n Column,\n Entity,\n JoinColumn,\n ManyToOne,\n PrimaryGeneratedColumn,\n} from \"typeorm\";\nimport { Role } from \"./role.entity\";\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n @Column()\n first_name: string;\n @Column()\n last_name: string;\n @Column({\n unique: true,\n })\n email: string;\n @Column()\n password: string;\n\n @ManyToOne(() => Role)\n @JoinColumn({ name: \"role_id\" })\n role: Role;\n}\n```\n\nCan anyone help me with my problem?\n\n========================================\n\nTop Answer:\nAnyone migrating from **NestJs v7** to **v9** will run into this issue because they use **different TypeORM versions**.\n\nTurns out this was a breaking change on **TypeORM** side.\n\nGoing from **v0.2.x** to **v0.3.x** has this breaking change they dropped the `findOne(id)` method in favor of `findOneBy({where : {id: id}})`\n\nCheck Here: https://typeorm.io/changelog#breaking-changes-1 \n\nhttps://i.sstatic.net/rhL3W.png\n\nI have TypeORM v0.3.12:\n\nhttps://i.sstatic.net/FBiak.png\n\nHere I get the same error\nhttps://i.sstatic.net/VJqQQ.png\n\nNow the error is resolved:\n\nhttps://i.sstatic.net/dOsNM.png\n\nThis video rang the bell for me: https://www.youtube.com/watch?v=UEFEze_SQKU\n\n========================================\n\nCode:\n```text\nimport { Request, Response } from \"express\";\nimport { getManager } from \"typeorm\";\nimport { User } from \"../entity/user.entity\";\n\n\nexport const GetUser = async (req: Request, res: Response) => {\n const repository = getManager().getRepository(User);\n\n const { password, ...user } = await repository.findOne(req.params.id);\n\n res.send(user);\n};\n```\n\n```text\nrouter.get(\"/api/users/:id\", AuthMiddleware, GetUser);\n```\n\n```text\nimport {\n Column,\n Entity,\n JoinColumn,\n ManyToOne,\n PrimaryGeneratedColumn,\n} from \"typeorm\";\nimport { Role } from \"./role.entity\";\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n @Column()\n first_name: string;\n @Column()\n last_name: string;\n @Column({\n unique: true,\n })\n email: string;\n @Column()\n password: string;\n\n @ManyToOne(() => Role)\n @JoinColumn({ name: \"role_id\" })\n role: Role;\n}\n```\n\n```js\nrepository.findOne({where: {id: parseInt(req.params.id, 10)}})\n```\n\n```js\nrepository.findOneBy({id: parseInt(req.params.id, 10)})\n```\n\n```text\nfindOne\n```\n\n```text\nSelect * ... limit 1\n```\n\n```text\nfindOne\n```\n\n```text\nid\n```\n\n```text\nreq.params.id\n```\n\n```text\nfindOneBy({id: req.params.id});\n```\n\n```text\nfindOne(id)\n```\n\n```text\nfindOneBy({where : {id: id}})\n```\n\n========================================\n\nComments:\n- Please do not upload images of code/data/errors.\n- Thank you for your answer I tried both solutions but it doesnt work. (property) id?: number | FindOperator Type 'string' is not assignable to type 'number | FindOperator'.ts(2322)\n- @bobby17jones, This is because `req.params.id` is a string where as in your code the `id` is Int. Just use #parseInt function and this will work.\n- @bobby17jones updated the answer to fix your issue.\n- Please don't post screenshots of text. They can't be searched or copied, or even consumed by users of adaptive technologies like screen readers. Instead, paste the code as text directly into your question, then select it and click the code block button. And for documentation, mark it as a blockquote.","metadata":{"transformedAt":"2026-08-18T18:33:44.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":194,"estimatedTokens":1034}}69{"id":"stack-62050659","source":"stackoverflow","questionId":62050659,"title":"How to add a helper method to a typeORM entity?","tags":["typescript","typeorm"],"text":"Title: How to add a helper method to a typeORM entity?\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to add a helper method to one of my Entity classes but I'm getting an error message. My entity:\n\n```\nimport { Entity, PrimaryColumn, Column } from 'typeorm'\n\n@Entity('accounts')\nclass Account {\n @PrimaryColumn()\n username: string\n\n @Column({ name: 'firstname' })\n firstName: string\n\n @Column({ name: 'lastname' })\n lastName: string\n\n public fullName() : string {\n return `${this.firstName} ${this.lastName}`\n }\n}\n```\n\nWhen I try to call `account.fullName()` I get the following error message:\n\n`\"account.fullName\" is not a function`\n\nWhat am I getting wrong?\n\n========================================\n\nCode:\n```text\nimport { Entity, PrimaryColumn, Column } from 'typeorm'\n\n@Entity('accounts')\nclass Account {\n @PrimaryColumn()\n username: string\n\n @Column({ name: 'firstname' })\n firstName: string\n\n @Column({ name: 'lastname' })\n lastName: string\n\n public fullName() : string {\n return `${this.firstName} ${this.lastName}`\n }\n}\n```\n\n```text\naccount.fullName()\n```\n\n```text\n\"account.fullName\" is not a function\n```\n\n```ts\nimport { Entity, PrimaryColumn, Column } from 'typeorm'\n\n@Entity('accounts')\nclass Account {\n @PrimaryColumn()\n username: string\n\n @Column({ name: 'firstname' })\n firstName: string\n\n @Column({ name: 'lastname' })\n lastName: string\n\n public get fullName() : string {\n return `${this.firstName} ${this.lastName}`\n }\n}\n```\n\n```text\nget\n```\n\n========================================\n\nComments:\n- What happens if you want to call it with a parameter?\n- @BurakGavas you can change the `get` keyword to `set` and that's all.\n- Is this as per the best practices/ or, are we allowed to do this without ensuring anything breaks (silently)? Would migrations work properly ?\n- Does it work with typeorm 0.3.17? Do I need to call the function manually?","metadata":{"transformedAt":"2026-08-18T18:33:44.687Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":95,"estimatedTokens":477}}70{"id":"stack-59696814","source":"stackoverflow","questionId":59696814,"title":"TypeORM - never return the password from the database when fetching a user","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: TypeORM - never return the password from the database when fetching a user\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI created a REST API using NestJs with TypeORM. Basically this is my user entity\n\n```\n@Entity('User')\nexport class User extends BaseEntity {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ unique: true })\n public username: string;\n\n public passwordHash: string;\n}\n```\n\nWhen fetching users from the database the sensitive password information get returned too. But I only need the password field for the sign in process. So when calling the service for signing in I compare the password hash from the database user with the provided password from the client. I would never want to return the password information back to the client.\n\nAs you can image fetching users from the database happens quite often, you would have to delete the password information from the user object quite often.\n\nLet's assume you have a group entity and have a relation between them. When fetching users related to a group you would also have to take care for the sensitive data in the groups domain. \n\nAnd maybe some users are deeply nested within an object returned by a big SQL query statement. Is there a way I can \"hide\" some fields? When calling `this.usersRepository.find()` I would get a list of users and each user would have an `id` and a `username` field **but not** a `passwordHash` field. This would make things easier because I only need to fetch the hash field within my `signIn` flow.\n\n========================================\n\nTop Answer:\nYou can use @Exclude, like:\n\n```\n@Entity('User')\nexport class User extends BaseEntity {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ unique: true })\n public username: string;\n\n @Exclude()\n @Column()\n password: string;\n}\n```\n\n========================================\n\nCode:\n```text\n@Entity('User')\nexport class User extends BaseEntity {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ unique: true })\n public username: string;\n\n public passwordHash: string;\n}\n```\n\n```text\nthis.usersRepository.find()\n```\n\n```text\nid\n```\n\n```text\nusername\n```\n\n```text\npasswordHash\n```\n\n```text\nsignIn\n```\n\n```text\n@Entity()\nexport class User {\n\n @Column({select: false})\n password: string;\n}\n```\n\n```text\nselect: false\n```\n\n```text\naddSelect\n```\n\n```text\n@Entity('User')\nexport class User extends BaseEntity {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ unique: true })\n public username: string;\n\n @Exclude()\n @Column()\n password: string;\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":115,"estimatedTokens":650}}71{"id":"stack-62373766","source":"stackoverflow","questionId":62373766,"title":"How to create a unique index containing multiple fields where one is a foreign key","tags":["sql","node.js","typeorm"],"text":"Title: How to create a unique index containing multiple fields where one is a foreign key\nTags: sql, node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to create an index with multiple fields, one of the field is a foriegn key to another table. However i get the following error:\n\n Error: Index \"player_id_UNIQUE\" contains column that is missing in the\n entity (Earning): player_id\n\nGiven that player_id is a foriegn key that im joining how do i handle this\n\n```\nimport { Column, Entity, Index, JoinColumn, ManyToOne, PrimaryColumn } from \"typeorm\";\nimport { PersonPlayer } from \"./PersonPlayer\";\nimport { Team } from \"./Team\";\n\n @Entity()\n @Index(\"player_id_UNIQUE\", [\"player_id\", \"period\", \"year\"], { unique: true })\n export class Earning {\n\n @PrimaryColumn({length: 36})\n id: string;\n\n @Column({nullable: true})\n year: number;\n\n @Column({type: 'decimal', nullable: true})\n amount: number;\n\n @Column({nullable: true, length: 45})\n period: string;\n\n @ManyToOne(() => Team, {nullable: true})\n @JoinColumn({name: 'team_id'})\n team: Team;\n\n @ManyToOne(() => PersonPlayer, {nullable: true})\n @JoinColumn({name: 'player_id'})\n player: PersonPlayer;\n\n @Column({nullable: true, length: 45})\n dtype: string;\n\n }\n```\n\nWhen i generate this entity and create the sql table (without the index) i see `player_id` as one of the columns. But it appears that typeorm is not able to recognize right now with the index that player_id exists in the entity through the joincolumn relationship.\n\n========================================\n\nTop Answer:\n```\n@Index([\"player.id\", \"period\", \"year\"])\n```\n\nOr Just do this ! 🥳\n\n========================================\n\nCode:\n```text\nimport { Column, Entity, Index, JoinColumn, ManyToOne, PrimaryColumn } from \"typeorm\";\nimport { PersonPlayer } from \"./PersonPlayer\";\nimport { Team } from \"./Team\";\n\n @Entity()\n @Index(\"player_id_UNIQUE\", [\"player_id\", \"period\", \"year\"], { unique: true })\n export class Earning {\n\n @PrimaryColumn({length: 36})\n id: string;\n\n @Column({nullable: true})\n year: number;\n\n @Column({type: 'decimal', nullable: true})\n amount: number;\n\n @Column({nullable: true, length: 45})\n period: string;\n\n @ManyToOne(() => Team, {nullable: true})\n @JoinColumn({name: 'team_id'})\n team: Team;\n\n\n @ManyToOne(() => PersonPlayer, {nullable: true})\n @JoinColumn({name: 'player_id'})\n player: PersonPlayer;\n\n @Column({nullable: true, length: 45})\n dtype: string;\n\n }\n```\n\n```text\nplayer_id\n```\n\n```text\n@Index(\"player_id_UNIQUE\", [\"player.id\", \"period\", \"year\"], { unique: true })\n```\n\n```text\nCREATE UNIQUE INDEX \"player_id_UNIQUE\" ON \"user_earning\" (\"player_id\", \"period\", \"year\")\n```\n\n```text\nplayer.id\n```\n\n```text\nplayer_id\n```\n\n```text\n@Index([\"player.id\", \"period\", \"year\"])\n```\n\n```js\n@Column()\nplayer_id: number\n```\n\n```text\nplayer_id\n```\n\n```text\nEarning\n```\n\n```text\nplayer\n```\n\n```text\nplayer_id\n```\n\n========================================\n\nComments:\n- Did you manage to figure this out @Kay? I'm running into the same issue now and cannot find the answer in the official documentation.\n- @VincentvanderWeele Yes, I changed`player: personPlayer` to be `player_id: PersonPlayer`. This works for us because our project is only to handle db migrations, although it would be nicer to have player as the name instead of player_id. But because we are not using the rest of the orm to make any business logic we didin't mind","metadata":{"transformedAt":"2026-08-18T18:33:44.687Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":147,"estimatedTokens":875}}72{"id":"stack-63848877","source":"stackoverflow","questionId":63848877,"title":"Generating migration file for a project using NestJS and TypeORM","tags":["typescript","nestjs","typeorm"],"text":"Title: Generating migration file for a project using NestJS and TypeORM\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to generate migration files for my entities, but whenever I run the command to create the entity, it creates an \"empty\" file, just the up and down methods are created.\n\nI have added this script in my package.json file: `\"typeorm\": \"node --require ts-node/register ./node_modules/typeorm/cli.js\"`.\n\nIn my app.module.ts, the connection is configured like this:\n\n```\nTypeOrmModule.forRoot({\n type: 'mysql',\n host: database().host,\n port: parseInt(database().port),\n username: database().username,\n password: database().password,\n database: database().schema,\n entities: [Question, QuestionOption],\n migrations: ['src/migration/*{.ts,.js}'],\n cli: {\n migrationsDir: 'src/migration'\n },\n synchronize: true,\n })\n```\n\nWhere `database()` it's a nestjs config file and get the values from an .env file.\n\nThe script I'm using to create the migration is: `npm run typeorm migration:create -- -n QuestionTables -d src/migrations` where need to specify the **-d**, otherwise the migration file is not created (even if it's specified in the cli of the forRoot method.\n\nDo I need to write manually the SQL to create the tables?\n\nWhat if I need to add a new column to an existing table, should I create a new migration file and write manually the SQL code to add that?\n\nAnother command that I tried to run was this one: `npm run typeorm migration:generate -- -n QuestionTables -d src/migrations` and here it gives me an error: \" Error: No connection options were found in any orm configuration files.\"\n\n========================================\n\nCode:\n```text\nTypeOrmModule.forRoot({\n type: 'mysql',\n host: database().host,\n port: parseInt(database().port),\n username: database().username,\n password: database().password,\n database: database().schema,\n entities: [Question, QuestionOption],\n migrations: ['src/migration/*{.ts,.js}'],\n cli: {\n migrationsDir: 'src/migration'\n },\n synchronize: true,\n })\n```\n\n```text\n\"typeorm\": \"node --require ts-node/register ./node_modules/typeorm/cli.js\"\n```\n\n```text\ndatabase()\n```\n\n```text\nnpm run typeorm migration:create -- -n QuestionTables -d src/migrations\n```\n\n```text\nnpm run typeorm migration:generate -- -n QuestionTables -d src/migrations\n```\n\n```text\n// ormconfig.ts\nexport const config: TypeOrmModuleOptions = {\n type: 'mysql',\n host: database().host,\n port: parseInt(database().port),\n username: database().username,\n password: database().password,\n database: database().schema,\n entities: [Question, QuestionOption], // maybe you should also consider chage it to something like: [__dirname + '/**/*.entity.ts', __dirname + '/src/**/*.entity.js']\n migrations: ['src/migration/*{.ts,.js}'],\n cli: {\n migrationsDir: 'src/migration'\n },\n synchronize: true,\n }\n```\n\n```text\n// ormconfig-migrations.ts\n\nimport {config} from './ormconfig';\n\nexport = config;\n```\n\n```text\nimport {config} from './ormconfig';\n\nTypeOrmModule.forRoot(config);\n```\n\n```text\n// package.json\n\n\"scripts\": {\n ...\n \"typeorm:cli\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli -f ./ormconfig-migrations.ts\",\n \"migration-generate\": \"npm run typeorm:cli -- migration:generate -n\"\n}\n```\n\n```text\nnpm run typeorm migration:create\n```\n\n```text\nnpm run typeorm migration:generate\n```\n\n```text\nforRoot\n```\n\n========================================\n\nComments:\n- Could you have your migrations generate tables in a schema other than public?\n- Alright, so now if I run the command npm run migration-generate Test, it says that No changes in database schema were found - cannot generate a migration. Do I need to create a migration and code manually the SQL inside of it to create the table?\n- Have you already created any tables? If so than clear the schema, drop the tables or drop the schema and recreate it, and then run migration-generate. This error says your database already have tables matching to the entities in your project.\n- Not yet, my database is empty.\n- You have any migrations in the migrations table?\n- I deleted everything from the database, there's only a database without any tables there. If I run the npm run migration-generate, I got a message saying that no changes in database schema were found. If I run migration-create, it creates a file in the migration folder, but with up and down method empty. Should it create a migration file with some SQL code or do I need to write that SQL code?\n- Also, I modified the ormconfig.ts with this: entities: [__dirname + '/src/event/entities/*.entity.ts', __dirname + '/src/event/entities/*.entity.js'] src/event/entities is where my Typescript classes are right now\n- Nevermind my friend, I found the error, my Entity class has a constructor that was causing some sort of cannot destructure property error. I fixed that and could run the generate command!\n- Won't `synchronize: true` defeat the whole purpose? Whenever you initiation this connection it will always sync entities with the DB schema, therefore there are no migrations to be generated.\n- It is not necessary to add the `npm run`\n- Correct. To generate a migration you have to know current state and expected state, find difference between those and create SQL queries to adjust current state to match expected state. `synchronize: true` will adjust current state automatically. Not sure exactly when, I imagine typeorm does its magic on connection. Meaning DB may already be in expected state and therefore do not require a migration.","metadata":{"transformedAt":"2026-08-18T18:33:44.688Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":142,"estimatedTokens":1417}}73{"id":"stack-57819937","source":"stackoverflow","questionId":57819937,"title":"TypeORM select all rows but limit 25","tags":["node.js","typeorm","typeorm-datamapper"],"text":"Title: TypeORM select all rows but limit 25\nTags: node.js, typeorm, typeorm-datamapper\nSource: Stack Overflow\n\nQuestion:\n`CandidateEntity`\n\n```\n@Entity({ name: 'users' })\nexport class CandidateEntity {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @OneToOne(() => CandidateEmployeeInfoEntity, employeeInfo => employeeInfo.candidate)\n public employeeInfo: CandidateEmployeeInfoEntity;\n}\n```\n\n`EmployeeInfoEntity`\n\n```\n@Entity({ name: 'candidates_employee_infos' })\nexport class CandidateEmployeeInfoEntity {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ type: 'bool', nullable: false })\n public relocation: boolean;\n\n @Column({ type: 'text', nullable: true })\n public softSkills: string;\n\n @OneToOne(() => CandidateEntity, candidate => candidate.employeeInfo)\n public candidate: CandidateEntity;\n\n @Column({ type: 'integer' })\n public candidateId: number;\n}\n```\n\nI create query to select first 25 rows from 104 rows in database\n\n```\nconst {\n perPage = 25,\n page = 1,\n} = params;\nconst skip = (perPage * page) - perPage;\n\nlet candidatesQuery = this.candidateRepository.createQueryBuilder('candidates');\ncandidatesQuery = candidatesQuery.leftJoinAndSelect(`candidates.employeeInfo`, 'employeeInfo'); // problem in this relation\ncandidatesQuery = candidatesQuery.skip(skip);\ncandidatesQuery = candidatesQuery.take(perPage);\n\nconst { entities, raw } = await candidatesQuery.getRawAndEntities();\nconst count = await candidatesQuery.getCount();\n\nconsole.log(entities.length) // 104 rows\nconsole.log(raw.length) // 104 rows\nconsole.log(count) // 104 rows\n```\n\nOutput sql query when typeorm return not correct results\n\nfirst query\n\n```\nSELECT DISTINCT \"distinctAlias\".\"candidates_id\" as \"ids_candidates_id\" FROM (SELECT \"candidates\".\"id\" AS \"candidates_id\", \"candidates\".\"uuid\" AS \"candidates_uuid\", \"candidates\".\"role\" AS \"candidates_role\", \"candidates\".\"first_name\" AS \"candidates_first_name\", \"candidates\".\"last_name\" AS \"candidates_last_name\", \"candidates\".\"email\" AS \"candidates_email\", \"candidates\".\"phone\" AS \"candidates_phone\", \"candidates\".\"phone_prefix\" AS \"candidates_phone_prefix\", \"candidates\".\"country_id\" AS \"candidates_country_id\", \"candidates\".\"city_id\" AS \"candidates_city_id\", \"candidates\".\"avatar\" AS \"candidates_avatar\", \"candidates\".\"confirmed_at\" AS \"candidates_confirmed_at\", \"candidates\".\"is_generated\" AS \"candidates_is_generated\", \"candidates\".\"created_at\" AS \"candidates_created_at\", \"candidates\".\"birthday\" AS \"candidates_birthday\", \"candidates\".\"type\" AS \"candidates_type\", \"employeeInfo\".\"id\" AS \"employeeInfo_id\", \"employeeInfo\".\"hourly_rate_from\" AS \"employeeInfo_hourly_rate_from\", \"employeeInfo\".\"hourly_rate_to\" AS \"employeeInfo_hourly_rate_to\", \"employeeInfo\".\"hourly_rate_currency\" AS \"employeeInfo_hourly_rate_currency\", \"employeeInfo\".\"salary_rate_from\" AS \"employeeInfo_salary_rate_from\", \"employeeInfo\".\"salary_rate_to\" AS \"employeeInfo_salary_rate_to\", \"employeeInfo\".\"salary_rate_currency\" AS \"employeeInfo_salary_rate_currency\", \"employeeInfo\".\"relocation\" AS \"employeeInfo_relocation\", \"employeeInfo\".\"soft_skills\" AS \"employeeInfo_soft_skills\", \"employeeInfo\".\"candidate_id\" AS \"employeeInfo_candidate_id\" FROM \"users\" \"candidates\" LEFT JOIN \"candidates_employee_infos\" \"employeeInfo\" ON \"employeeInfo\".\"candidate_id\"=\"candidates\".\"id\" WHERE \"candidates\".\"type\" IN ($1)) \"distinctAlias\" ORDER BY \"candidates_id\" ASC LIMIT 25\n```\n\nsecond query\n\n```\nSELECT \"candidates\".\"id\" AS \"candidates_id\", \"candidates\".\"uuid\" AS \"candidates_uuid\", \"candidates\".\"role\" AS \"candidates_role\", \"candidates\".\"first_name\" AS \"candidates_first_name\", \"candidates\".\"last_name\" AS \"candidates_last_name\", \"candidates\".\"email\" AS \"candidates_email\", \"candidates\".\"phone\" AS \"candidates_phone\", \"candidates\".\"phone_prefix\" AS \"candidates_phone_prefix\", \"candidates\".\"country_id\" AS \"candidates_country_id\", \"candidates\".\"city_id\" AS \"candidates_city_id\", \"candidates\".\"avatar\" AS \"candidates_avatar\", \"candidates\".\"confirmed_at\" AS \"candidates_confirmed_at\", \"candidates\".\"is_generated\" AS \"candidates_is_generated\", \"candidates\".\"created_at\" AS \"candidates_created_at\", \"candidates\".\"birthday\" AS \"candidates_birthday\", \"candidates\".\"type\" AS \"candidates_type\", \"employeeInfo\".\"id\" AS \"employeeInfo_id\", \"employeeInfo\".\"hourly_rate_from\" AS \"employeeInfo_hourly_rate_from\", \"employeeInfo\".\"hourly_rate_to\" AS \"employeeInfo_hourly_rate_to\", \"employeeInfo\".\"hourly_rate_currency\" AS \"employeeInfo_hourly_rate_currency\", \"employeeInfo\".\"salary_rate_from\" AS \"employeeInfo_salary_rate_from\", \"employeeInfo\".\"salary_rate_to\" AS \"employeeInfo_salary_rate_to\", \"employeeInfo\".\"salary_rate_currency\" AS \"employeeInfo_salary_rate_currency\", \"employeeInfo\".\"relocation\" AS \"employeeInfo_relocation\", \"employeeInfo\".\"soft_skills\" AS \"employeeInfo_soft_skills\", \"employeeInfo\".\"candidate_id\" AS \"employeeInfo_candidate_id\" FROM \"users\" \"candidates\" LEFT JOIN \"candidates_employee_infos\" \"employeeInfo\" ON \"employeeInfo\".\"candidate_id\"=\"candidates\".\"id\" WHERE \"candidates\".\"type\" IN ($1)\n```\n\nthird query\n\n```\nSELECT COUNT(DISTINCT(\"candidates\".\"id\")) as \"cnt\" FROM \"users\" \"candidates\" LEFT JOIN \"candidates_employee_infos\" \"employeeInfo\" ON \"employeeInfo\".\"candidate_id\"=\"candidates\".\"id\" WHERE \"candidates\".\"type\" IN ($1)\n```\n\nWhen I remove load relation `employeeInfo`.\n\nThis line\n`candidatesQuery = candidatesQuery.leftJoinAndSelect('candidates.employeeInfo', 'employeeInfo');`\n\nTypeORM return 25 rows\n\n```\nconsole.log(entities.length) // 25 rows\nconsole.log(raw.length) // 25 rows\nconsole.log(count) // 104 rows\n```\n\nWhy ? And how to fix this problem ?\n\n========================================\n\nTop Answer:\nYou can use take and skip with repository pattern:\n\n```\nconst {\n perPage = 25,\n page = 1,\n} = params;\nconst skip = (perPage * page) - perPage;\n\nconst candidates = await this.candidateRepository.find({\n relations: ['employeeInfo'],\n take: perPage,\n skip,\n});\n```\n\nalso for pagination purpose I recommend to use findAndCount\n\n```\nconst { perPage = 20, page = 1 } = params;\nconst skip = (perPage * page) - perPage;\n\nconst [data, total] = await this.repo.findAndCount({\n take,\n skip,\n // ...other options\n});\n```\n\n========================================\n\nCode:\n```text\n@Entity({ name: 'users' })\nexport class CandidateEntity {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @OneToOne(() => CandidateEmployeeInfoEntity, employeeInfo => employeeInfo.candidate)\n public employeeInfo: CandidateEmployeeInfoEntity;\n}\n```\n\n```text\n@Entity({ name: 'candidates_employee_infos' })\nexport class CandidateEmployeeInfoEntity {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ type: 'bool', nullable: false })\n public relocation: boolean;\n\n @Column({ type: 'text', nullable: true })\n public softSkills: string;\n\n @OneToOne(() => CandidateEntity, candidate => candidate.employeeInfo)\n public candidate: CandidateEntity;\n\n @Column({ type: 'integer' })\n public candidateId: number;\n}\n```\n\n```text\nconst {\n perPage = 25,\n page = 1,\n} = params;\nconst skip = (perPage * page) - perPage;\n\nlet candidatesQuery = this.candidateRepository.createQueryBuilder('candidates');\ncandidatesQuery = candidatesQuery.leftJoinAndSelect(`candidates.employeeInfo`, 'employeeInfo'); // problem in this relation\ncandidatesQuery = candidatesQuery.skip(skip);\ncandidatesQuery = candidatesQuery.take(perPage);\n\nconst { entities, raw } = await candidatesQuery.getRawAndEntities();\nconst count = await candidatesQuery.getCount();\n\nconsole.log(entities.length) // 104 rows\nconsole.log(raw.length) // 104 rows\nconsole.log(count) // 104 rows\n```\n\n```text\nSELECT DISTINCT \"distinctAlias\".\"candidates_id\" as \"ids_candidates_id\" FROM (SELECT \"candidates\".\"id\" AS \"candidates_id\", \"candidates\".\"uuid\" AS \"candidates_uuid\", \"candidates\".\"role\" AS \"candidates_role\", \"candidates\".\"first_name\" AS \"candidates_first_name\", \"candidates\".\"last_name\" AS \"candidates_last_name\", \"candidates\".\"email\" AS \"candidates_email\", \"candidates\".\"phone\" AS \"candidates_phone\", \"candidates\".\"phone_prefix\" AS \"candidates_phone_prefix\", \"candidates\".\"country_id\" AS \"candidates_country_id\", \"candidates\".\"city_id\" AS \"candidates_city_id\", \"candidates\".\"avatar\" AS \"candidates_avatar\", \"candidates\".\"confirmed_at\" AS \"candidates_confirmed_at\", \"candidates\".\"is_generated\" AS \"candidates_is_generated\", \"candidates\".\"created_at\" AS \"candidates_created_at\", \"candidates\".\"birthday\" AS \"candidates_birthday\", \"candidates\".\"type\" AS \"candidates_type\", \"employeeInfo\".\"id\" AS \"employeeInfo_id\", \"employeeInfo\".\"hourly_rate_from\" AS \"employeeInfo_hourly_rate_from\", \"employeeInfo\".\"hourly_rate_to\" AS \"employeeInfo_hourly_rate_to\", \"employeeInfo\".\"hourly_rate_currency\" AS \"employeeInfo_hourly_rate_currency\", \"employeeInfo\".\"salary_rate_from\" AS \"employeeInfo_salary_rate_from\", \"employeeInfo\".\"salary_rate_to\" AS \"employeeInfo_salary_rate_to\", \"employeeInfo\".\"salary_rate_currency\" AS \"employeeInfo_salary_rate_currency\", \"employeeInfo\".\"relocation\" AS \"employeeInfo_relocation\", \"employeeInfo\".\"soft_skills\" AS \"employeeInfo_soft_skills\", \"employeeInfo\".\"candidate_id\" AS \"employeeInfo_candidate_id\" FROM \"users\" \"candidates\" LEFT JOIN \"candidates_employee_infos\" \"employeeInfo\" ON \"employeeInfo\".\"candidate_id\"=\"candidates\".\"id\" WHERE \"candidates\".\"type\" IN ($1)) \"distinctAlias\" ORDER BY \"candidates_id\" ASC LIMIT 25\n```\n\n```text\nSELECT \"candidates\".\"id\" AS \"candidates_id\", \"candidates\".\"uuid\" AS \"candidates_uuid\", \"candidates\".\"role\" AS \"candidates_role\", \"candidates\".\"first_name\" AS \"candidates_first_name\", \"candidates\".\"last_name\" AS \"candidates_last_name\", \"candidates\".\"email\" AS \"candidates_email\", \"candidates\".\"phone\" AS \"candidates_phone\", \"candidates\".\"phone_prefix\" AS \"candidates_phone_prefix\", \"candidates\".\"country_id\" AS \"candidates_country_id\", \"candidates\".\"city_id\" AS \"candidates_city_id\", \"candidates\".\"avatar\" AS \"candidates_avatar\", \"candidates\".\"confirmed_at\" AS \"candidates_confirmed_at\", \"candidates\".\"is_generated\" AS \"candidates_is_generated\", \"candidates\".\"created_at\" AS \"candidates_created_at\", \"candidates\".\"birthday\" AS \"candidates_birthday\", \"candidates\".\"type\" AS \"candidates_type\", \"employeeInfo\".\"id\" AS \"employeeInfo_id\", \"employeeInfo\".\"hourly_rate_from\" AS \"employeeInfo_hourly_rate_from\", \"employeeInfo\".\"hourly_rate_to\" AS \"employeeInfo_hourly_rate_to\", \"employeeInfo\".\"hourly_rate_currency\" AS \"employeeInfo_hourly_rate_currency\", \"employeeInfo\".\"salary_rate_from\" AS \"employeeInfo_salary_rate_from\", \"employeeInfo\".\"salary_rate_to\" AS \"employeeInfo_salary_rate_to\", \"employeeInfo\".\"salary_rate_currency\" AS \"employeeInfo_salary_rate_currency\", \"employeeInfo\".\"relocation\" AS \"employeeInfo_relocation\", \"employeeInfo\".\"soft_skills\" AS \"employeeInfo_soft_skills\", \"employeeInfo\".\"candidate_id\" AS \"employeeInfo_candidate_id\" FROM \"users\" \"candidates\" LEFT JOIN \"candidates_employee_infos\" \"employeeInfo\" ON \"employeeInfo\".\"candidate_id\"=\"candidates\".\"id\" WHERE \"candidates\".\"type\" IN ($1)\n```\n\n```text\nSELECT COUNT(DISTINCT(\"candidates\".\"id\")) as \"cnt\" FROM \"users\" \"candidates\" LEFT JOIN \"candidates_employee_infos\" \"employeeInfo\" ON \"employeeInfo\".\"candidate_id\"=\"candidates\".\"id\" WHERE \"candidates\".\"type\" IN ($1)\n```\n\n```text\nconsole.log(entities.length) // 25 rows\nconsole.log(raw.length) // 25 rows\nconsole.log(count) // 104 rows\n```\n\n```text\nCandidateEntity\n```\n\n```text\nEmployeeInfoEntity\n```\n\n```text\nemployeeInfo\n```\n\n```text\ncandidatesQuery = candidatesQuery.leftJoinAndSelect('candidates.employeeInfo', 'employeeInfo');\n```\n\n```text\n.offset\n```\n\n```text\n.limit\n```\n\n```text\n.skip\n```\n\n```text\n.take\n```\n\n```text\n.offset\n```\n\n```text\n.limit\n```\n\n```text\nconst {\n perPage = 25,\n page = 1,\n} = params;\nconst skip = (perPage * page) - perPage;\n\nconst candidates = await this.candidateRepository.find({\n relations: ['employeeInfo'],\n take: perPage,\n skip,\n});\n```\n\n```text\nconst { perPage = 20, page = 1 } = params;\nconst skip = (perPage * page) - perPage;\n\nconst [data, total] = await this.repo.findAndCount({\n take,\n skip,\n // ...other options\n});\n```\n\n========================================\n\nComments:\n- What I do when I have issues with typeorm is getting the sql query and see what it does exactly. So could you provide the getSql?\n- @SoftwarePerson I updated question, added sql\n- using `offset` instead of `skip` worked for me while using query builder\n- used `findAndCount` its working!!","metadata":{"transformedAt":"2026-08-18T18:33:44.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":273,"estimatedTokens":3099}}74{"id":"stack-57647558","source":"stackoverflow","questionId":57647558,"title":"TypeORM, Query entity based on relation property","tags":["typeorm"],"text":"Title: TypeORM, Query entity based on relation property\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI would like to query an entity based on a related property, for instance:\n\n```\nconst x = await repo.findOne({ name: 'foo', parent: { name: 'foo' }});\n```\n\nbut it aways returns a null when I query by its related `parent`\n\nI alread added : `relations: ['parent']`, already set relation as `{eager:true}`\n\nWhen I Query by `parent: {id: X}` it works. but I must query by its name.\n\nWhat should I do to get this query working in TypeORM\n\nIt would be similar to:\n\nselect * from entity inner join parent ... where entity.name = 'foo' and parent.name = 'foo'\n\n========================================\n\nTop Answer:\nThere's a workaround for filtering based on relation fields for `findOne()`/`find()` methods that I've discovered recently. The problem with filtering related table fields only exists for `ObjectLiteral`-style `where`, while string conditions work perfectly. \n\nAssume that we have two entities – `User` and `Role`, user belongs to one role, role has many users:\n\n```\n@Entity()\nexport class User {\n name: string;\n\n @ManyToOne(() => Role, role => role.users)\n role: Role;\n}\n\n@Entity()\nexport class Role {\n @OneToMany(() => User, user => user.role)\n users: User[];\n}\n```\n\nNow we can call `findOne()`/`find()` methods of `EntityManager` or repository:\n\n```\nroleRepository.find({\n join: { alias: 'roles', innerJoin: { users: 'roles.users' } },\n where: qb => {\n qb.where({ // Filter Role fields\n a: 1,\n b: 2\n }).andWhere('users.name = :userName', { userName: 'John Doe' }); // Filter related field\n }\n});\n```\n\nYou can omit the `join` part if you've marked your relation as an eager one.\n\n========================================\n\nCode:\n```text\nconst x = await repo.findOne({ name: 'foo', parent: { name: 'foo' }});\n```\n\n```text\nparent\n```\n\n```text\nrelations: ['parent']\n```\n\n```text\n{eager:true}\n```\n\n```text\nparent: {id: X}\n```\n\n```js\nconst x = await repo.createQueryBuilder(\"foo\")\n .innerJoinAndSelect(\"foo.parent\", \"parent\")\n .where(\"parent.name = :name\", { name })\n .getOne()\n```\n\n```text\nfind\n```\n\n```text\nfindOne\n```\n\n```text\nQueryBuilder\n```\n\n```text\ntypeorm >= 0.3\n```\n\n```js\n@Entity()\nexport class User {\n name: string;\n\n @ManyToOne(() => Role, role => role.users)\n role: Role;\n}\n\n@Entity()\nexport class Role {\n @OneToMany(() => User, user => user.role)\n users: User[];\n}\n```\n\n```js\nroleRepository.find({\n join: { alias: 'roles', innerJoin: { users: 'roles.users' } },\n where: qb => {\n qb.where({ // Filter Role fields\n a: 1,\n b: 2\n }).andWhere('users.name = :userName', { userName: 'John Doe' }); // Filter related field\n }\n});\n```\n\n```text\nfindOne()\n```\n\n```text\nfind()\n```\n\n```text\nObjectLiteral\n```\n\n```text\nwhere\n```\n\n```text\nUser\n```\n\n```text\nRole\n```\n\n```text\nfindOne()\n```\n\n```text\nfind()\n```\n\n```text\nEntityManager\n```\n\n```text\njoin\n```\n\n```js\nconst searchTerm = 'foo'\nconst parents = await parentRepo.find({name:searchTerm})\nconst parentIdList = parents.map(parent=>parent.id)\nconst x = await repo.find({ where:[{name: searchTerm}, {parent: In(parentIdList)}]});\n```\n\n```text\nid\n```\n\n```text\ntypeorm^0.3 above\n```\n\n```text\nconst x = await repo.createQueryBuilder(\"foo\")\n .innerJoinAndSelect(\"foo.parent\", \"parent\", \"parent.name = :name\", { name })\n .getOne()\n```\n\n```text\n.where\n```\n\n```text\nconst data = await this.repo.findOne({\n where: {\n parent: {\n name: 'some name',\n // id: Not(IsNull()), // parent (not)exist - this can helpful for someone\n },\n },\n // relations: ['parent'], // if you need this relation\n});\n```\n\n========================================\n\nComments:\n- It was already implemented I think. See github.com/typeorm/typeorm/issues/2707 The accepted answer should be updated.\n- Does anyone know how to say the `qb` property type to fix the type missing? Thanks in advance!\n- @btd1337 `WhereExpression` is what you need\n- `join` is now deprecated.","metadata":{"transformedAt":"2026-08-18T18:33:44.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":220,"estimatedTokens":993}}75{"id":"stack-53790994","source":"stackoverflow","questionId":53790994,"title":"Bulk update via raw query in TypeORM","tags":["node.js","typeorm","bulkupdate"],"text":"Title: Bulk update via raw query in TypeORM\nTags: node.js, typeorm, bulkupdate\nSource: Stack Overflow\n\nQuestion:\nHow can I do bulk update via raw query in TypeORM?\n\nFor example we have model *User* with property *name*\n\nHow can I change names of few users in one transaction? \n\ntypeorm version: **0.2.7**\n\ndatabase: **postgress**\n\n========================================\n\nTop Answer:\nAlso you can update several rows with repository api this way:\n\n```\nawait repository.update(\n {\n id: In([1,2,3,4,5]),\n },\n { selected: true },\n);\n```\n\n========================================\n\nCode:\n```js\nimport {getConnection, In} from \"typeorm\";\nconst userIds = [1,2,3];\n\nawait getConnection()\n .createQueryBuilder()\n .update(User)\n .set({ isaSeniorCitizen: true })\n .where({ id: In(userIds) })\n .execute();\n```\n\n```text\nimport {getConnection} from \"typeorm\";\n\nawait getConnection()\n .createQueryBuilder()\n .update(User)\n .set({ firstName: \"Timber\", lastName: \"Saw\" })\n .where(\"id = :id\", { id: 1 })\n .execute();\n```\n\n```text\ngetRepository(User).query('UPDATE `users` SET firstName = 'Timber', lastName = 'Saw' WHERE id = 1')\n```\n\n```text\nquery()\n```\n\n```text\n.where({ id: In(userIds) })\n```\n\n```text\nWHERE id IN (${userIds.join(',')})\n```\n\n```text\nimport {getConnection } from \"typeorm\";\nconst userIds = [1,2,3];\n\nawait getConnection()\n .createQueryBuilder()\n .update(User)\n .set({ isaSeniorCitizen: true })\n .whereInIds(userIds)\n .execute();\n```\n\n```text\nawait repository.update(\n {\n id: In([1,2,3,4,5]),\n },\n { selected: true },\n);\n```\n\n```js\n@Controller(\"/test\")\nexport class TestController {\n\n constructor(\n @InjectRepository(Users) private UsersRepository: Repository<Users>\n ) { }\n\n @Get()\n async test() {\n\n await this.UsersRepository\n .createQueryBuilder(\"updateUsers\")\n .update(Users)\n .set({ name: 'michael scott' })\n .whereInIds([1, 2, 3])\n .execute();\n\n }\n\n}\n```\n\n```text\ngetConnection()\n```\n\n```text\nawait this.operationRepository.manager.transaction(async (transaction) => {\n const operation = await transaction.save(Operation, {\n description: dto.description,\n type: dto.type,\n assigneeUserId: assigneeUserId,\n });\n\n const operationProducts = dto.products.map((p) => ({\n ...p,\n operationId: operation.id,\n }));\n\n const updateProductOperationFn = async () => {\n await transaction\n .createQueryBuilder()\n .insert()\n .into(OperationProduct)\n .values(operationProducts)\n .execute();\n };\n const updateProductsFn = async () => {\n await Promise.all(\n productsWithNewStock.map((p) =>\n transaction\n .createQueryBuilder()\n .update(Product)\n .set({ currentStock: p.currentStock })\n .where('id = :id', { id: p.id })\n .execute(),\n ),\n );\n };\n\n await Promise.all([updateProductOperationFn(), updateProductsFn()]);\n});\n```\n\n========================================\n\nComments:\n- I am not sure who does this query bulk updating?\n- sorry my question was \"how\" does this query bulk updating it?\n- Don't build query strings in TS! This is how you get SQL injection.\n- What difference between this and first answer?\n- It lets you update against multiple records: `.where({ id: In(userIds) })`. Since your question was regarding `how to bulk update`\n- But in this scenario subscribers are not working, any solutions for that? @aitchkhan","metadata":{"transformedAt":"2026-08-18T18:33:44.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":166,"estimatedTokens":861}}76{"id":"stack-66909895","source":"stackoverflow","questionId":66909895,"title":"TypeORM: QueryFailedError: relation does not exist","tags":["node.js","database","postgresql","nestjs","typeorm"],"text":"Title: TypeORM: QueryFailedError: relation does not exist\nTags: node.js, database, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI need a little help with migration. I'm trying to seed DB using migration. But I get an error \"QueryFailedError: relation \"account\" does not exist\". I think it's just typical newbie mistake. So please check my code:\n\n**account.entity.ts**\n\n```\nimport { BeforeInsert, Column, Entity, OneToMany } from 'typeorm';\nimport { AbstractEntity } from '../../common/abstract.entity';\nimport { SourceEntity } from '../source/source.entity';\nimport { UtilsService } from '../../shared/services/utils.service';\n\n@Entity({ name: 'account' })\nexport class AccountEntity extends AbstractEntity {\n @Column({ unique: true })\n username: string;\n\n @Column({ nullable: true })\n password: string;\n\n @OneToMany(() => SourceEntity, (source) => source.account, {\n cascade: true,\n })\n sources: SourceEntity[];\n\n @BeforeInsert()\n async setPassword() {\n this.password = UtilsService.generateHash(this.password);\n }\n}\n```\n\n**seed-data.migration.ts**\n\n```\nimport { getCustomRepository, MigrationInterface, QueryRunner } from 'typeorm';\nimport { AccountRepository } from '../modules/account/account.repository';\nimport { SourceRepository } from '../modules/source/source.repository';\n\ntype DataType = {\n username: string;\n password: string;\n sources: { username: string }[];\n};\n\nexport class SeedData1617243952346 implements MigrationInterface {\n private data: DataType[] = [\n {\n username: 'test',\n password: 'password',\n sources: [\n { username: 'some_test' },\n { username: 'okey_test' },\n { username: 'super_test' },\n ],\n },\n {\n username: 'account',\n password: 'password',\n sources: [\n { username: 'some_account' },\n { username: 'okey_account' },\n { username: 'super_account' },\n ],\n },\n ];\n\n public async up(): Promise {\n await Promise.all(\n this.data.map(async (item) => {\n const accountRepository = getCustomRepository(AccountRepository);\n const accountEntity = accountRepository.create();\n accountEntity.username = item.username;\n accountEntity.password = item.password;\n\n const sourceRepository = getCustomRepository(SourceRepository);\n const sources = [];\n\n await Promise.all(\n item.sources.map(async (sourceItem) => {\n const sourceEntity = sourceRepository.create();\n sourceEntity.username = sourceItem.username;\n\n sources.push(sourceEntity);\n }),\n );\n\n accountEntity.sources = sources;\n const account = await accountRepository.save(accountEntity);\n console.log('Account created:', account.id);\n }),\n );\n }\n\n public async down(): Promise {\n await Promise.all(\n this.data.map(async (item) => {\n const sourceRepository = getCustomRepository(SourceRepository);\n const accountRepository = getCustomRepository(AccountRepository);\n\n const account = await accountRepository.findOne({\n where: { username: item.username },\n });\n if (account) {\n await Promise.all(\n item.sources.map(async (src) => {\n const source = await sourceRepository.findOne({\n where: { username: src.username },\n });\n if (source) {\n await sourceRepository.delete(source);\n }\n }),\n );\n\n await accountRepository.delete(account);\n }\n }),\n );\n }\n}\n```\n\n**source.entity.ts**\n\n```\nimport { Column, Entity, ManyToOne } from 'typeorm';\nimport { AbstractEntity } from '../../common/abstract.entity';\nimport { AccountEntity } from '../account/account.entity';\n\n@Entity({ name: 'source' })\nexport class SourceEntity extends AbstractEntity {\n @Column({ unique: true })\n username: string;\n\n @Column({ default: true })\n overrideCaption: boolean;\n\n @ManyToOne(() => AccountEntity, (account) => account.sources)\n account: AccountEntity;\n}\n```\n\n**Error:**\n\n```\nError during migration run:\nQueryFailedError: relation \"account\" does not exist\n at new QueryFailedError (/home/wiha/dev/own/instahub/src/error/QueryFailedError.ts:9:9)\n at PostgresQueryRunner. (/home/wiha/dev/own/instahub/src/driver/postgres/PostgresQueryRunner.ts:228:19)\n at step (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:143:27)\n at Object.throw (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:124:57)\n at rejected (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:115:69)\n at processTicksAndRejections (internal/process/task_queues.js:97:5) {\n length: 106,\n severity: 'ERROR',\n code: '42P01',\n detail: undefined,\n hint: undefined,\n position: '13',\n internalPosition: undefined,\n internalQuery: undefined,\n where: undefined,\n schema: undefined,\n table: undefined,\n column: undefined,\n dataType: undefined,\n constraint: undefined,\n file: 'parse_relation.c',\n line: '1191',\n routine: 'parserOpenTable',\n query: 'INSERT INTO \"account\"(\"id\", \"created_at\", \"updated_at\", \"username\", \"password\") VALUES (DEFAULT, DEFAULT, DEFAULT, $1, $2) RETURNING \"id\", \"created_at\", \"updated_at\"',\n parameters: [\n 'test',\n '$2b$10$iB6yb3D8e6iGmKoVAJ7eYeYfoItclw5lcVXqauPf9VH94DlDrbuSa'\n ]\n}\n```\n\nTables are created in another migration\n\nDB: PostgreSQL 12.6\n\nNode: 14.0.0\n\nTypeORM: 0.2.32\n\n@nestjs/typeorm: 7.1.5\n\n========================================\n\nTop Answer:\nJust in case I help someone, my issue was not specifying the schema in the Entity\n\n```\n@Entity({ name: 'account', schema: 'companydbo' })\n```\n\n========================================\n\nCode:\n```ts\nimport { BeforeInsert, Column, Entity, OneToMany } from 'typeorm';\nimport { AbstractEntity } from '../../common/abstract.entity';\nimport { SourceEntity } from '../source/source.entity';\nimport { UtilsService } from '../../shared/services/utils.service';\n\n@Entity({ name: 'account' })\nexport class AccountEntity extends AbstractEntity {\n @Column({ unique: true })\n username: string;\n\n @Column({ nullable: true })\n password: string;\n\n @OneToMany(() => SourceEntity, (source) => source.account, {\n cascade: true,\n })\n sources: SourceEntity[];\n\n @BeforeInsert()\n async setPassword() {\n this.password = UtilsService.generateHash(this.password);\n }\n}\n```\n\n```ts\nimport { getCustomRepository, MigrationInterface, QueryRunner } from 'typeorm';\nimport { AccountRepository } from '../modules/account/account.repository';\nimport { SourceRepository } from '../modules/source/source.repository';\n\ntype DataType = {\n username: string;\n password: string;\n sources: { username: string }[];\n};\n\nexport class SeedData1617243952346 implements MigrationInterface {\n private data: DataType[] = [\n {\n username: 'test',\n password: 'password',\n sources: [\n { username: 'some_test' },\n { username: 'okey_test' },\n { username: 'super_test' },\n ],\n },\n {\n username: 'account',\n password: 'password',\n sources: [\n { username: 'some_account' },\n { username: 'okey_account' },\n { username: 'super_account' },\n ],\n },\n ];\n\n public async up(): Promise<void> {\n await Promise.all(\n this.data.map(async (item) => {\n const accountRepository = getCustomRepository(AccountRepository);\n const accountEntity = accountRepository.create();\n accountEntity.username = item.username;\n accountEntity.password = item.password;\n\n const sourceRepository = getCustomRepository(SourceRepository);\n const sources = [];\n\n await Promise.all(\n item.sources.map(async (sourceItem) => {\n const sourceEntity = sourceRepository.create();\n sourceEntity.username = sourceItem.username;\n\n sources.push(sourceEntity);\n }),\n );\n\n accountEntity.sources = sources;\n const account = await accountRepository.save(accountEntity);\n console.log('Account created:', account.id);\n }),\n );\n }\n\n public async down(): Promise<void> {\n await Promise.all(\n this.data.map(async (item) => {\n const sourceRepository = getCustomRepository(SourceRepository);\n const accountRepository = getCustomRepository(AccountRepository);\n\n const account = await accountRepository.findOne({\n where: { username: item.username },\n });\n if (account) {\n await Promise.all(\n item.sources.map(async (src) => {\n const source = await sourceRepository.findOne({\n where: { username: src.username },\n });\n if (source) {\n await sourceRepository.delete(source);\n }\n }),\n );\n\n await accountRepository.delete(account);\n }\n }),\n );\n }\n}\n```\n\n```ts\nimport { Column, Entity, ManyToOne } from 'typeorm';\nimport { AbstractEntity } from '../../common/abstract.entity';\nimport { AccountEntity } from '../account/account.entity';\n\n@Entity({ name: 'source' })\nexport class SourceEntity extends AbstractEntity {\n @Column({ unique: true })\n username: string;\n\n @Column({ default: true })\n overrideCaption: boolean;\n\n @ManyToOne(() => AccountEntity, (account) => account.sources)\n account: AccountEntity;\n}\n```\n\n```sh\nError during migration run:\nQueryFailedError: relation \"account\" does not exist\n at new QueryFailedError (/home/wiha/dev/own/instahub/src/error/QueryFailedError.ts:9:9)\n at PostgresQueryRunner.<anonymous> (/home/wiha/dev/own/instahub/src/driver/postgres/PostgresQueryRunner.ts:228:19)\n at step (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:143:27)\n at Object.throw (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:124:57)\n at rejected (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:115:69)\n at processTicksAndRejections (internal/process/task_queues.js:97:5) {\n length: 106,\n severity: 'ERROR',\n code: '42P01',\n detail: undefined,\n hint: undefined,\n position: '13',\n internalPosition: undefined,\n internalQuery: undefined,\n where: undefined,\n schema: undefined,\n table: undefined,\n column: undefined,\n dataType: undefined,\n constraint: undefined,\n file: 'parse_relation.c',\n line: '1191',\n routine: 'parserOpenTable',\n query: 'INSERT INTO \"account\"(\"id\", \"created_at\", \"updated_at\", \"username\", \"password\") VALUES (DEFAULT, DEFAULT, DEFAULT, $1, $2) RETURNING \"id\", \"created_at\", \"updated_at\"',\n parameters: [\n 'test',\n '$2b$10$iB6yb3D8e6iGmKoVAJ7eYeYfoItclw5lcVXqauPf9VH94DlDrbuSa'\n ]\n}\n```\n\n```text\ncreateConnection({\n type: \"mysql\",\n host: \"localhost\",\n port: 3306,\n username: \"root\",\n password: \"admin\",\n database: \"test\",\n entities: [\n Photo\n ],\n\n// ---\n synchronize: true,\n// ---\n logging: false\n```\n\n```text\nsynchronize: true,\n```\n\n```text\nschema:sync\n```\n\n```text\n// In a prev migration the countries table was created\n// Then in a new migration\n\nexport class SeedCountriesTable1616610473154 implements MigrationInterface {\n public async up(queryRunner: QueryRunner): Promise<void> {\n // Trying to commit last transcaction\n await queryRunner.commitTransaction().then(async () => {\n // Seeding database\n // Then try to start another one\n await queryRunner.startTransaction().then(async () => {\n await getRepository('countries').save(countries);\n });\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n public async down(): Promise<void> {}\n}\n```\n\n```text\nprivate static async getProducts(): Promise<Product[]> {\n return await getRepository(Product)\n .createQueryBuilder('product')\n .where('product.source = \"noobie\"') // <---- DOUBLE QUOTES = BAD!!!\n .getMany();\n}\n```\n\n```text\nprivate static async getProducts(): Promise<Product[]> {\n return await getRepository(Product)\n .createQueryBuilder('product')\n .where(\"product.source = 'noobie'\") // <---- SINGLE QUOTES!!!\n .getMany();\n}\n```\n\n```text\n@Entity({ name: 'account', schema: 'companydbo' })\n```\n\n```text\nmigrationsTransactionMode: 'each'\n```\n\n```none\n\"test:e2e\": \"cross-env NODE_ENV=test jest --config ./test/jest-e2e.json --runInBand\"\n```\n\n```text\n--runInBand\n```\n\n```text\njest\n```\n\n```text\ntest:e2e\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- how do you initialize your db?\n- @shusson via TypeOrmModule.forRootAsync\n- can you show more code? TypeORM can create the schema for you, but it depends how you initialize the TypeORM connection.\n- @shusson check this gist\n- you need to double check your entities list includes the account entity. gist.github.com/qWici/…\n- @shusson I have next struct - screenshot on Imgur. So I think it's works fine.\n- Mark this answer as correct. But what I actually done: 1. Remove migration for creating tables for entities 2. Set **synchronize** to true 3. Recreate DB 4. Run typeorm schema:sync 5. Run migration\n- This is actually the most correct answer it tells you exactly when the issue happens and unless your project is a demo project I will not recommend turning on the synchronise:true option.\n- The documentation says: **Typically, it is unsafe to use synchronize: true for schema synchronization on production once you get data in your database. Here is where migrations come to help.** Reference: typeorm.io/docs/advanced-topics/migrations\n- Great job, this is exactly what we needed !\n- +1 to this because its really not clear why it works the first time (it assumes the 'public' schema in postgres when creating the table, which is what i would expect), but not the second time (on a rerun of sync when the table already exists). fixed my problem, don't know why dont care why, thank you.","metadata":{"transformedAt":"2026-08-18T18:33:44.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":478,"estimatedTokens":3342}}77{"id":"stack-58240290","source":"stackoverflow","questionId":58240290,"title":"TypeORM: Many-to-many custom column names","tags":["typescript","typeorm"],"text":"Title: TypeORM: Many-to-many custom column names\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nGiven the following two **TypeORM** entities that have a **@ManyToMany** relationship:\n\n```\n@Entity({ name: 'products' })\nexport class ProductEntity {\n @PrimaryColumn()\n id: number;\n\n @Column()\n name: string;\n\n @ManyToMany(type => CategoryEntity, { eager: true })\n @JoinTable({ name: 'products_categories' })\n categories: CategoryEntity[];\n}\n```\n\n```\n@Entity({ name: 'categories' })\nexport class CategoryEntity {\n @PrimaryColumn({ length: 40 })\n code: string;\n}\n```\n\nAs a result I get created a table called `\"products_categories\"` with the following column names:\n\n- `productsId`\n\n- `categoriesCode`\n\nIs there a way of giving these two columns custom names? I would like to rename them as follows:\n\n- `productsId` -> `productId`\n\n- `categoriesCode` -> `categoryCode`\n\n========================================\n\nCode:\n```js\n@Entity({ name: 'products' })\nexport class ProductEntity {\n @PrimaryColumn()\n id: number;\n\n @Column()\n name: string;\n\n @ManyToMany(type => CategoryEntity, { eager: true })\n @JoinTable({ name: 'products_categories' })\n categories: CategoryEntity[];\n}\n```\n\n```js\n@Entity({ name: 'categories' })\nexport class CategoryEntity {\n @PrimaryColumn({ length: 40 })\n code: string;\n}\n```\n\n```text\n\"products_categories\"\n```\n\n```text\nproductsId\n```\n\n```text\ncategoriesCode\n```\n\n```text\nproductsId\n```\n\n```text\nproductId\n```\n\n```text\ncategoriesCode\n```\n\n```text\ncategoryCode\n```\n\n```text\n@ManyToMany(type => CategoryEntity, { eager: true })\n@JoinTable({\n name: \"products_categories\",\n joinColumn: {\n name: \"product\",\n referencedColumnName: \"id\"\n },\n inverseJoinColumn: {\n name: \"category\",\n referencedColumnName: \"id\"\n }\n})\ncategories: CategoryEntity[];\n```\n\n```text\n@JoinTable\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.688Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":115,"estimatedTokens":463}}78{"id":"stack-67197276","source":"stackoverflow","questionId":67197276,"title":"How do I make combination of 3 columns in typeorm, postgres unique?","tags":["typescript","postgresql","nestjs","typeorm"],"text":"Title: How do I make combination of 3 columns in typeorm, postgres unique?\nTags: typescript, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHow can I achieve that there aren't 2 same records in db with values of these 3 columns combined being the same?\n\n```\n@Column()\n sector: string;\n\n @Column()\n row: string;\n\n @Column()\n number: string;\n```\n\n========================================\n\nTop Answer:\nYou can annotate the entity with an @Index as described in the documentation about \"Indices with multiple columns\":\n\n```\n@Index([\"sector\", \"row\", \"number\"], { unique: true })\n```\n\n========================================\n\nCode:\n```text\n@Column()\n sector: string;\n\n @Column()\n row: string;\n\n @Column()\n number: string;\n```\n\n```js\n@Unique([\"sector\", \"row\", \"number\"])\n```\n\n```text\n@Index\n```\n\n```text\n@Index([\"sector\", \"row\", \"number\"], { unique: true })\n```\n\n========================================\n\nComments:\n- Most DBMS will create an index structure for unique-constraints as well. Somehow, they need to determine if a value already exists, and this can only be done efficiently if some sort of index exists (otherwise it would require scanning the entire table). For PostgreSQL also see this answer: stackoverflow.com/questions/23542794/….\n- Wow. Didn't know about that. Thank you!\n- Sure thing. In general however, your answer is absolutely correct. Postgres using an index either way is an implementation detail. One should always use the semantically better suitable way, and in this case I agree with you that this would be a constraint, not an index.\n- is the the same as PRIMARY KEY('sector', 'row', 'number')","metadata":{"transformedAt":"2026-08-18T18:33:44.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":60,"estimatedTokens":412}}79{"id":"stack-62450501","source":"stackoverflow","questionId":62450501,"title":"NestJS controller not mapped","tags":["javascript","docker","nestjs","typeorm"],"text":"Title: NestJS controller not mapped\nTags: javascript, docker, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nSo I have an API that will be deployed in a docker container. This API has the `authentications` controller, simple and not something special.\n\nWhen I start up the API in development mode on my local machine, the auth controller will be found and everything is working fine. Same for building and running it on my local machine. But when I'll dockerize the project and run it on a virtual machine, then I'll can't access the auth controller. Every other controller is working finde, but the auth controller doesn't exist.\n\nLooking into the docker logs, no auth controller will be mapped. Both local and builded docker images should contain the same project files.\n\nauth controller:\n\n```\nimport {\n Controller,\n Post,\n Delete,\n UseGuards,\n Request,\n Body,\n} from '@nestjs/common';\n\nimport { AuthenticationsService } from './authentications.service';\nimport { JwtAuthGuard } from '../shared/guards/jwtAuth.guard';\nimport { SignInDTO } from './dtos/addGraphNodeToGraphByGraphId.dto';\n\n@Controller('authentications')\nexport class AuthenticationsController {\n constructor(\n private readonly authenticationsService: AuthenticationsService,\n ) {}\n\n @Post()\n public signIn(@Body() { username, password }: SignInDTO): Promise {\n return this.authenticationsService.signIn(username, password);\n }\n\n @Delete()\n @UseGuards(JwtAuthGuard)\n public signOut(@Request() request): Promise {\n return this.authenticationsService.signOut(\n request.encodedToken,\n request.user.tokenExpirationSinceEpochInMilliseconds,\n );\n }\n}\n```\n\nError:\n\n```\n{\n \"statusCode\": 404,\n \"message\": \"Not Found\",\n \"error\": \"Cannot POST /authentications\"\n}\n```\n\nWhat could cause that the authentications controller will not be mapped?\n\n========================================\n\nTop Answer:\nIf you have already tried everything else and nothing worked, try deleting the `dist` folder. That's what worked for me.\n\n========================================\n\nCode:\n```text\nimport {\n Controller,\n Post,\n Delete,\n UseGuards,\n Request,\n Body,\n} from '@nestjs/common';\n\nimport { AuthenticationsService } from './authentications.service';\nimport { JwtAuthGuard } from '../shared/guards/jwtAuth.guard';\nimport { SignInDTO } from './dtos/addGraphNodeToGraphByGraphId.dto';\n\n@Controller('authentications')\nexport class AuthenticationsController {\n constructor(\n private readonly authenticationsService: AuthenticationsService,\n ) {}\n\n @Post()\n public signIn(@Body() { username, password }: SignInDTO): Promise<string> {\n return this.authenticationsService.signIn(username, password);\n }\n\n @Delete()\n @UseGuards(JwtAuthGuard)\n public signOut(@Request() request): Promise<void> {\n return this.authenticationsService.signOut(\n request.encodedToken,\n request.user.tokenExpirationSinceEpochInMilliseconds,\n );\n }\n}\n```\n\n```text\n{\n \"statusCode\": 404,\n \"message\": \"Not Found\",\n \"error\": \"Cannot POST /authentications\"\n}\n```\n\n```text\nauthentications\n```\n\n```text\nnest update -f\n```\n\n```js\n@Module({\n controllers: [AuthenticationController],\n})\nexport class AppModule {}\n```\n\n```text\ndist\n```\n\n```text\nmaster\n```\n\n```text\ndev\n```\n\n```text\npino\n```\n\n```text\ndebug\n```\n\n========================================\n\nComments:\n- If you modify an existing controller, does it repercutes the modification in the docker container ?\n- Put code of module which requires this controller into the question. Maybe there is something here. Also which operation systems do you have locally and in docker?\n- Yes, I guess if I wouldn't have done that it would also not work on my local machine\n- I already found a solution: stackoverflow.com/a/62591471/8408576\n- The selected answer didn't work for me so, I shared mine just in case anybody else is facing the same thing.\n- turnout my build was not compiling so intellij was just using the last working version :facepalm: thanks!","metadata":{"transformedAt":"2026-08-18T18:33:44.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":157,"estimatedTokens":988}}80{"id":"stack-67114152","source":"stackoverflow","questionId":67114152,"title":"TypeScript/Eslint throwing a 'Promise returned' error on a Express Router async route","tags":["node.js","typescript","eslint","typeorm","express-router"],"text":"Title: TypeScript/Eslint throwing a 'Promise returned' error on a Express Router async route\nTags: node.js, typescript, eslint, typeorm, express-router\nSource: Stack Overflow\n\nQuestion:\nI have the following endpoint setup to reset a database after test runs:\n\n```\nimport { getConnection } from 'typeorm';\nimport express from 'express';\nconst router = express.Router();\n\nconst resetDatabase = async (): Promise => {\n const connection = getConnection();\n await connection.dropDatabase();\n await connection.synchronize();\n};\n\n// typescript-eslint throws an error in the following route:\nrouter.post('/reset', async (_request, response) => {\n await resetTestDatabase();\n response.status(204).end();\n});\n\nexport default router;\n```\n\nThe entire route since `async` is underlined with a typescript-eslint error `Promise returned in function argument where a void return was expected.`\n\nThe app works perfectly but I'm not sure if I should be doing a safer implementation or just ignoring/disabling Eslint for this one. Any idea of what's wrong with that code?\n\n========================================\n\nTop Answer:\nI found a solution that doesn't involves using `then()` and let you use the abstraction of async without getting cursed by the eslint, there's two solutions *(but i recommend more the second one)*\n\n### First Solution: Using \"inside async\"\n\nThis is basic using a async inside the void like this:\n\n```\nrouter.post('/reset', (_request, response) => {\n (async () => {\n await resetTestDatabase();\n response.status(204).end();\n })()\n});\n```\n\n### Second Solution *(recommended)*: \"Type Overlap\"\n\nThe second option is to you use it as an async, as Always, but say \"hey TypeScript, nothing is wrong here hehe\" with the \"as\" keyword\n\n```\nimport { RequestHandler } from 'express'\n\nrouter.post('/reset', (async (_request, response) => {\n await resetTestDatabase();\n response.status(204).end();\n}) as RequestHandler);\n```\n\n========================================\n\nCode:\n```text\nimport { getConnection } from 'typeorm';\nimport express from 'express';\nconst router = express.Router();\n\nconst resetDatabase = async (): Promise<void> => {\n const connection = getConnection();\n await connection.dropDatabase();\n await connection.synchronize();\n};\n\n// typescript-eslint throws an error in the following route:\nrouter.post('/reset', async (_request, response) => {\n await resetTestDatabase();\n response.status(204).end();\n});\n\nexport default router;\n```\n\n```text\nasync\n```\n\n```text\nPromise returned in function argument where a void return was expected.\n```\n\n```text\nimport { getConnection } from 'typeorm';\nimport express from 'express';\nconst router = express.Router();\n\nconst resetDatabase = async (): Promise<void> => {\n const connection = getConnection();\n await connection.dropDatabase();\n await connection.synchronize();\n};\n\n// typescript-eslint throws an error in the following route:\nrouter.post('/reset', async (_request, response) => {\n await resetTestDatabase();\n return response.status(204).send(); // <----- return added here\n});\n\nexport default router;\n```\n\n```text\nrouter.post('/reset', (_request, response) => {\n resetDatabase().then(() => response.status(204).send());\n});\n```\n\n```text\nPromise<void>\n```\n\n```text\nvoid\n```\n\n```text\nPromise<void>\n```\n\n```text\nRequestHandler\n```\n\n```text\nvoid\n```\n\n```text\nPromise<Response>\n```\n\n```text\nreturn\n```\n\n```text\nasync/await\n```\n\n```ts\nrouter.post('/reset', (_request, response) => {\n (async () => {\n await resetTestDatabase();\n response.status(204).end();\n })()\n});\n```\n\n```ts\nimport { RequestHandler } from 'express'\n\nrouter.post('/reset', (async (_request, response) => {\n await resetTestDatabase();\n response.status(204).end();\n}) as RequestHandler);\n```\n\n```text\nthen()\n```\n\n```text\nimport { RequestHandler } from 'express'\n\nrouter.post('/reset', (async (_request, response) => {\n await resetTestDatabase();\n response.status(204).end();\n}) as RequestHandler);\n```\n\n```text\napp.get(\"/manifest.webmanifest\", (_req, res) => {\n getManifest(pwaOptions)\n .then(result => res.send(result))\n .catch(error => res.status(500).send('Unexpected error'))\n});\n```\n\n```text\nRequestHandler\n```\n\n```text\n.catch(...)\n```\n\n========================================\n\nComments:\n- I put this into the Typescript playground and it compiles without any errors so I don't think anything is wrong with the code. Maybe if you your linting configuration we can get to the bottom of it.\n- Actually scratch that, I've checked what linting rule causes this and I'll write a proper answer\n- This question is similar to: Promise returned in function argument where a void return was expected. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.\n- Thank you! The second solution works, but adding the return to the first one keeps throwing the error, it really feels like eslint does not like that async. The rule is indeed `no-misused-promises`, forgot to mention it. Any idea of what might be happening with async await? I'm actually trying to get rid of .then()s for consistency =)\n- When you add `async` to a function, it automatically makes the return type a `Promise`. If you were to return nothing as you do in your `async` function, the return type is `Promise` instead of just `void`. Honestly, I'm not sure that linting rule is worth it so I would be tempted to disable it.\n- Maybe you can try adding a type annotation to your handler. Like `async (_request, response): Promise => {`\n- His majesty doesn't like it. There is only so much time one can spend trying to appease Typescripot :P I'll just leave the then(), thanks again mate!\n- Is there any way to solve this without then()?\n- A lot of places like event handlers, I'm just trying to use `await` inside the callback function, I couldn't care less about whether it returns nothing or a promise of nothing, it makes no difference. It's ugly, hard to read, and a pain in the ass to have to use some verbose inner async autocalled function every time you want to use an await. No thanks. To disable the rule in this specific scenario you can set the `checksVoidReturn` option for `@typescript-eslint/no-misused-promises` to `false`.\n- It does make a difference, because a Promise can fail so you could end up with an unhandled promise rejection. If you know that this can't happen in your particular scenario, then you can silence the warning in that particular place (or disable checksVoidReturn entirely as you suggested)\n- What's the benefit of doing this? It sounds like OP gets a linting error for something that's desired behavior. Rather than create a complicated workaround for the linting error, it makes way more sense to disable the rule... unless I'm missing something.\n- Well, sometimes to disable some rules is kinda mean when you're using eslint, because if you don't want rules, why you using eslint after all? 👍🤔\n- I think that's a great question! Why use eslint at all? To me it's to enforce certain rules around code that ensure that the code is better. If applying a rule makes code worse, it's not a good rule.\n- Fair enough, make sense\n- You use eslint, because this is a very valid error that in some cases causes terribly hard to find bugs. It's just that this is not such a case, that's why you ignore it *just* here, not for all the code.\n- I think for the time being where ExpressJS5 is still in beta the express-async-handler is the \"cleanest\" solution. As you don't need to alter or duplicate any logic and just need to wrap the router callable in that function.","metadata":{"transformedAt":"2026-08-18T18:33:44.688Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":217,"estimatedTokens":1911}}81{"id":"stack-54192483","source":"stackoverflow","questionId":54192483,"title":"Typeorm dynamic query builder from structured object","tags":["graphql","typeorm"],"text":"Title: Typeorm dynamic query builder from structured object\nTags: graphql, typeorm\nSource: Stack Overflow\n\nQuestion:\nFor use in a graphql server I have defined a structured input type where you can specify a number of filter conditions very similar to how prisma works:\n\nhttps://i.sstatic.net/mRvM9.png\n\nWhich allows me to submit structured filters in a query like:\n\n```\n{\n users(\n where: {\n OR: [{ email: { starts_with: \"ja\" } }, { email: { ends_with: \".com\" } }],\n AND: [{ email: { starts_with: \"ja\" } }, { email: { ends_with: \".com\" } }],\n email: {contains: \"lowe\"}\n }\n ) {\n id\n email\n }\n}\n```\n\nInside my resolver I feed the args.where through a function to parse the structure and utilize TypeOrm's query builder to convert it to proper sql. The entirety of the function is:\n\n```\nimport { Brackets } from \"typeorm\";\n\nexport const filterQuery = (query: any, where: any) => {\n if (!where) {\n return query;\n }\n\n Object.keys(where).forEach(key => {\n if (key === \"OR\") {\n where[key].map((queryArray: any) => {\n query.orWhere(new Brackets(qb => filterQuery(qb, queryArray)));\n });\n } else if (key === \"AND\") {\n where[key].map((queryArray: any) => {\n query.andWhere(new Brackets(qb => filterQuery(qb, queryArray)));\n });\n } else {\n const whereArgs = Object.entries(where);\n\n whereArgs.map(whereArg => {\n const [fieldName, filters] = whereArg;\n const ops = Object.entries(filters);\n\n ops.map(parameters => {\n const [operation, value] = parameters;\n\n switch (operation) {\n case \"is\": {\n query.andWhere(`${fieldName} = :isvalue`, { isvalue: value });\n break;\n }\n case \"not\": {\n query.andWhere(`${fieldName} != :notvalue`, { notvalue: value });\n break;\n }\n case \"in\": {\n query.andWhere(`${fieldName} IN :invalue`, { invalue: value });\n break;\n }\n case \"not_in\": {\n query.andWhere(`${fieldName} NOT IN :notinvalue`, {\n notinvalue: value\n });\n break;\n }\n case \"lt\": {\n query.andWhere(`${fieldName} :gtvalue`, { gtvalue: value });\n break;\n }\n case \"gte\": {\n query.andWhere(`${fieldName} >= :gtevalue`, { gtevalue: value });\n break;\n }\n case \"contains\": {\n query.andWhere(`${fieldName} ILIKE :convalue`, {\n convalue: `%${value}%`\n });\n break;\n }\n case \"not_contains\": {\n query.andWhere(`${fieldName} NOT ILIKE :notconvalue`, {\n notconvalue: `%${value}%`\n });\n break;\n }\n case \"starts_with\": {\n query\n .andWhere(`${fieldName} ILIKE :swvalue`)\n .setParameter(\"swvalue\", `${value}%`);\n break;\n }\n case \"not_starts_with\": {\n query\n .andWhere(`${fieldName} NOT ILIKE :nswvalue`)\n .setParameter(\"nswvalue\", `${value}%`);\n break;\n }\n case \"ends_with\": {\n query.andWhere(`${fieldName} ILIKE :ewvalue`, {\n ewvalue: `%${value}`\n });\n break;\n }\n case \"not_ends_with\": {\n query.andWhere(`${fieldName} ILIKE :newvalue`, {\n newvalue: `%${value}`\n });\n break;\n }\n default: {\n break;\n }\n }\n });\n });\n }\n });\n\n return query;\n};\n```\n\nWhich works (kinda) but does not nest the AND/OR queries like I would expect (and had previously got working in KNEX). The above function generates the SQL:\n\n```\nSELECT\n \"user\".\"id\" AS \"user_id\",\n \"user\".\"name\" AS \"user_name\",\n \"user\".\"email\" AS \"user_email\",\n \"user\".\"loginToken\" AS \"user_loginToken\",\n \"user\".\"loginTokenExpiry\" AS \"user_loginTokenExpiry\",\n \"user\".\"active\" AS \"user_active\",\n \"user\".\"visible\" AS \"user_visible\",\n \"user\".\"isStaff\" AS \"user_isStaff\",\n \"user\".\"isBilling\" AS \"user_isBilling\",\n \"user\".\"createdAt\" AS \"user_createdAt\",\n \"user\".\"updatedAt\" AS \"user_updatedAt\",\n \"user\".\"version\" AS \"user_version\"\nFROM \"user\" \"user\"\nWHERE (email ILIKE $1)\n AND (email ILIKE $2)\n OR (email ILIKE $3)\n OR (email ILIKE $4)\n AND email ILIKE $5\n-- PARAMETERS: [\"ja%\",\"%.com\",\"ja%\",\"%.com\",\"%lowe%\"]\n```\n\nBut I would expect to see something more like:\n\n```\n..... \nWHERE email ILIKE '%low%' \nAND (\n email ILIKE 'ja%' AND email ILIKE '%.com'\n) AND (\n email ILIKE 'ja%' OR email ILIKE '%.com'\n)\n```\n\nForgive the nonsense, repetitive query. I'm just trying to illustrated the expected NESTED statements.\n\nHow can I force the AND/OR branches of my query builder function to properly nest like expected?\n\n** Bonus points if someone can help me figure out the actual typescript typings here **\n\n========================================\n\nTop Answer:\nBased on Ben's answer, I tweaked a little the functions to allow a more versatile \"*filter*\" object:\n\n```\nSPDX-License-Identifier: Apache-2.0\n\n// enum\nexport enum Operator {\n AND = 'AND',\n OR = 'OR',\n}\n\n// interfaces\ninterface FieldOptions {\n is?: string;\n not?: string;\n in?: string;\n not_in?: string;\n lt?: string;\n lte?: string;\n gt?: string;\n gte?: string;\n contains?: string;\n not_contains?: string;\n starts_with?: string;\n not_starts_with?: string;\n ends_with?: string;\n not_ends_with?: string;\n}\n\nexport interface Field {\n [key: string]: FieldOptions;\n}\n\nexport type Where = {\n [K in Operator]?: (Where | Field)[];\n};\n\n// functions\nexport const filterQuery = (query: SelectQueryBuilder, where: Where) => {\n if (!where) {\n return query;\n } else {\n return traverseTree(query, where) as SelectQueryBuilder;\n }\n};\n\nconst traverseTree = (query: WhereExpression, where: Where, upperOperator = Operator.AND) => {\n Object.keys(where).forEach((key) => {\n if (key === Operator.OR) {\n query = query.orWhere(buildNewBrackets(where, Operator.OR));\n } else if (key === Operator.AND) {\n query = query.andWhere(buildNewBrackets(where, Operator.AND));\n } else {\n // Field\n query = handleArgs(query, where as Field, upperOperator === Operator.AND ? 'andWhere' : 'orWhere');\n }\n });\n\n return query;\n};\n\nconst buildNewBrackets = (where: Where, operator: Operator) => {\n return new Brackets((qb) =>\n where[operator].map((queryArray) => {\n traverseTree(qb, queryArray, operator);\n }),\n );\n};\n\nconst handleArgs = (query: WhereExpression, field: Field, andOr: 'andWhere' | 'orWhere') => {\n ...\n};\n```\n\nThis way we now can have this kind of object as a query parameter:\n\n```\n{\n AND: [\n {\n OR: [\n {\n name: {\n is: 'John'\n },\n },\n {\n surname: {\n is: 'Doe'\n },\n }\n ]\n },\n {\n AND: [\n {\n age: {\n gt: 30\n },\n },\n {\n type: {\n not: 'Employee'\n }\n }\n ]\n },\n {\n registered_date: {\n gte: '2000-01-01'\n }\n }\n ]\n}\n```\n\nThe resulting query would be:\n\n```\nSELECT *\nFROM users U \nWHERE (U.name = 'John' OR U.surname = 'Doe') AND (U.age > 30 AND U.type != 'Employee') AND U.registered_date >= '2000-01-01';\n```\n\n========================================\n\nCode:\n```js\n{\n users(\n where: {\n OR: [{ email: { starts_with: \"ja\" } }, { email: { ends_with: \".com\" } }],\n AND: [{ email: { starts_with: \"ja\" } }, { email: { ends_with: \".com\" } }],\n email: {contains: \"lowe\"}\n }\n ) {\n id\n email\n }\n}\n```\n\n```js\nimport { Brackets } from \"typeorm\";\n\nexport const filterQuery = (query: any, where: any) => {\n if (!where) {\n return query;\n }\n\n Object.keys(where).forEach(key => {\n if (key === \"OR\") {\n where[key].map((queryArray: any) => {\n query.orWhere(new Brackets(qb => filterQuery(qb, queryArray)));\n });\n } else if (key === \"AND\") {\n where[key].map((queryArray: any) => {\n query.andWhere(new Brackets(qb => filterQuery(qb, queryArray)));\n });\n } else {\n const whereArgs = Object.entries(where);\n\n whereArgs.map(whereArg => {\n const [fieldName, filters] = whereArg;\n const ops = Object.entries(filters);\n\n ops.map(parameters => {\n const [operation, value] = parameters;\n\n switch (operation) {\n case \"is\": {\n query.andWhere(`${fieldName} = :isvalue`, { isvalue: value });\n break;\n }\n case \"not\": {\n query.andWhere(`${fieldName} != :notvalue`, { notvalue: value });\n break;\n }\n case \"in\": {\n query.andWhere(`${fieldName} IN :invalue`, { invalue: value });\n break;\n }\n case \"not_in\": {\n query.andWhere(`${fieldName} NOT IN :notinvalue`, {\n notinvalue: value\n });\n break;\n }\n case \"lt\": {\n query.andWhere(`${fieldName} < :ltvalue`, { ltvalue: value });\n break;\n }\n case \"lte\": {\n query.andWhere(`${fieldName} <= :ltevalue`, { ltevalue: value });\n break;\n }\n case \"gt\": {\n query.andWhere(`${fieldName} > :gtvalue`, { gtvalue: value });\n break;\n }\n case \"gte\": {\n query.andWhere(`${fieldName} >= :gtevalue`, { gtevalue: value });\n break;\n }\n case \"contains\": {\n query.andWhere(`${fieldName} ILIKE :convalue`, {\n convalue: `%${value}%`\n });\n break;\n }\n case \"not_contains\": {\n query.andWhere(`${fieldName} NOT ILIKE :notconvalue`, {\n notconvalue: `%${value}%`\n });\n break;\n }\n case \"starts_with\": {\n query\n .andWhere(`${fieldName} ILIKE :swvalue`)\n .setParameter(\"swvalue\", `${value}%`);\n break;\n }\n case \"not_starts_with\": {\n query\n .andWhere(`${fieldName} NOT ILIKE :nswvalue`)\n .setParameter(\"nswvalue\", `${value}%`);\n break;\n }\n case \"ends_with\": {\n query.andWhere(`${fieldName} ILIKE :ewvalue`, {\n ewvalue: `%${value}`\n });\n break;\n }\n case \"not_ends_with\": {\n query.andWhere(`${fieldName} ILIKE :newvalue`, {\n newvalue: `%${value}`\n });\n break;\n }\n default: {\n break;\n }\n }\n });\n });\n }\n });\n\n return query;\n};\n```\n\n```sql\nSELECT\n \"user\".\"id\" AS \"user_id\",\n \"user\".\"name\" AS \"user_name\",\n \"user\".\"email\" AS \"user_email\",\n \"user\".\"loginToken\" AS \"user_loginToken\",\n \"user\".\"loginTokenExpiry\" AS \"user_loginTokenExpiry\",\n \"user\".\"active\" AS \"user_active\",\n \"user\".\"visible\" AS \"user_visible\",\n \"user\".\"isStaff\" AS \"user_isStaff\",\n \"user\".\"isBilling\" AS \"user_isBilling\",\n \"user\".\"createdAt\" AS \"user_createdAt\",\n \"user\".\"updatedAt\" AS \"user_updatedAt\",\n \"user\".\"version\" AS \"user_version\"\nFROM \"user\" \"user\"\nWHERE (email ILIKE $1)\n AND (email ILIKE $2)\n OR (email ILIKE $3)\n OR (email ILIKE $4)\n AND email ILIKE $5\n-- PARAMETERS: [\"ja%\",\"%.com\",\"ja%\",\"%.com\",\"%lowe%\"]\n```\n\n```js\n..... \nWHERE email ILIKE '%low%' \nAND (\n email ILIKE 'ja%' AND email ILIKE '%.com'\n) AND (\n email ILIKE 'ja%' OR email ILIKE '%.com'\n)\n```\n\n```js\nimport { Brackets, WhereExpression, SelectQueryBuilder } from \"typeorm\";\n\ninterface FieldOptions {\n starts_with?: string;\n ends_with?: string;\n contains?: string;\n}\n\ninterface Fields {\n email?: FieldOptions;\n}\n\ninterface Where extends Fields {\n OR?: Fields[];\n AND?: Fields[];\n}\n\nconst handleArgs = (\n query: WhereExpression,\n where: Where,\n andOr: \"andWhere\" | \"orWhere\"\n) => {\n const whereArgs = Object.entries(where);\n\n whereArgs.map(whereArg => {\n const [fieldName, filters] = whereArg;\n const ops = Object.entries(filters);\n\n ops.map(parameters => {\n const [operation, value] = parameters;\n\n switch (operation) {\n case \"is\": {\n query[andOr](`${fieldName} = :isvalue`, { isvalue: value });\n break;\n }\n case \"not\": {\n query[andOr](`${fieldName} != :notvalue`, { notvalue: value });\n break;\n }\n case \"in\": {\n query[andOr](`${fieldName} IN :invalue`, { invalue: value });\n break;\n }\n case \"not_in\": {\n query[andOr](`${fieldName} NOT IN :notinvalue`, {\n notinvalue: value\n });\n break;\n }\n case \"lt\": {\n query[andOr](`${fieldName} < :ltvalue`, { ltvalue: value });\n break;\n }\n case \"lte\": {\n query[andOr](`${fieldName} <= :ltevalue`, { ltevalue: value });\n break;\n }\n case \"gt\": {\n query[andOr](`${fieldName} > :gtvalue`, { gtvalue: value });\n break;\n }\n case \"gte\": {\n query[andOr](`${fieldName} >= :gtevalue`, { gtevalue: value });\n break;\n }\n case \"contains\": {\n query[andOr](`${fieldName} ILIKE :convalue`, {\n convalue: `%${value}%`\n });\n break;\n }\n case \"not_contains\": {\n query[andOr](`${fieldName} NOT ILIKE :notconvalue`, {\n notconvalue: `%${value}%`\n });\n break;\n }\n case \"starts_with\": {\n query[andOr](`${fieldName} ILIKE :swvalue`, {\n swvalue: `${value}%`\n });\n break;\n }\n case \"not_starts_with\": {\n query[andOr](`${fieldName} NOT ILIKE :nswvalue`, {\n nswvalue: `${value}%`\n });\n break;\n }\n case \"ends_with\": {\n query[andOr](`${fieldName} ILIKE :ewvalue`, {\n ewvalue: `%${value}`\n });\n break;\n }\n case \"not_ends_with\": {\n query[andOr](`${fieldName} ILIKE :newvalue`, {\n newvalue: `%${value}`\n });\n break;\n }\n default: {\n break;\n }\n }\n });\n });\n\n return query;\n};\n\nexport const filterQuery = <T>(query: SelectQueryBuilder<T>, where: Where) => {\n if (!where) {\n return query;\n }\n\n Object.keys(where).forEach(key => {\n if (key === \"OR\") {\n query.andWhere(\n new Brackets(qb =>\n where[key]!.map(queryArray => {\n handleArgs(qb, queryArray, \"orWhere\");\n })\n )\n );\n } else if (key === \"AND\") {\n query.andWhere(\n new Brackets(qb =>\n where[key]!.map(queryArray => {\n handleArgs(qb, queryArray, \"andWhere\");\n })\n )\n );\n }\n });\n\n return query;\n};\n```\n\n```text\nSPDX-License-Identifier: Apache-2.0\n\n// enum\nexport enum Operator {\n AND = 'AND',\n OR = 'OR',\n}\n\n// interfaces\ninterface FieldOptions {\n is?: string;\n not?: string;\n in?: string;\n not_in?: string;\n lt?: string;\n lte?: string;\n gt?: string;\n gte?: string;\n contains?: string;\n not_contains?: string;\n starts_with?: string;\n not_starts_with?: string;\n ends_with?: string;\n not_ends_with?: string;\n}\n\nexport interface Field {\n [key: string]: FieldOptions;\n}\n\nexport type Where = {\n [K in Operator]?: (Where | Field)[];\n};\n\n// functions\nexport const filterQuery = <T>(query: SelectQueryBuilder<T>, where: Where) => {\n if (!where) {\n return query;\n } else {\n return traverseTree(query, where) as SelectQueryBuilder<T>;\n }\n};\n\nconst traverseTree = (query: WhereExpression, where: Where, upperOperator = Operator.AND) => {\n Object.keys(where).forEach((key) => {\n if (key === Operator.OR) {\n query = query.orWhere(buildNewBrackets(where, Operator.OR));\n } else if (key === Operator.AND) {\n query = query.andWhere(buildNewBrackets(where, Operator.AND));\n } else {\n // Field\n query = handleArgs(query, where as Field, upperOperator === Operator.AND ? 'andWhere' : 'orWhere');\n }\n });\n\n return query;\n};\n\nconst buildNewBrackets = (where: Where, operator: Operator) => {\n return new Brackets((qb) =>\n where[operator].map((queryArray) => {\n traverseTree(qb, queryArray, operator);\n }),\n );\n};\n\nconst handleArgs = (query: WhereExpression, field: Field, andOr: 'andWhere' | 'orWhere') => {\n ...\n};\n```\n\n```text\n{\n AND: [\n {\n OR: [\n {\n name: {\n is: 'John'\n },\n },\n {\n surname: {\n is: 'Doe'\n },\n }\n ]\n },\n {\n AND: [\n {\n age: {\n gt: 30\n },\n },\n {\n type: {\n not: 'Employee'\n }\n }\n ]\n },\n {\n registered_date: {\n gte: '2000-01-01'\n }\n }\n ]\n}\n```\n\n```text\nSELECT *\nFROM users U \nWHERE (U.name = 'John' OR U.surname = 'Doe') AND (U.age > 30 AND U.type != 'Employee') AND U.registered_date >= '2000-01-01';\n```\n\n```sql\nSELECT *\nFROM users U \nWHERE (U.name = 'John' OR U.surname = 'Doe') OR (U.age > 30 AND U.type != 'Employee') AND U.registered_date >= '2000-01-01';\n```\n\n```sql\nSELECT *\nFROM users U \nWHERE (U.name = 'John' OR U.surname = 'Doe') AND (U.age > 30 AND U.type != 'Employee') AND U.registered_date >= '2000-01-01';\n```\n\n========================================\n\nComments:\n- in your example query, there is { id email}, are you sure this is you are getting because it is seems to be a json, json should have pair. Also what is query? you are calling query.orWhere\n- Thanks Shadab. It's not json, its a standard Graphql query. Id and email represent the return fields I want back from the query.\n- This is FANTASTIC. Thank you Ben. The only case this does not cover is the root level statements not nested under AND or WHERE.. In the case of my example query above the `email: {contains: \"lowe\"}` is ignored. In your opinion should I accept root level where statements or do should I require all statements to be nested in either OR or AND? ```\n- Now as I tinker more It starts to make more sense to only have AND/OR as the root level elements. It is far more explicit that way and not much of an inconvenience.\n- and if you did want to add it at the root level you can add an else where you call the function `else { handleArgs(query, where, \"andWhere\") }`\n- This assumes no fields have a duplicate name, however, how might one address a case where two tables are joined and the function must distinguish between `id` in the first entity vs `id` in the second entity without getting error: `Error: ER_NON_UNIQ_ERROR: Column 'id' in where clause is ambiguous`?\n- @benawad Sorry for that but are you the ben awad?\n- This opens code to SQL injections if used on user input.","metadata":{"transformedAt":"2026-08-18T18:33:44.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":746,"estimatedTokens":4477}}82{"id":"stack-56644690","source":"stackoverflow","questionId":56644690,"title":"How to mock chained function calls using jest?","tags":["node.js","typescript","jestjs","nestjs","typeorm"],"text":"Title: How to mock chained function calls using jest?\nTags: node.js, typescript, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am testing the following service:\n\n```\n@Injectable()\nexport class TripService {\n private readonly logger = new Logger('TripService');\n\n constructor(\n @InjectRepository(TripEntity)\n private tripRepository: Repository\n ) {}\n\n public async showTrip(clientId: string, tripId: string): Promise> {\n const trip = await this.tripRepository\n .createQueryBuilder('trips')\n .innerJoinAndSelect('trips.driver', 'driver', 'driver.clientId = :clientId', { clientId })\n .where({ id: tripId })\n .select([\n 'trips.id',\n 'trips.distance',\n 'trips.sourceAddress',\n 'trips.destinationAddress',\n 'trips.startTime',\n 'trips.endTime',\n 'trips.createdAt'\n ])\n .getOne();\n\n if (!trip) {\n throw new HttpException('Trip not found', HttpStatus.NOT_FOUND);\n }\n\n return trip;\n }\n}\n```\n\nMy repository mock:\n\n```\nexport const repositoryMockFactory: () => MockType> = jest.fn(() => ({\n findOne: jest.fn(entity => entity),\n findAndCount: jest.fn(entity => entity),\n create: jest.fn(entity => entity),\n save: jest.fn(entity => entity),\n update: jest.fn(entity => entity),\n delete: jest.fn(entity => entity),\n createQueryBuilder: jest.fn(() => ({\n delete: jest.fn().mockReturnThis(),\n innerJoinAndSelect: jest.fn().mockReturnThis(),\n innerJoin: jest.fn().mockReturnThis(),\n from: jest.fn().mockReturnThis(),\n where: jest.fn().mockReturnThis(),\n execute: jest.fn().mockReturnThis(),\n getOne: jest.fn().mockReturnThis(),\n })),\n}));\n```\n\nMy tripService.spec.ts:\n\n```\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { TripService } from './trip.service';\nimport { MockType } from '../mock/mock.type';\nimport { Repository } from 'typeorm';\nimport { TripEntity } from './trip.entity';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport { repositoryMockFactory } from '../mock/repositoryMock.factory';\nimport { DriverEntity } from '../driver/driver.entity';\nimport { plainToClass } from 'class-transformer';\n\ndescribe('TripService', () => {\n let service: TripService;\n let tripRepositoryMock: MockType>;\n let driverRepositoryMock: MockType>;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n TripService,\n { provide: getRepositoryToken(DriverEntity), useFactory: repositoryMockFactory },\n { provide: getRepositoryToken(TripEntity), useFactory: repositoryMockFactory },\n ],\n }).compile();\n\n service = module.get(TripService);\n driverRepositoryMock = module.get(getRepositoryToken(DriverEntity));\n tripRepositoryMock = module.get(getRepositoryToken(TripEntity));\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n expect(driverRepositoryMock).toBeDefined();\n expect(tripRepositoryMock).toBeDefined();\n });\n\n describe('TripService.showTrip()', () => {\n const trip: TripEntity = plainToClass(TripEntity, {\n id: 'one',\n distance: 123,\n sourceAddress: 'one',\n destinationAddress: 'one',\n startTime: 'one',\n endTime: 'one',\n createdAt: 'one',\n });\n it('should show the trip is it exists', async () => {\n tripRepositoryMock.createQueryBuilder.mockReturnValue(trip);\n await expect(service.showTrip('one', 'one')).resolves.toEqual(trip);\n });\n });\n});\n```\n\nI want to mock the call to the `tripRepository.createQueryBuilder().innerJoinAndSelect().where().select().getOne();`\n\nFirst question, should I mock the chained calls here because I assume that it should already be tested in Typeorm.\n\nSecond, if I want to mock the parameters passed to each chained call and finally also mock the return value, how can I go about it?\n\n========================================\n\nTop Answer:\nGuilherme's answer is totally right. I just wanted to offer a modified approach that might apply to more test cases, and in TypeScript. Instead of defining your chained calls as `()`, you can use a `jest.fn`, allowing you to make more assertions. e.g.,\n\n```\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst createQueryBuilder: any = {\n select: jest.fn().mockImplementation(() => {\n return createQueryBuilder\n }),\n addSelect: jest.fn().mockImplementation(() => {\n return createQueryBuilder\n }),\n groupBy: jest.fn().mockImplementation(() => {\n return createQueryBuilder\n }),\n where: jest.fn().mockImplementation(() => {\n return createQueryBuilder\n }),\n getRawMany: jest\n .fn()\n .mockImplementationOnce(() => {\n return FILTERED_REACTIONS\n })\n .mockImplementationOnce(() => {\n return SOMETHING_ELSE\n }),\n}\n\n/* run your code */\n\n// then you can include an assertion like this:\nexpect(createQueryBuilder.groupBy).toHaveBeenCalledWith(`some group`)\n```\n\n========================================\n\nCode:\n```js\n@Injectable()\nexport class TripService {\n private readonly logger = new Logger('TripService');\n\n constructor(\n @InjectRepository(TripEntity)\n private tripRepository: Repository<TripEntity>\n ) {}\n\n public async showTrip(clientId: string, tripId: string): Promise<Partial<TripEntity>> {\n const trip = await this.tripRepository\n .createQueryBuilder('trips')\n .innerJoinAndSelect('trips.driver', 'driver', 'driver.clientId = :clientId', { clientId })\n .where({ id: tripId })\n .select([\n 'trips.id',\n 'trips.distance',\n 'trips.sourceAddress',\n 'trips.destinationAddress',\n 'trips.startTime',\n 'trips.endTime',\n 'trips.createdAt'\n ])\n .getOne();\n\n if (!trip) {\n throw new HttpException('Trip not found', HttpStatus.NOT_FOUND);\n }\n\n return trip;\n }\n}\n```\n\n```text\nexport const repositoryMockFactory: () => MockType<Repository<any>> = jest.fn(() => ({\n findOne: jest.fn(entity => entity),\n findAndCount: jest.fn(entity => entity),\n create: jest.fn(entity => entity),\n save: jest.fn(entity => entity),\n update: jest.fn(entity => entity),\n delete: jest.fn(entity => entity),\n createQueryBuilder: jest.fn(() => ({\n delete: jest.fn().mockReturnThis(),\n innerJoinAndSelect: jest.fn().mockReturnThis(),\n innerJoin: jest.fn().mockReturnThis(),\n from: jest.fn().mockReturnThis(),\n where: jest.fn().mockReturnThis(),\n execute: jest.fn().mockReturnThis(),\n getOne: jest.fn().mockReturnThis(),\n })),\n}));\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { TripService } from './trip.service';\nimport { MockType } from '../mock/mock.type';\nimport { Repository } from 'typeorm';\nimport { TripEntity } from './trip.entity';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport { repositoryMockFactory } from '../mock/repositoryMock.factory';\nimport { DriverEntity } from '../driver/driver.entity';\nimport { plainToClass } from 'class-transformer';\n\ndescribe('TripService', () => {\n let service: TripService;\n let tripRepositoryMock: MockType<Repository<TripEntity>>;\n let driverRepositoryMock: MockType<Repository<DriverEntity>>;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n TripService,\n { provide: getRepositoryToken(DriverEntity), useFactory: repositoryMockFactory },\n { provide: getRepositoryToken(TripEntity), useFactory: repositoryMockFactory },\n ],\n }).compile();\n\n service = module.get<TripService>(TripService);\n driverRepositoryMock = module.get(getRepositoryToken(DriverEntity));\n tripRepositoryMock = module.get(getRepositoryToken(TripEntity));\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n expect(driverRepositoryMock).toBeDefined();\n expect(tripRepositoryMock).toBeDefined();\n });\n\n describe('TripService.showTrip()', () => {\n const trip: TripEntity = plainToClass(TripEntity, {\n id: 'one',\n distance: 123,\n sourceAddress: 'one',\n destinationAddress: 'one',\n startTime: 'one',\n endTime: 'one',\n createdAt: 'one',\n });\n it('should show the trip is it exists', async () => {\n tripRepositoryMock.createQueryBuilder.mockReturnValue(trip);\n await expect(service.showTrip('one', 'one')).resolves.toEqual(trip);\n });\n });\n});\n```\n\n```text\ntripRepository.createQueryBuilder().innerJoinAndSelect().where().select().getOne();\n```\n\n```text\nconst reactions = await this.reactionEntity\n .createQueryBuilder(TABLE_REACTIONS)\n .select('reaction')\n .addSelect('COUNT(1) as count')\n .groupBy('content_id, source, reaction')\n .where(`content_id = :contentId AND source = :source`, {\n contentId,\n source,\n })\n .getRawMany<GetContentReactionsResult>();\n\nreturn reactions;\n```\n\n```text\nit('should return the reactions that match the supplied parameters', async () => {\n const PARAMS = { contentId: '1', source: 'anything' };\n\n const FILTERED_REACTIONS = REACTIONS.filter(\n r => r.contentId === PARAMS.contentId && r.source === PARAMS.source,\n );\n\n // Pay attention to this part. Here I created a createQueryBuilder \n // const with all methods I call in the code above. Notice that I return\n // the same `createQueryBuilder` in all the properties/methods it has\n // except in the last one that is the one that return the data \n // I want to check.\n const createQueryBuilder: any = {\n select: () => createQueryBuilder,\n addSelect: () => createQueryBuilder,\n groupBy: () => createQueryBuilder,\n where: () => createQueryBuilder,\n getRawMany: () => FILTERED_REACTIONS,\n };\n\n jest\n .spyOn(reactionEntity, 'createQueryBuilder')\n .mockImplementation(() => createQueryBuilder);\n\n await expect(query.getContentReactions(PARAMS)).resolves.toEqual(\n FILTERED_REACTIONS,\n );\n});\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst createQueryBuilder: any = {\n select: jest.fn().mockImplementation(() => {\n return createQueryBuilder\n }),\n addSelect: jest.fn().mockImplementation(() => {\n return createQueryBuilder\n }),\n groupBy: jest.fn().mockImplementation(() => {\n return createQueryBuilder\n }),\n where: jest.fn().mockImplementation(() => {\n return createQueryBuilder\n }),\n getRawMany: jest\n .fn()\n .mockImplementationOnce(() => {\n return FILTERED_REACTIONS\n })\n .mockImplementationOnce(() => {\n return SOMETHING_ELSE\n }),\n}\n\n/* run your code */\n\n// then you can include an assertion like this:\nexpect(createQueryBuilder.groupBy).toHaveBeenCalledWith(`some group`)\n```\n\n```text\n()\n```\n\n```text\njest.fn\n```\n\n```text\n@EntityRepository(User)\n export class UserRepository extends Repository<User> {\n async getStatus(id: string) {\n const status = await this.createQueryBuilder()\n .select('User.id')\n .where('User.id = :id', { id })\n .getRawOne();\n\n return {status};\n }\n }\n```\n\n```text\nconst userRepoMock = mock<UserRepository>()\n```\n\n```text\nconst user = {\n status: open,\n };\n\n when(userRepoMock.getStatus).mockResolvedValue(user as User);\n```\n\n========================================\n\nComments:\n- I would say that it could be better that you just use a test database with specific NODE_ENV and configuration so that your test includes all the sql transaction management in it. Mocking TypeOrm SQL interactions seems to me like a suboptimal way to test your service that is also quite expensive in dev time.\n- @zenbeni I will test with test database in e2e tests. This is just a unit test so I don't want to use database for it, as it will slow tests and add tight coupling with database.\n- What's the meaning behind this service? It appears to be a wrapper of your repository. If you want to unit test, you should rather unit test your business logic instead of the persistence layer. Is the TripRepository comming from a library or do you own it? Your test approach appears to be more a functional test and you should set up an actual test database for it.\n- Additionally, I'd argue that you should not create a unit test this service. This service depends on the database. It makes no sense to mock your entire database connection. Rather, this service is your dependency for other services and should be the one mocked. For other services, you should write tests: \"Assume my TripService gives me a trip, then I expect this to happen\" and \"Assume I get an exception, I expect it to be handled that way\" You should not mock each call on the repository. This is your underlying persistence layer. Assume it's working.\n- @k0pernikus This service is not just a wrapper, this has business logic before and after the query. I just gave it as an example. The real question is about mocking chained function calls.\n- @AbhyuditJain That's the issue that your are mixing business logic inside your repository. Create a real facade for your repository. It should only contain methods accessing your tripReposiory. That facade should only provide methods such as `getOneTrip(clientId: string, tripId: string)`. Create another service, that only contains your business logic. That service should depend on your RepositoryFacade. You now only have to mock the `getOneTrip` call instead of mocking the chained methods.\n- Since you are using typeorm and nestjs, this may help you: github.com/BrunnerLivio/nestjs-integration-test-db-example\n- @k0pernikus I ended up doing that only. I extended Repository and made my custom functions.\n- This. This this this. There are lots of questions and answers on this subject but this is the solution that works at the intersection of Jest, TypeScript, and third-party libraries\n- this implementation works with a few details for aggregate in TypeOrm\n- @Guilherme De Jesus Rafael Thank you soo soo much, you saved my next day :-D","metadata":{"transformedAt":"2026-08-18T18:33:44.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":407,"estimatedTokens":3404}}83{"id":"stack-59849262","source":"stackoverflow","questionId":59849262,"title":"Postgresql full text search with TypeOrm","tags":["postgresql","typeorm"],"text":"Title: Postgresql full text search with TypeOrm\nTags: postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nThere is some way to handle full text search with Postgres and TypeOrm. I've seen some examples but they only work with Mysql. How can I get the equivalent of this but with Postgresql?\n\n```\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: string;\n\n @Index({ fulltext: true })\n @Column(\"varchar\")\n name: string;\n}\n```\n\nAnd use query builder:\n\n```\nconst searchTerm = \"John\";\n\nconst result = await connection.manager.getRepository(User)\n .createQueryBuilder()\n .select()\n .where(`MATCH(name) AGAINST ('${searchTerm}' IN BOOLEAN MODE)`)\n .getMany();\n```\n\n========================================\n\nTop Answer:\nHere's an alternative using tsvector, where query is the input string.\n\n```\nconst songs = await getManager()\n .createQueryBuilder()\n .select('song')\n .from(Models.Song, 'song')\n .where(\n 'to_tsvector(song.title) @@ to_tsquery(:query)',\n { query }\n )\n .getMany();\n```\n\nIf you wish to include stop words (You, A, etc), and want partial matching.\n\n```\nconst songs = await getManager()\n .createQueryBuilder()\n .select('song')\n .from(Models.Song, 'song')\n .where(\n `to_tsvector('simple',song.title) @@ to_tsquery('simple', :query)`,\n { query: `${query}:*` }\n )\n .getMany();\n```\n\nIf you also want to allow for multi word strings (with spaces).\n\n```\nconst formattedQuery = query.trim().replace(/ /g, ' & ');\n const songs = await getManager()\n .createQueryBuilder()\n .select('song')\n .from(Models.Song, 'song')\n .where(\n `to_tsvector('simple',song.title) @@ to_tsquery('simple', :query)`,\n { query: `${formattedQuery}:*` }\n )\n .getMany();\n```\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: string;\n\n @Index({ fulltext: true })\n @Column(\"varchar\")\n name: string;\n}\n```\n\n```text\nconst searchTerm = \"John\";\n\nconst result = await connection.manager.getRepository(User)\n .createQueryBuilder()\n .select()\n .where(`MATCH(name) AGAINST ('${searchTerm}' IN BOOLEAN MODE)`)\n .getMany();\n```\n\n```text\nconst searchTerm = \"John\";\n\nconst result = await connection.manager.getRepository(User)\n .createQueryBuilder()\n .select()\n .where('name ILIKE :searchTerm', {searchTerm: `%${searchTerm}%`})\n .getMany();\n```\n\n```text\nconst result = await connection.manager.getRepository(User)\n .createQueryBuilder()\n .select()\n .where('first_name ILIKE :searchTerm', {searchTerm: `%${searchTerm}%`})\n .orWhere('last_name ILIKE :searchTerm', {searchTerm: `%${searchTerm}%`})\n .getMany();\n```\n\n```text\nILIKE\n```\n\n```text\nconst songs = await getManager()\n .createQueryBuilder()\n .select('song')\n .from(Models.Song, 'song')\n .where(\n 'to_tsvector(song.title) @@ to_tsquery(:query)',\n { query }\n )\n .getMany();\n```\n\n```text\nconst songs = await getManager()\n .createQueryBuilder()\n .select('song')\n .from(Models.Song, 'song')\n .where(\n `to_tsvector('simple',song.title) @@ to_tsquery('simple', :query)`,\n { query: `${query}:*` }\n )\n .getMany();\n```\n\n```text\nconst formattedQuery = query.trim().replace(/ /g, ' & ');\n const songs = await getManager()\n .createQueryBuilder()\n .select('song')\n .from(Models.Song, 'song')\n .where(\n `to_tsvector('simple',song.title) @@ to_tsquery('simple', :query)`,\n { query: `${formattedQuery}:*` }\n )\n .getMany();\n```\n\n========================================\n\nComments:\n- github.com/typeorm/typeorm/issues/3068\n- \"*There is some way to handle full text search with Postgres and TypeOrm*\" - how do you know that? Yes, `MATCH(name) AGAINST ('${searchTerm}' IN BOOLEAN MODE)` is definitely MySQL-specific syntax (and also an sql injection).\n- This issue makes no sense to me because I am very new on TypeOrm, I need a more complete example like the one in the question. Thank you!\n- youtube.com/watch?v=szfUbzsKvtE&ab_channel=BenAwad\n- This is how primary a text based search should happen in postgres. The usuage of regular expresssion is fine but they highly affect the performance of the query. Using tsvector() and tsquery() is the postgre recommeded approach as well\n- does the formattedQuery have any risk of SQL injection?\n- I dont think so, but might be worth another stack overflow question entirely.","metadata":{"transformedAt":"2026-08-18T18:33:44.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":174,"estimatedTokens":1113}}84{"id":"stack-66991600","source":"stackoverflow","questionId":66991600,"title":"TypeOrm migration - Error: Cannot find module","tags":["node.js","typeorm"],"text":"Title: TypeOrm migration - Error: Cannot find module\nTags: node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying npm run typeorm migration:run in my project and it is showing the error below.\n\nError during migration run:\nError: Cannot find module 'src/permission/permission.entity'\n\nhttps://i.sstatic.net/IbJYI.png\n\normconfig.js\n\n```\nmodule.exports = {\n type: 'mysql',\n host: 'localhost',\n port: 33066,\n username: 'root',\n password: '123456',\n database: 'admin',\n synchronize: false,\n entities: ['./src/**/*.entity.ts'],\n migrations: ['./src/migrations/*.ts'],\n cli: {\n entitiesDir: './ts/',\n migrationsDir: './src/migrations',\n },\n};\n```\n\nWhat am I doing wrong?\nThis is my git repo: https://github.com/wesoz/udemy-nest-admin/tree/td/seed\n\n========================================\n\nTop Answer:\nUsing *typeorm@^0.3.10*\n\nThis worked for me.\n`npm i -D tsconfig-paths`\n\nAdding this flag to the **ts-node** command `-r tsconfig-paths/register`\n\n```\n\"migration:run\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js migration:run -d=ormconfig.ts\"\n```\n\n========================================\n\nCode:\n```js\nmodule.exports = {\n type: 'mysql',\n host: 'localhost',\n port: 33066,\n username: 'root',\n password: '123456',\n database: 'admin',\n synchronize: false,\n entities: ['./src/**/*.entity.ts'],\n migrations: ['./src/migrations/*.ts'],\n cli: {\n entitiesDir: './ts/',\n migrationsDir: './src/migrations',\n },\n};\n```\n\n```text\nimport { Permission } from '../permission/permission.entity';\n```\n\n```text\n\"migration:run\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js migration:run -d=ormconfig.ts\"\n```\n\n```text\nnpm i -D tsconfig-paths\n```\n\n```text\n-r tsconfig-paths/register\n```\n\n========================================\n\nComments:\n- Thank you so much! Now I'm getting the error: RepositoryNotFoundError: No repository for \"permissions\" was found. Looks like this entity is not registered in current \"default\" connection?\n- No idea sorry, maybe you can ask a new question.\n- That's entirely unrelated\n- This is the answer which worked for me","metadata":{"transformedAt":"2026-08-18T18:33:44.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":93,"estimatedTokens":522}}85{"id":"stack-53141744","source":"stackoverflow","questionId":53141744,"title":"TypeORM basic join explanation","tags":["typeorm","typeorm-datamapper"],"text":"Title: TypeORM basic join explanation\nTags: typeorm, typeorm-datamapper\nSource: Stack Overflow\n\nQuestion:\nAccording to typeorm guide\n\nI don't understand this part very well:\n\n```\n(type => Photo, photo => photo.user)\n```\n\nwhat does mean type? what does mean photo => photo. ? . it's not good explained on the link.\n\nPartial code:\n\n```\nImport {Entity, PrimaryGeneratedColumn, Column, OneToMany} from \"typeorm\";\nimport {Photo} from \"./Photo\";\n\n@Entity()\nexport class User {\n \n @PrimaryGeneratedColumn()\n id: number;\n \n @Column()\n name: string;\n \n @OneToMany(type => Photo, photo => photo.user)\n photos: Photo[];\n}\n```\n\nand on the code:\n\n```\nconst user = await createQueryBuilder(\"user\")\n .leftJoinAndSelect(\"user.photos\", \"photo\")\n .where(\"user.name = :name\", { name: \"Timber\" })\n .getOne();\n```\n\nfrom where comes \"\"user.photos\"?\n\n========================================\n\nCode:\n```text\n(type => Photo, photo => photo.user)\n```\n\n```text\nImport {Entity, PrimaryGeneratedColumn, Column, OneToMany} from \"typeorm\";\nimport {Photo} from \"./Photo\";\n\n@Entity()\nexport class User {\n \n @PrimaryGeneratedColumn()\n id: number;\n \n @Column()\n name: string;\n \n @OneToMany(type => Photo, photo => photo.user)\n photos: Photo[];\n}\n```\n\n```text\nconst user = await createQueryBuilder(\"user\")\n .leftJoinAndSelect(\"user.photos\", \"photo\")\n .where(\"user.name = :name\", { name: \"Timber\" })\n .getOne();\n```\n\n```text\n(type => Photo, photo => photo.user)\n```\n\n```text\n@OneToMany\n```\n\n```text\n@OneToMany(()=> Photo, photo => photo.user)\n```\n\n```text\nwhere comes \"user.photos\"\n```\n\n```text\nleftJoinAndSelect(\"user.photos\", \"photo\")\n```\n\n```text\nphotos\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.689Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":101,"estimatedTokens":415}}86{"id":"stack-59927625","source":"stackoverflow","questionId":59927625,"title":"How to store big int in nest js using typeorm","tags":["nestjs","typeorm"],"text":"Title: How to store big int in nest js using typeorm\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nsome.entity.ts\n\n```\namount:number\n```\n\nBut when I store a very large data in my postgres it throws error '''integer out of range'''\n\nMy question is how can I store **Big Int** as type in psql using typeorm\n\n========================================\n\nTop Answer:\nJust add `{ bigNumberStrings: false }` to TypeORM's configuration, such as:\n\n```\nTypeOrmModule.forRoot({\n bigNumberStrings: false,\n ...config.database,\n}),\n```\n\nThen the bigint will return number type.\n\n========================================\n\nCode:\n```text\namount:number\n```\n\n```text\n@Column({type: 'bigint'})\ncolumnName: string;\n```\n\n```text\nbigint\n```\n\n```text\nbigint\n```\n\n```text\nstring\n```\n\n```text\nTypeOrmModule.forRoot({\n bigNumberStrings: false,\n ...config.database,\n}),\n```\n\n```text\n{ bigNumberStrings: false }\n```\n\n```js\n@PrimaryGeneratedColumn( 'increment', {type: 'bigint'} )\n id: number;\n```\n\n```text\nbigint\n```\n\n```text\nPrimaryGeneratedColumn\n```\n\n```text\nexport class ColumnNumberTransformer {\n public to(data: number): number {\n return data;\n }\n\n public from(data: string): number {\n // output value, you can use Number, parseFloat variations\n // also you can add nullable condition:\n // if (!Boolean(data)) return 0;\n\n return parseInt(data);\n }\n}\n```\n\n```text\n@Entity('accounts')\nexport class AccountEntity extends BaseEntity {\n @Column({\n type: 'bigint',\n nullable: false,\n transformer: new ColumnNumberTransformer()\n })\n public balance: number;\n}\n```\n\n```js\n@Column({type: 'bigint'})\ncolumnName: bigint\n```\n\n```text\nparseInt8: true\n```\n\n```text\ntype\n```\n\n```text\nhost\n```\n\n```text\nport\n```\n\n```text\nbigint\n```\n\n```text\ncolumnName\n```\n\n```text\ncolumnName\n```\n\n```text\nbigint\n```\n\n```text\nstring\n```\n\n```text\nbigNumberStrings\n```\n\n========================================\n\nComments:\n- how about length for integer\n- JS also has a `BigInt` type which can be mapped to/from using the `transformer` option. (Note: `BigInt` in JS is arbitrarily large, not just 8 byte.)\n- Since OP didn't mention the database technology, this is only supported for mysql/mariadb at this time. orkhan.gitbook.io/typeorm/docs/…\n- That is exactly what I need to search for. I am using lib nestjs-typeorm-paginate for pagination but the field \"id\" (type bigint) is always returns a string. Thanks again.\n- this actually worked, appreciate it","metadata":{"transformedAt":"2026-08-18T18:33:44.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":158,"estimatedTokens":624}}87{"id":"stack-56771768","source":"stackoverflow","questionId":56771768,"title":"How to transform input data with NestJS and TypeORM","tags":["typescript","nestjs","typeorm"],"text":"Title: How to transform input data with NestJS and TypeORM\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to create functionality where I can transform incoming data before it hits the database. Let's say that we want to make sure that when a new user is created, the firstName and lastName attribute values are always starting with a capital letter. Or another great example is to prevent login issues and store email addresses always in lowercase letters.\n\nI've taken a look at the pipe documentation of NestJS but it's too generic. I want to be able to specify which fields need transformation and I don't want to create a pipe for each attribute or endpoint that needs transformation.\n\nI've also tried the @Transform decorator form the 'class-transformer' package but this doesn't seem to work.\n\n```\nexport class UserRoleCreateDto {\n @IsDefined()\n @IsString()\n @IsNotEmpty()\n @Transform((name) => name.toUpperCase())\n readonly name;\n}\n```\n\nThe expected result should be the name in uppercase letters but it's not.\n\nAnyone any ideas or examples on how to implement proper input transformation for NestJS / TypeORM before it hits the database?\n\nThanks for your time!\n\n========================================\n\nTop Answer:\nHere is a small working example\n\n```\n@UsePipes(new ValidationPipe({transform: true}))\n @Get('test_input')\n async testInput(@Query() data: UserRoleCreateDto): Promise {\n\n return data;\n }\n```\n\nand checking in bash:\n\n```\ncurl 'http://localhost:3060/test_input?name=hello'\n\n{\"name\":\"HELLO\"}\n```\n\nCheck that you have `ValidationPipe` decorator and especially `transform: true` option, without these it doesn't work. `transform: true` automatically transforms input data to the class instance.\n\nMore about validation on the nestjs documentation page - link\n\nAlso, just in case, instead of `@Query()` decorator you can use `@Body()` for POST data or `@Param()` for URL parameters\n\n========================================\n\nCode:\n```text\nexport class UserRoleCreateDto {\n @IsDefined()\n @IsString()\n @IsNotEmpty()\n @Transform((name) => name.toUpperCase())\n readonly name;\n}\n```\n\n```js\n@Entity()\nexport class User {\n \n @BeforeInsert()\n nameToUpperCase() {\n this.email = this.email.toLowerCase()\n this.name = this.name.toUpperCase();\n }\n}\n```\n\n```text\n@UsePipes(new ValidationPipe({transform: true}))\n @Get('test_input')\n async testInput(@Query() data: UserRoleCreateDto): Promise<any> {\n\n return data;\n }\n```\n\n```text\ncurl 'http://localhost:3060/test_input?name=hello'\n\n{\"name\":\"HELLO\"}\n```\n\n```text\nValidationPipe\n```\n\n```text\ntransform: true\n```\n\n```text\ntransform: true\n```\n\n```text\n@Query()\n```\n\n```text\n@Body()\n```\n\n```text\n@Param()\n```\n\n```text\n@Transform(({name}) => name.toUpperCase())\n```\n\n```text\n@Transform((name) => name.toUpperCase())\n```\n\n```text\n{}\n```\n\n```text\nconsole.log()\n```\n\n```text\nTransform()\n```\n\n```text\n@Matches()\n```\n\n```text\n'class-transformer'\n```\n\n```text\n@UsePipes(new ValidationPipe({transform: true}))\n```\n\n```text\napp.useGlobalPipes\n```\n\n```text\nclass ClassName {\n @Transform((param) => param.value.toUpperCase())\n name: string;\n}\n```\n\n```text\nparam\n```\n\n```text\nvalue, key, obj, type\n```\n\n========================================\n\nComments:\n- This only works when the value is being processed by the controllers middlewares. It doesn't work if the program is running from a script, cron job, etc.","metadata":{"transformedAt":"2026-08-18T18:33:44.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":174,"estimatedTokens":853}}88{"id":"stack-65938257","source":"stackoverflow","questionId":65938257,"title":"How does InjectRepository work internally in NestJS?","tags":["node.js","dependency-injection","nestjs","typeorm"],"text":"Title: How does InjectRepository work internally in NestJS?\nTags: node.js, dependency-injection, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn nestjs, I understand that\n\n```\nimports: [\n TypeOrmModule.forFeature([TaskRepository]),\n],\n```\n\ncreates some kind of provider token so then I can inject the repository in my service (in same module) with this token.\n\nWhat I don't understand is how `@InjectRepository()` works internally, for example:\n\n```\nconstructor(\n @InjectRepository(TaskRepository)\n private taskRepository: TaskRepository,\n ) {}\n```\n\nHow is `InjectRepository` custom decorator (which should have been created with `createParamDecorator`) able to inject a provider registered in a module? I researched and found out that `createParamDecorator` doesn't have ability to use DI. If `createParamDecorator` just creates a new `TaskRepository` instance and returns it, then why do I need to import `TypeOrmModule.forFeature` in module? Can someone explain how this works internally? Thanks!\n\n========================================\n\nCode:\n```text\nimports: [\n TypeOrmModule.forFeature([TaskRepository]),\n],\n```\n\n```text\nconstructor(\n @InjectRepository(TaskRepository)\n private taskRepository: TaskRepository,\n ) {}\n```\n\n```text\n@InjectRepository()\n```\n\n```text\nInjectRepository\n```\n\n```text\ncreateParamDecorator\n```\n\n```text\ncreateParamDecorator\n```\n\n```text\ncreateParamDecorator\n```\n\n```text\nTaskRepository\n```\n\n```text\nTypeOrmModule.forFeature\n```\n\n```text\n@InjectRespoitory()\n```\n\n```text\ncreateParamDecorator()\n```\n\n```text\ncreateParamDecorator\n```\n\n```text\nreq\n```\n\n```text\ncontext\n```\n\n```text\npayload\n```\n\n```text\nExecutionContext\n```\n\n```text\n@InjectRepository()\n```\n\n```text\n@Inject()\n```\n\n```text\n<EntityName>Repository\n```\n\n```text\nconnection\n```\n\n```text\nTypeormModule.forFeature()\n```\n\n```text\n<EntityName>\n```\n\n```text\n@InjectRepository()\n```\n\n```text\n@Inject()\n```\n\n```text\n@InjectRepository()\n```\n\n```text\nTypeormModule.forFeature()\n```\n\n```text\n@InjectRepository()\n```\n\n```text\nTypeormModule.forFeature()\n```\n\n```text\nRepository<TaskEntity>\n```\n\n```text\nRepository\n```\n\n```text\n@InjectRepository()\n```\n\n========================================\n\nComments:\n- Thank you for great explanation! Actually I found the file on github: github.com/nestjs/typeorm/blob/… and kind of understood how it works but your explanation made everything much clearer","metadata":{"transformedAt":"2026-08-18T18:33:44.689Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":31,"totalLines":162,"estimatedTokens":599}}89{"id":"stack-43747765","source":"stackoverflow","questionId":43747765,"title":"Self-Referencing ManyToMany Relationship TypeORM","tags":["mysql","node.js","orm","typeorm"],"text":"Title: Self-Referencing ManyToMany Relationship TypeORM\nTags: mysql, node.js, orm, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have just started using TypeORM and I'm struggling getting the following relationship to work:\n\nUser->Friends, whereas a Friend is also a User Object.\nMy getters, getFriends & getFriendsInverse are working, however; I do now want to distinguish between the two. In other words; when I perform a mysql join I do not want to do a left join on friends and another one on inverseFriends.\n\nThe getter getFriends() needs to return all friends, regardless of which \"side\" the object I'm on.\n\nDoes that make sense?\n\nThis is my model definition:\n\n```\ngetFriends() {\n // This method should also return inverseFriends;\n // I do not want to return the concat version; this should\n // happen on the database/orm level\n // So I dont want: this.friends.concat(this.inverseFriends) \n return this.friends;\n}\n\n@ManyToMany(type => User, user => user.friendsInverse, {\n cascadeInsert: false,\n cascadeUpdate: false,\n})\n@JoinTable()\nfriends = [];\n\n@ManyToMany(type => User, user => user.friends, {\n cascadeInsert: true,\n cascadeUpdate: true,\n cascadeRemove: false,\n})\nfriendsInverse = [];\n```\n\nI hope someone understands my question :D\nThanks\nMatt\n\n========================================\n\nTop Answer:\nYou can self-reference your relations. Here is an example of a simple directed graph (aka a node can have a parent and multiple children).\n\n```\n@Entity()\nexport class Service extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n \n @Column()\n @Index({ unique: true })\n title: string;\n\n @ManyToOne(type => Service, service => service.children)\n parent: Service;\n\n @OneToMany(type => Service, service => service.parent)\n children: Service[];\n}\n```\n\nAn important note to keep in mind is that these relations are not auto loaded when reading an object from the DB with `find*` functions.\n\nTo actually load them, you have to use query builder at the moment and join them. (You can join multiple levels.) An example:\n\n```\nlet allServices = await this.repository.createQueryBuilder('category')\n .andWhere('category.price IS NULL')\n .innerJoinAndSelect('category.children', 'product')\n .leftJoinAndSelect('product.children', 'addon')\n .getMany();\n```\n\nPlease note how I used different names to reference them (`category`, `product`, and `addon`).\n\n========================================\n\nCode:\n```text\ngetFriends() {\n // This method should also return inverseFriends;\n // I do not want to return the concat version; this should\n // happen on the database/orm level\n // So I dont want: this.friends.concat(this.inverseFriends) \n return this.friends;\n}\n\n@ManyToMany(type => User, user => user.friendsInverse, {\n cascadeInsert: false,\n cascadeUpdate: false,\n})\n@JoinTable()\nfriends = [];\n\n@ManyToMany(type => User, user => user.friends, {\n cascadeInsert: true,\n cascadeUpdate: true,\n cascadeRemove: false,\n})\nfriendsInverse = [];\n```\n\n```text\nFred\n / \\\n Albert Laura\n / \\\n John Foo\n```\n\n```js\nimport { Column, Entity, JoinTable, ManyToMany, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity(UserModel.MODEL_NAME)\nexport class UserModel {\n static MODEL_NAME = 'users';\n\n @PrimaryGeneratedColumn()\n id?: number;\n\n @Column({ type: 'varchar', unique: true, length: 50 })\n username: string;\n\n @Column({ type: 'varchar', length: 50, unique: true })\n email: string;\n\n @ManyToMany(type => UserModel)\n @JoinTable()\n friends: UserModel[];\n\n @Column({ type: 'varchar', length: 300 })\n password: string;\n}\n```\n\n```js\nasync findFriends(id: Id): Promise<UserModel[]> {\n return await this.userORM.query(\n ` SELECT * \n FROM users U\n WHERE U.id <> $1\n AND EXISTS(\n SELECT 1\n FROM users_friends_users F\n WHERE (F.\"usersId_1\" = $1 AND F.\"usersId_2\" = U.id )\n OR (F.\"usersId_2\" = $1 AND F.\"usersId_1\" = U.id )\n ); `,\n [id],\n );\n }\n```\n\n```text\nFoo\n```\n\n```text\nFred\n```\n\n```text\nusers_friends_users\n```\n\n```text\n@Entity()\nexport class Service extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n \n @Column()\n @Index({ unique: true })\n title: string;\n\n @ManyToOne(type => Service, service => service.children)\n parent: Service;\n\n @OneToMany(type => Service, service => service.parent)\n children: Service[];\n}\n```\n\n```text\nlet allServices = await this.repository.createQueryBuilder('category')\n .andWhere('category.price IS NULL')\n .innerJoinAndSelect('category.children', 'product')\n .leftJoinAndSelect('product.children', 'addon')\n .getMany();\n```\n\n```text\nfind*\n```\n\n```text\ncategory\n```\n\n```text\nproduct\n```\n\n```text\naddon\n```\n\n```text\nimport { Column, Entity, JoinTable, ManyToMany, PrimaryGeneratedColumn, JoinTable } from 'typeorm';\n\n@Entity(UserModel.MODEL_NAME)\nexport class UserModel {\n static MODEL_NAME = 'users';\n\n @PrimaryGeneratedColumn()\n id?: number;\n\n @Column({ type: 'varchar', unique: true, length: 50 })\n username: string;\n\n @Column({ type: 'varchar', length: 50, unique: true })\n email: string;\n\n @ManyToMany(type => UserModel)\n @JoinTable({ joinColumn: { name: 'users_id_1' } })\n friends: UserModel[];\n\n @Column({ type: 'varchar', length: 300 })\n password: string;\n}\n```\n\n```text\njoinColumn\n```\n\n```text\nJoinTable\n```\n\n```text\nusers_friends_users\n```\n\n```text\nuser_id_1\n```\n\n```text\nuser_id_2\n```\n\n```text\nusers_friends_users\n```\n\n```text\nfriends[19]\n```\n\n```text\nusers_friends_users\n```\n\n```text\nfriends[]\n```\n\n```text\nRaw Query\n```\n\n========================================\n\nComments:\n- Please mark my answer as correct if it answers your question. Thanks in advance :)\n- hi, i already doing this, but when doing a production release the entity Service cannot identify it self\n- i'm not sure if this applies in this case. You are talking about a tree structure, but this would be more like a net. There is no 1 parent, x children.\n- Yep, definitely this does not work. See my answer for the specific case of the original question of this post.\n- From this answer, isn't it better to manually implement this with an empty table as you would in SQL with a junction table? Or am I missing the benefit of using @ManyToMany?\n- @talfreds using that annotation will create the junction table automatically for you. That is the magic of the ORM and its annotations. It will also, thanks to all of these annotations, automatically generate the migration files with raw queries, which is kind of crazy. I've tried generating a migration after making relatively big/complex changes to my schemas, and it works like a charm.\n- @talfreds also, using these annotations consistently instead of making part automatically and part manually will help the ORM keep track of everything.\n- Ah, I meant like this: stackoverflow.com/questions/55253563/… but I see your point, using @ManyToMany is better if you don't require an extra field or something\n- This works perfectly. I don't suppose you can also show how you performed an update, since by default we can end up with duplicate rows with usersId_1 and usersId_2 inverted.\n- @tarmes I don't really remember, but I think that I basically checked if that friend connection was already in the DB when adding a new friend. This should prevented duplicates. Maybe apart from this, and as a precaution measure, you can have a cron that checks the table and cleans it of duplicates.","metadata":{"transformedAt":"2026-08-18T18:33:44.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":292,"estimatedTokens":1861}}90{"id":"stack-53680665","source":"stackoverflow","questionId":53680665,"title":"nestjs / TypeOrm database transaction","tags":["nestjs","typeorm"],"text":"Title: nestjs / TypeOrm database transaction\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nAssuming we have 2 services, A and B.\nService A has a function doing the following:\n\n- Validate the data\n\n- Call a service B function, that makes changes to the database\n\n- Do some more stuff\n\n- Do changes to the database\n\nNow, let's assume that one of the following, steps 3 or 4 failed.\nSince service B made changes in the database, those changes are still there.\n\nIs there any way of rolling the database back in this case? I though about database transactions, but I couldn't find any way to do that in nest js, although it is supported by TypeOrm, it doesn't look natural to nest.\nIf not, I am now \"stuck\" with the changes occured by service B, but without the changes should have happen by A.\n\nThanks a lot.\n\n========================================\n\nTop Answer:\ntypeorm-transactional uses CLS (Continuation Local Storage) to handle and propagate transactions between different repositories and service methods.\n\n```\n@Injectable()\nexport class PostService {\n constructor(\n private readonly authorRepository: AuthorRepository,\n private readonly postRepository: PostRepository,\n ) {}\n\n @Transactional() // will open a transaction if one doesn't already exist\n async createPost(authorUsername: string, message: string): Promise {\n const author = await this.authorRepository.create({ username: authorUsername });\n return this.postRepository.save({ message, author_id: author.id });\n }\n}\n```\n\n========================================\n\nCode:\n```text\ngetConnection().transaction(entityManager -> {\n service1.doStuff1(entityManager);\n service2.doStuff2(entityManager);\n});\n```\n\n```text\nEntityManager\n```\n\n```text\nQueryRunner\n```\n\n```text\nEntityManager\n```\n\n```text\nRepository\n```\n\n```text\nEntityManager\n```\n\n```js\n@Injectable()\nclass MyService {\n // 1. Inject the Typeorm Connection\n constructor(@InjectConnection() private connection: Connection) { }\n\n async findById(id: number): Promise<Thing> {\n return new Promise(resolve => {\n // 2. Do your business logic\n this.connection.transaction(async entityManager => {\n resolve(\n await entityManager.findOne(Thing, id, {\n lock: { mode: 'pessimistic_write' },\n }),\n );\n });\n });\n }\n}\n```\n\n```text\nNestJS\n```\n\n```text\nConnection\n```\n\n```text\n.transaction\n```\n\n```text\nentityManager\n```\n\n```text\n.transaction\n```\n\n```js\n@Injectable()\nexport class PostService {\n constructor(\n private readonly authorRepository: AuthorRepository,\n private readonly postRepository: PostRepository,\n ) {}\n\n @Transactional() // will open a transaction if one doesn't already exist\n async createPost(authorUsername: string, message: string): Promise<Post> {\n const author = await this.authorRepository.create({ username: authorUsername });\n return this.postRepository.save({ message, author_id: author.id });\n }\n}\n```\n\n```text\nfunction assignChildToParent(nestedObj, parentIdKey) {\n const parentMap = {};\n\n for (const prop in nestedObj) {\n if (nestedObj.hasOwnProperty(prop)) {\n const obj = nestedObj[prop];\n const parentId = obj[parentIdKey];\n\n parentMap[prop] = { ...obj, children: {} };\n\n if (parentId !== null && parentMap.hasOwnProperty(parentId)) {\n parentMap[parentId].children[prop] = parentMap[prop];\n }\n }\n }\n\n const result = {};\n\n for (const prop in parentMap) {\n if (parentMap.hasOwnProperty(prop) && parentMap[prop][parentIdKey] === null) {\n result[prop] = parentMap[prop];\n }\n }\n\n return result;\n}\n\nconst nestedObj = {\n obj1: { name: 'Parent 1', parentId: null },\n obj2: { name: 'Parent 2', parentId: 'obj1' },\n obj3: { name: 'Parent 3', parentId: null }\n};\n\nconst parentIdKey = 'parentId';\n\nconst result = assignChildToParent(nestedObj, parentIdKey);\nconsole.log(result);\n```\n\n========================================\n\nComments:\n- While this is a solution, there's an obvious issue: Every service method will have to accept an EntityManager parameter. And if those services use other injectables, like data-access objects (DAOs), then the service methods will need to pass the EntityManager instance down the chain even further (e.g. to DAO methods). I think this is an obvious and impulsive solution--a solution that works!--but it adds significant boilerplate code and doesn't fit well with DI and IoC.\n- @avejidah you don't have ThreadLocal in TypeScript Node so you cannot store a context instance where you keep reference of the entity manager along all the services. Singleton won't work either as you have an entity manager per request (many ones are processed together in node thanks to event queue). The only way to keep an entity manager everywhere would be to store it in some way in the execution context of NestJS but you would loose manual entity manager usage and manual transaction management which can be needed.\n- I personally keep the parameter and use a decorator along the method to inject a new entity manager if it is null so I never have to worry about initializing it. Keeping explicit transaction management is more important to me than code sugar, I don't find it boilerplate personally.\n- @zenbeni could you a code snippet? which decorator are you using? maybe `@TransactionManager`?\n- Any suggestions if I use nestjsx/crud\n- This is the most elegant way to do it.\n- This, IMO, is the most succinct approach\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:44.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":183,"estimatedTokens":1416}}91{"id":"stack-61365822","source":"stackoverflow","questionId":61365822,"title":"TypeORM Query Builder Returning Empty Array When Raw SQL Works","tags":["postgresql","typescript","typeorm"],"text":"Title: TypeORM Query Builder Returning Empty Array When Raw SQL Works\nTags: postgresql, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm attempting to run the following type of query using `createQueryBuilder`. I've verified that all of my entities are properly created and joined. However, running the following returns an empty array: \n\n```\nlet apiKey = await getConnection()\n .createQueryBuilder()\n .from(ApiKey, \"apiKey\")\n .innerJoinAndSelect(\"apiKey.site\", \"site\")\n .where(\"site.domain = :domain\", { domain: \"mysitename.com\" })\n .andWhere(\"apiKey.key = :key\", { key })\n .getMany()\n```\n\nBut! When I replace `getMany()` with `getSql()`, copy the raw SQL and run it, it works! I get the result I expected:\n\n```\nSELECT \"site\".\"id\" AS \"site_id\", \"site\".\"domain\" AS \"site_domain\", \"site\".\"name\" AS \"site_name\", \"site\".\"createdAt\" AS \"site_createdAt\", \"site\".\"apiKeyId\" AS \"site_apiKeyId\", \"site\".\"userId\" AS \"site_userId\" FROM \"api_key\" \"apiKey\" INNER JOIN \"site\" \"site\" ON \"site\".\"id\"=\"apiKey\".\"siteId\" WHERE \"site\".\"domain\" = 'mysitename.com'\n```\n\nIs there any thing obviously wrong with how I'm trying to build this query? \n\nThanks in advance for the help!\n\n========================================\n\nTop Answer:\nYou need to select the repository\n\n```\nlet apiKey = await getConnection()\n .getRepository(ApiKey) // <-----------\n .createQueryBuilder('apiKey') // <-----------\n .innerJoinAndSelect(\"apiKey.site\", \"site\")\n .where(\"site.domain = :domain\", { domain: \"mysitename.com\" })\n .andWhere(\"apiKey.key = :key\", { key })\n .getMany()\n```\n\n========================================\n\nCode:\n```text\nlet apiKey = await getConnection()\n .createQueryBuilder()\n .from(ApiKey, \"apiKey\")\n .innerJoinAndSelect(\"apiKey.site\", \"site\")\n .where(\"site.domain = :domain\", { domain: \"mysitename.com\" })\n .andWhere(\"apiKey.key = :key\", { key })\n .getMany()\n```\n\n```text\nSELECT \"site\".\"id\" AS \"site_id\", \"site\".\"domain\" AS \"site_domain\", \"site\".\"name\" AS \"site_name\", \"site\".\"createdAt\" AS \"site_createdAt\", \"site\".\"apiKeyId\" AS \"site_apiKeyId\", \"site\".\"userId\" AS \"site_userId\" FROM \"api_key\" \"apiKey\" INNER JOIN \"site\" \"site\" ON \"site\".\"id\"=\"apiKey\".\"siteId\" WHERE \"site\".\"domain\" = 'mysitename.com'\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\ngetMany()\n```\n\n```text\ngetSql()\n```\n\n```text\nlet apiKey = await getConnection()\n .getRepository(ApiKey) // <-----------\n .createQueryBuilder('apiKey') // <-----------\n .innerJoinAndSelect(\"apiKey.site\", \"site\")\n .where(\"site.domain = :domain\", { domain: \"mysitename.com\" })\n .andWhere(\"apiKey.key = :key\", { key })\n .getMany()\n```\n\n========================================\n\nComments:\n- This worked! Do you have any resources/docs on how I'd craft that query to return an entity (or entities) instead of the raw results?\n- May be to some it would help, Can refer the docs for understanding getRawMany()\n- Great idea @Zaker I'll update to include that reference","metadata":{"transformedAt":"2026-08-18T18:33:44.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":87,"estimatedTokens":733}}92{"id":"stack-59437390","source":"stackoverflow","questionId":59437390,"title":"TypeORM jsonb array column","tags":["node.js","postgresql","typescript","orm","typeorm"],"text":"Title: TypeORM jsonb array column\nTags: node.js, postgresql, typescript, orm, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm working on a node micro-service, orm and db are respectively `typeorm` and `postgresql`\n\nI'm trying to create `jsonb` array column but I'm probably not doing it the correct way.\n\n**Notes**\n\n- I would normally have accomplished this by simply adding a simple extra entity and relation. In this case I have been asked to use the `jsonb` type in oder to be able to amend the interface without catering for schema changes.\n\n- Storing a simple list of indexed ids would be equally good enough for now.\n\n- I am not sure I should be using the `array: true` column option. I made a few attempts to use a plain `jsonb` object without succeeding ( `\"{}\"::jsonb` ).\n\n**My aim:**\n\nTo store an array of objects with an **indexed** `id` column, and to be able to add and remove ids. In case this is not possible a flat indexed string array would do.\n\ne.g:\n\n`[ {id: 'some-uuid-000'}, {id: 'some-uuid-001'}, ... ]`\n\nor:\n\n`['some-uuid-000', 'some-uuid-001', 'some-uuid-002']`\n\n**Code:**\n\nMy column definition :\n\n```\n@Column({\n type: 'jsonb',\n array: true,\n default: () => 'ARRAY[]::jsonb[]',\n nullable: false,\n })\n public users: Array = [];\n```\n\nI manage to fetch the empty array with\n\n```\nconst group = await repo.findOneOrFail({ id: groupId });\nconsole.log('>>>>>', group.users);\n```\n\nwhich outputs:\n\n```\n>>>>> []\n```\n\nwhen trying to add an item to the array and persist as below\n\n```\nreturn repo.update(groupId, { users: [...group.users, { id: userId }] });\n```\n\nI get the following output:\n\n```\n2019-12-21 14:40:44.088 UTC [556] ERROR: malformed array literal: \"[{\"id\":\"cc135b8a-b6ed-4cd7-99fc-396228e74509\"}]\"\n2019-12-21 14:40:44.088 UTC [556] DETAIL: \"[\" must introduce explicitly-specified array dimensions.\n2019-12-21 14:40:44.088 UTC [556] STATEMENT: UPDATE \"group\" SET \"users\" = $2, \"created_at\" = CURRENT_TIMESTAMP WHERE \"id\" IN ($1)\n(node:5050) UnhandledPromiseRejectionWarning: QueryFailedError: malformed array literal: \"[{\"id\":\"cc135b8a-b6ed-4cd7-99fc-396228e74509\"}]\"\n```\n\nThe output error tells me that the configuration must be wrong as postgres seems to be provided with a plain objects array while expecting a different format/notation. I haven't found much details about this sort of scenarios in the docs.\n\n========================================\n\nTop Answer:\n```\n@Column('simple-array', { nullable: true })\n toId!: string[];\n```\n\n========================================\n\nCode:\n```text\n@Column({\n type: 'jsonb',\n array: true,\n default: () => 'ARRAY[]::jsonb[]',\n nullable: false,\n })\n public users: Array<{ id: string }> = [];\n```\n\n```text\nconst group = await repo.findOneOrFail({ id: groupId });\nconsole.log('>>>>>', group.users);\n```\n\n```text\n>>>>> []\n```\n\n```text\nreturn repo.update(groupId, { users: [...group.users, { id: userId }] });\n```\n\n```text\n2019-12-21 14:40:44.088 UTC [556] ERROR: malformed array literal: \"[{\"id\":\"cc135b8a-b6ed-4cd7-99fc-396228e74509\"}]\"\n2019-12-21 14:40:44.088 UTC [556] DETAIL: \"[\" must introduce explicitly-specified array dimensions.\n2019-12-21 14:40:44.088 UTC [556] STATEMENT: UPDATE \"group\" SET \"users\" = $2, \"created_at\" = CURRENT_TIMESTAMP WHERE \"id\" IN ($1)\n(node:5050) UnhandledPromiseRejectionWarning: QueryFailedError: malformed array literal: \"[{\"id\":\"cc135b8a-b6ed-4cd7-99fc-396228e74509\"}]\"\n```\n\n```text\ntypeorm\n```\n\n```text\npostgresql\n```\n\n```text\njsonb\n```\n\n```text\njsonb\n```\n\n```text\narray: true\n```\n\n```text\njsonb\n```\n\n```text\n\"{}\"::jsonb\n```\n\n```text\nid\n```\n\n```text\n[ {id: 'some-uuid-000'}, {id: 'some-uuid-001'}, ... ]\n```\n\n```text\n['some-uuid-000', 'some-uuid-001', 'some-uuid-002']\n```\n\n```text\n@Column({\n type: 'jsonb',\n array: false,\n default: () => \"'[]'\",\n nullable: false,\n })\n public users!: Array<{ id: string }>;\n```\n\n```text\narray\n```\n\n```text\njsonb[]\n```\n\n```text\njsonb\n```\n\n```text\njsonb_set\n```\n\n```text\n@Column('simple-array', { nullable: true })\n toId!: string[];\n```\n\n========================================\n\nComments:\n- One will still get error, error: malformed array literal: \"[]\"\n- Your answer could be improved by adding more information on what the code does and how it helps the OP.\n- simple-array is not applicable here because the OP is trying to store JSON in Postgres and not just regular strings. `simple-array` has the caveat that the values cannot contain commas(,).","metadata":{"transformedAt":"2026-08-18T18:33:44.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":191,"estimatedTokens":1114}}93{"id":"stack-72957962","source":"stackoverflow","questionId":72957962,"title":"How to extend TypeORM repository in NestJS 9 (TypeORM 3.+)","tags":["node.js","dependency-injection","orm","nestjs","typeorm"],"text":"Title: How to extend TypeORM repository in NestJS 9 (TypeORM 3.+)\nTags: node.js, dependency-injection, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nPreviously, TypeORM repository could be extended and injected directly into services, e.g.:\n\n```\nimport { User } from './entities/user.entity';\nimport { EntityRepository, Repository } from 'typeorm';\n\n@EntityRepository(User)\nexport class UsersRepo extends Repository {\n // my custom repo methods\n}\n```\n\n```\nimport { Injectable } from '@nestjs/common'\nimport { UsersRepo } from './users.repo';\n\n@Injectable()\nexport class UsersService {\n constructor(private readonly usersRepo: UsersRepo) {}\n}\n```\n\nBut since version 3.0.0 TypeORM does not support repository extending via inheritance.\n\nHow to achieve such behavior in NestJS 9 (which depends on TypeORM 3.+)? The only solution I came up with is to add custom methods to the service layer. But I would like to keep all ORM-related methods (query, aggregations, etc.) in the repository layer.\n\n========================================\n\nTop Answer:\nHope helpful for you:\n\n```\nimport { DataSource, Repository } from 'typeorm';\nimport { EntityTarget } from 'typeorm/common/EntityTarget';\n\nexport class GenericRepository extends Repository {\n constructor(target: EntityTarget, dataSource: DataSource) {\n super(target, dataSource.createEntityManager());\n }\n\n async someCommonMethod() {\n return {};\n }\n}\n```\n\n```\nimport { DataSource } from 'typeorm';\nimport { User } from '../../entities/User';\nimport { Injectable } from '@nestjs/common';\nimport { GenericRepository } from '../common/generic.repository';\n\n@Injectable()\nexport class UserRepository extends GenericRepository {\n constructor(private dataSource: DataSource) {\n super(User, dataSource.createEntityManager());\n }\n}\n```\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { User } from '../../entities/User';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { UsersRepository } from './users.repository';\n\n@Injectable()\nexport class UsersService {\n constructor(\n @InjectRepository(User)\n private readonly usersRepository: UsersRepository,\n ) {}\n}\n```\n\n========================================\n\nCode:\n```js\nimport { User } from './entities/user.entity';\nimport { EntityRepository, Repository } from 'typeorm';\n\n@EntityRepository(User)\nexport class UsersRepo extends Repository<User> {\n // my custom repo methods\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common'\nimport { UsersRepo } from './users.repo';\n\n@Injectable()\nexport class UsersService {\n constructor(private readonly usersRepo: UsersRepo) {}\n}\n```\n\n```js\n@Injectable()\nexport class UserRepository extends Repository<UserEntity> {\n\n\n constructor(\n @InjectRepository(UserEntity)\n repository: Repository<UserEntity>\n ) {\n super(repository.target, repository.manager, repository.queryRunner);\n }\n}\n```\n\n```text\n\"@nestjs/typeorm\": \"^9.0.0\"\n```\n\n```text\nconstructor(\n @InjectRepository(UserEntity)\n private readonly repository: BaseRepository<UserEntity>,\n) {}\n```\n\n```text\n@Module({\n imports: [TypeOrmModule.forFeature([UserEntity])],\n exports: [UserService],\n providers: [UserService],\n})\nexport class UserModule {}\n```\n\n```text\nimport { DataSource, Repository } from 'typeorm';\nimport { EntityTarget } from 'typeorm/common/EntityTarget';\n\nexport class GenericRepository<T> extends Repository<T> {\n constructor(target: EntityTarget<T>, dataSource: DataSource) {\n super(target, dataSource.createEntityManager());\n }\n\n async someCommonMethod() {\n return {};\n }\n}\n```\n\n```text\nimport { DataSource } from 'typeorm';\nimport { User } from '../../entities/User';\nimport { Injectable } from '@nestjs/common';\nimport { GenericRepository } from '../common/generic.repository';\n\n@Injectable()\nexport class UserRepository extends GenericRepository<User> {\n constructor(private dataSource: DataSource) {\n super(User, dataSource.createEntityManager());\n }\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { User } from '../../entities/User';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { UsersRepository } from './users.repository';\n\n\n@Injectable()\nexport class UsersService {\n constructor(\n @InjectRepository(User)\n private readonly usersRepository: UsersRepository,\n ) {}\n}\n```\n\n```js\nimport { Repository } from 'typeorm';\nimport { User } from './user.entity';\n\nexport interface ExtendedUserRepository extends Repository<User> {\n findByUsername(username: string): Promise<User | undefined>;\n findByEmail(email: string): Promise<User | undefined>;\n}\n\nexport const extendedUserRepository = {\n findByUsername(this: Repository<User>, username: string) {\n return this.findOne({ where: { username } });\n },\n findByEmail(this: Repository<User>, email: string) {\n return this.findOne({ where: { email } });\n }\n};\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\nimport { User } from './user.entity';\nimport { extendedUserRepository, ExtendedUserRepository } from './user.repository';\n\n@Injectable()\nexport class UserService {\n private userRepository: ExtendedUserRepository;\n\n constructor(\n @InjectRepository(User)\n private readonly repository: Repository<User>\n ) {\n this.userRepository = this.repository.extend(extendedUserRepository);\n }\n\n // Use this.userRepository to access custom methods\n}\n```\n\n========================================\n\nComments:\n- For some reason when I try to use my custom repository outside my module, this method breaks down..\n- well, did you export it from your module?\n- How would this work if I want to use `userRepository` in multiple services? Is calling `extend` on the same instance from multiple constructors safe?\n- @ArnoHilke As far as I understand, it should be fine. I've also been using this method pretty extensively for a while now and never run into a problem.","metadata":{"transformedAt":"2026-08-18T18:33:44.689Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":230,"estimatedTokens":1482}}94{"id":"stack-48851140","source":"stackoverflow","questionId":48851140,"title":"How to handle TypeORM entity field unique validation error in NestJS?","tags":["typeorm","nestjs"],"text":"Title: How to handle TypeORM entity field unique validation error in NestJS?\nTags: typeorm, nestjs\nSource: Stack Overflow\n\nQuestion:\nI've set a custom unique validator decorator on my TypeORM entity field email. NestJS has dependency injection, but the service is not injected.\n\nThe error is:\n\n```\nTypeError: Cannot read property 'findByEmail' of undefined\n```\n\nAny help on implementing a custom email validator?\n\n`user.entity.ts`:\n\n```\n@Column()\n@Validate(CustomEmail, {\n message: \"Title is too short or long!\"\n})\n@IsEmail()\nemail: string;\n```\n\nMy `CustomEmail` validator is\n\n```\nimport {ValidatorConstraint, ValidatorConstraintInterface, \nValidationArguments} from \"class-validator\";\nimport {UserService} from \"./user.service\";\n\n@ValidatorConstraint({ name: \"customText\", async: true })\nexport class CustomEmail implements ValidatorConstraintInterface {\n\n constructor(private userService: UserService) {}\n async validate(text: string, args: ValidationArguments) {\n\n const user = await this.userService.findByEmail(text);\n return !user; \n }\n\n defaultMessage(args: ValidationArguments) { \n return \"Text ($value) is too short or too long!\";\n }\n}\n```\n\nI know I could set `unique` in the `Column` options\n\n```\n@Column({\n unique: true\n})\n```\n\nbut this throws a mysql error and the `ExceptionsHandler` that crashes my app, so I can't handle it myself...\n\nThankx!\n\n========================================\n\nTop Answer:\nI can propose 2 different approaches here, the first one catches the constraint violation error locally without additional request, and the second one uses a global error filter, catching such errors in the entire application. I personally use the latter.\n\n### Local no-db request solution\n\nNo need to make additional database request. You can catch the error violating the unique constraint and throw any `HttpException` you want to the client. In `users.service.ts`:\n\n```\npublic create(newUser: Partial): Promise {\n return this.usersRepository.save(newUser).catch((e) => {\n if (/(email)[\\s\\S]+(already exists)/.test(e.detail)) {\n throw new BadRequestException(\n 'Account with this email already exists.',\n );\n }\n return e;\n });\n }\n```\n\nWhich will return:\n\nhttps://i.sstatic.net/KntnY.png\n\n### Global error filter solution\n\nOr even create a global QueryErrorFilter:\n\n```\n@Catch(QueryFailedError)\nexport class QueryErrorFilter extends BaseExceptionFilter {\n public catch(exception: any, host: ArgumentsHost): any {\n const detail = exception.detail;\n if (typeof detail === 'string' && detail.includes('already exists')) {\n const messageStart = exception.table.split('_').join(' ') + ' with';\n throw new BadRequestException(\n exception.detail.replace('Key', messageStart),\n );\n }\n return super.catch(exception, host);\n }\n}\n```\n\nThen in `main.ts`:\n\n```\nasync function bootstrap() {\n const app = await NestFactory.create(/**/);\n /* ... */\n const { httpAdapter } = app.get(HttpAdapterHost);\n app.useGlobalFilters(new QueryErrorFilter(httpAdapter));\n /* ... */\n await app.listen(3000);\n}\nbootstrap();\n```\n\nThis will give generic `$table entity with ($field)=($value) already exists.` error message. Example:\n\nhttps://i.sstatic.net/7TzX2.png\n\n========================================\n\nCode:\n```text\nTypeError: Cannot read property 'findByEmail' of undefined\n```\n\n```text\n@Column()\n@Validate(CustomEmail, {\n message: \"Title is too short or long!\"\n})\n@IsEmail()\nemail: string;\n```\n\n```text\nimport {ValidatorConstraint, ValidatorConstraintInterface, \nValidationArguments} from \"class-validator\";\nimport {UserService} from \"./user.service\";\n\n@ValidatorConstraint({ name: \"customText\", async: true })\nexport class CustomEmail implements ValidatorConstraintInterface {\n\n constructor(private userService: UserService) {}\n async validate(text: string, args: ValidationArguments) {\n\n const user = await this.userService.findByEmail(text);\n return !user; \n }\n\n defaultMessage(args: ValidationArguments) { \n return \"Text ($value) is too short or too long!\";\n }\n}\n```\n\n```text\n@Column({\n unique: true\n})\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nCustomEmail\n```\n\n```text\nunique\n```\n\n```text\nColumn\n```\n\n```text\nExceptionsHandler\n```\n\n```js\npublic create(newUser: Partial<UserEntity>): Promise<UserEntity> {\n return this.usersRepository.save(newUser).catch((e) => {\n if (/(email)[\\s\\S]+(already exists)/.test(e.detail)) {\n throw new BadRequestException(\n 'Account with this email already exists.',\n );\n }\n return e;\n });\n }\n```\n\n```js\n@Catch(QueryFailedError)\nexport class QueryErrorFilter extends BaseExceptionFilter {\n public catch(exception: any, host: ArgumentsHost): any {\n const detail = exception.detail;\n if (typeof detail === 'string' && detail.includes('already exists')) {\n const messageStart = exception.table.split('_').join(' ') + ' with';\n throw new BadRequestException(\n exception.detail.replace('Key', messageStart),\n );\n }\n return super.catch(exception, host);\n }\n}\n```\n\n```js\nasync function bootstrap() {\n const app = await NestFactory.create(/**/);\n /* ... */\n const { httpAdapter } = app.get(HttpAdapterHost);\n app.useGlobalFilters(new QueryErrorFilter(httpAdapter));\n /* ... */\n await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\nHttpException\n```\n\n```text\nusers.service.ts\n```\n\n```text\nmain.ts\n```\n\n```text\n$table entity with ($field)=($value) already exists.\n```\n\n```text\n@Entity()\nexport class MyEntity extends BaseEntity{ \n @Column({unique:true}) name:string; \n}\n\nexport abstract class BaseDataService<T> {\n\n constructor(protected readonly repo: Repository<T>) {}\n\n private async isUnique(t: any) {\n const uniqueColumns = this.repo.metadata.uniques.map(\n (e) => e.givenColumnNames[0]\n );\n\n for (const u of uniqueColumns) {\n const count = await this.repo.count({ where: { [u]: ILike(t[u]) } });\n if (count > 0) {\n throw new UnprocessableEntityException(`${u} must be unique!`);\n }\n }\n }\n\n async save(body: DeepPartial<T>) {\n await this.isUnique(body);\n try {\n return await this.repo.save(body);\n } catch (err) {\n throw new UnprocessableEntityException(err.message);\n }\n }\n\n\n\n async update(id: number, updated: QueryDeepPartialEntity<T>) {\n await this.isUnique(updated)\n try {\n return await this.repo.update(id, updated);\n } catch (err) {\n throw new UnprocessableEntityException(err.message);\n }\n }\n}\n```\n\n```js\nimport {\n Catch,\n ArgumentsHost,\n BadRequestException,\n HttpException,\n} from '@nestjs/common';\nimport { BaseExceptionFilter } from '@nestjs/core';\nimport { QueryFailedError } from 'typeorm';\n\ntype ExceptionType = { detail: string; table: string };\n\n@Catch(QueryFailedError)\nexport class QueryErrorFilter extends BaseExceptionFilter<\n HttpException | ExceptionType\n> {\n public catch(exception: ExceptionType, host: ArgumentsHost): void {\n const { detail = null } = exception || {};\n\n if (\n !detail ||\n typeof detail !== 'string' ||\n // deepcode ignore AttrAccessOnNull: <False positive>\n !detail.includes('already exists')\n ) {\n return super.catch(exception, host);\n } // else\n\n /**\n * this regex transform the message `(phone)=(123)` to a more intuitive `with phone: \"123\"` one,\n * the regex is long to prevent mistakes if the value itself is ()=(), for example, (phone)=(()=())\n */\n\n const extractMessageRegex =\n /\\((.*?)(?:(?:\\)=\\()(?!.*(\\))(?!.*\\))=\\()(.*?)\\)(?!.*\\)))(?!.*(?:\\)=\\()(?!.*\\)=\\()((.*?)\\))(?!.*\\)))/;\n\n const messageStart = `${exception.table.split('_').join(' ')} with`;\n\n /** prevent Regex DoS, doesn't treat messages longer than 200 characters */\n const exceptionDetail =\n exception.detail.length <= 200\n ? exception.detail.replace(extractMessageRegex, 'with $1: \"$3\"')\n : exception.detail;\n\n super.catch(\n new BadRequestException(exceptionDetail.replace('Key', messageStart)),\n host,\n );\n }\n}\n```\n\n```js\nasync function bootstrap() {\n const app = await NestFactory.create(/**/);\n /* ... */\n const { httpAdapter } = app.get(HttpAdapterHost);\n app.useGlobalFilters(new QueryErrorFilter(httpAdapter));\n /* ... */\n await app.listen(3000);\n}\nbootstrap();\n```\n\n========================================\n\nComments:\n- You cannot inject dependencies inside `ValidatorConstraint` class. It's not a part of the Nest container.\n- For custom validator implementation check this answer.\n- You can perform that check using pipes or a middleware(not recommended if you intend to reuse app wide) instead of the user service to keep to S(Single Responsibility Principle) in the SOLID design principle.\n- I think doing this at a service level is the only way to achieve this. If you use pipes (custom validators) you'll reach a point where if you want to `PATCH` an existing record with a value that already exists, there's no way to check whether that value belongs to the record itself (no error) or another record (throws error). In Ruby on Rails it's literally one line, but this is NestJS so it takes a lot longer.\n- Seems like a good solution imho, especially the global filter. Got it working using exception = new BadRequestException(...) instead of a throw, throwing it right away did cause a loss of every single exceptions returned to the client.\n- interesting solution, but in my case makes this request `SELECT COUNT(1) AS \"cnt\" FROM \"users\" \"User\"` and obviously gets all count of users, not sure why","metadata":{"transformedAt":"2026-08-18T18:33:44.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":363,"estimatedTokens":2364}}95{"id":"stack-40880447","source":"stackoverflow","questionId":40880447,"title":"How to inject an asynchronous dependency in inversify?","tags":["node.js","typescript","inversion-of-control","inversifyjs","typeorm"],"text":"Title: How to inject an asynchronous dependency in inversify?\nTags: node.js, typescript, inversion-of-control, inversifyjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have TypeScript application and I'm using Inversify for IoC.\n\nI have a connection class:\n\n```\n'use strict';\nimport { injectable } from 'inversify';\nimport { createConnection, Connection } from \"typeorm\";\nimport { Photo, PhotoMetadata, Author, Album } from '../index';\n\n@injectable()\nclass DBConnectionManager {\n\n public createPGConnection(): Promise {\n return createConnection({\n driver: {\n type: \"postgres\",\n host: \"host\",\n port: 5432,\n username: \"username\",\n password: \"password\",\n database: \"username\"\n },\n entities: [\n Photo, PhotoMetadata, Author, Album\n ],\n autoSchemaSync: true,\n });\n\n }\n\n}\n\nexport { DBConnectionManager };\n```\n\nAfter I created my connection I want to bind a connection into my container:\n\n```\nkernel.bind('DefaultConnection').toConstantValue(getConnectionManager().get());\n```\n\nand then I want to inject it into another class:\n\n```\nimport { injectable, inject } from 'inversify';\nimport { Connection, FindOptions } from \"typeorm\";\nimport { IGenericRepository, ObjectType } from '../index';\n\n @injectable()\n class GenericRepository implements IGenericRepository {\n\n private connection: Connection;\n private type: ObjectType;\n\n constructor( @inject('DefaultConnection') connection: Connection) {\n this.connection = connection;\n }\n```\n\nSo in my container configuration how can I bind DefaultConnection that needs to wait for CreateConnection \nI can do with async and wait but I'm wonder if there is a cleaner way to achive this in inversify\n\n========================================\n\nTop Answer:\nJust create connection at application startup and bind already connected instance, usually you don't really need to defer connection.\n\n========================================\n\nCode:\n```text\n'use strict';\nimport { injectable } from 'inversify';\nimport { createConnection, Connection } from \"typeorm\";\nimport { Photo, PhotoMetadata, Author, Album } from '../index';\n\n@injectable()\nclass DBConnectionManager {\n\n public createPGConnection(): Promise<Connection> {\n return createConnection({\n driver: {\n type: \"postgres\",\n host: \"host\",\n port: 5432,\n username: \"username\",\n password: \"password\",\n database: \"username\"\n },\n entities: [\n Photo, PhotoMetadata, Author, Album\n ],\n autoSchemaSync: true,\n });\n\n }\n\n}\n\nexport { DBConnectionManager };\n```\n\n```text\nkernel.bind<Connection>('DefaultConnection').toConstantValue(getConnectionManager().get());\n```\n\n```text\nimport { injectable, inject } from 'inversify';\nimport { Connection, FindOptions } from \"typeorm\";\nimport { IGenericRepository, ObjectType } from '../index';\n\n\n @injectable()\n class GenericRepository<T> implements IGenericRepository<T> {\n\n private connection: Connection;\n private type: ObjectType<T>;\n\n constructor( @inject('DefaultConnection') connection: Connection) {\n this.connection = connection;\n }\n```\n\n```text\ncontainer.bind<<DbClient>(\"DbClient\").to(DbClientClass);\n\ncontainer.bind<interfaces.Provider<DbClient>>(\"Provider<DbClient>\")\n .toProvider<DbClient>((context) => {\n return () => {\n return new Promise<DbClient>((resolve, reject) => {\n\n // Create instance\n let dbClient = context.container.get<DbClient>(\"DbClient\");\n\n // Open DB connection\n dbClient.initialize(\"//connection_string\")\n .then(() => {\n resolve(dbClient);\n })\n .catch((e: Error) => {\n reject(e);\n });\n });\n };\n });\n```\n\n```text\nclass UserRepository { \n\n private _db: DbClient;\n private _dbProvider: Provider<DbClient>;\n\n // STEP 1\n // Inject a provider of DbClient to the constructor\n public constructor(\n @inject(\"Provider<DbClient>\") provider: Provider<DbClient>\n ) { \n this._dbProvider = provider;\n }\n\n // STEP 2\n // Get a DB instance using a provider\n // Returns a cached DB instance if it has already been created\n private async getDb() {\n if (this._db) return this._db;\n this._db = await this._dbProvider();\n return Promise.resolve(this._db);\n }\n\n public async getUser(): Promise<Users[]>{\n let db = await this.getDb();\n return db.collections.user.get({});\n }\n\n public async deletetUser(id: number): Promise<boolean>{\n let db = await this.getDb();\n return db.collections.user.delete({ id: id });\n }\n\n}\n```\n\n```text\nclass UserRepository { \n\n // STEP 1\n public constructor(\n @inject(\"Provider<DbClient>\") private provider: Provider<DbClient>\n ) {}\n\n public async getUser(): Promise<Users[]>{\n // STEP 2: (No initialization method is required)\n let db = await this.provider.someFancyNameForProvideValue;\n return db.collections.user.get({});\n }\n}\n```\n\n```text\nconstructor\n```\n\n```text\nasync getDb()\n```\n\n========================================\n\nComments:\n- Is the one phase initialization already implemented? I cannot find any documentation on how to use it\n- This would work if your application runs continuously, and the assumption is that all initialization/dependency building is done before the first request comes in. In the case if you are trying to deploy to Serverless Framework, your application doesn't get initialized until the request comes in. This means you will run into timing/race condition. In my case, the IoC container isn't finished setting up and therefore the application ran into runtime error because the dependencies are building while processing the request.","metadata":{"transformedAt":"2026-08-18T18:33:44.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":218,"estimatedTokens":1502}}96{"id":"stack-58918644","source":"stackoverflow","questionId":58918644,"title":"NestJS - Cannot inject a service into a subscriber","tags":["node.js","typescript","nestjs","typeorm"],"text":"Title: NestJS - Cannot inject a service into a subscriber\nTags: node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a subscriber for NestJS to listen to any create, update or delete events (TypeORM). When one of these events is fired, I'd like to use an injected service in order to create a new revision entry.\n\nHowever, it seems I cannot get the dependency loaded inside of the subscriber and the service comes back as being undefined\n\nKey files:\n\n- EntityModificationSubscriber (Subscriber)\n\n- RevisionEntity (Entity)\n\napp.module.ts\n\n```\n@Module({\n imports: [\n HttpModule,\n TypeOrmModule.forRoot({\n type: (process.env.DB_TYPE as any) || 'postgres',\n host: process.env.DB_HOST || '127.0.0.1',\n port: (process.env.DB_PORT as any) || 5432,\n username: process.env.DB_USER || 'root',\n password: process.env.DB_PASS || '',\n database: process.env.DB_NAME || 'test',\n entities: [join(__dirname, '**/**.entity{.ts,.js}')],\n synchronize: true,\n logging: 'all',\n logger: 'advanced-console',\n subscribers: [EntityModificationSubscriber],\n }),\n TypeOrmModule.forFeature([\n RevisionEntity,\n ]),\n TerminusModule.forRootAsync({\n // Inject the TypeOrmHealthIndicator provided by nestjs/terminus\n inject: [TypeOrmHealthIndicator, MicroserviceHealthIndicator],\n useFactory: (db, msg) => getTerminusOptions(db, msg),\n }),\n GraphQLModule.forRoot({\n debug: true,\n playground: true,\n typePaths: ['./**/*.graphql'],\n }),\n ],\n controllers: [AppController],\n providers: [\n RevisionService,\n EntityModificationSubscriber,\n ],\n})\n```\n\nentity_modification_subscriber.ts\n\n```\nimport {EntitySubscriberInterface, EventSubscriber, InsertEvent, RemoveEvent, UpdateEvent} from 'typeorm';\nimport {RevisionEntity, RevisonEntityStatus} from '../entities/revison.entity';\nimport {RevisionService} from '../services/revisions.service';\nimport {Injectable} from '@nestjs/common';\n\n@Injectable()\n@EventSubscriber()\nexport class EntityModificationSubscriber implements EntitySubscriberInterface {\n\n constructor(private revisionService: RevisionService) {\n }\n\n // tslint:disable-next-line:no-empty\n afterInsert(event: InsertEvent): Promise | void {\n const revision = new RevisionEntity();\n\n revision.action = RevisonEntityStatus.Created;\n }\n\n afterUpdate(event: UpdateEvent): Promise | void {\n }\n\n // tslint:disable-next-line:no-empty\n afterRemove(event: RemoveEvent) {\n // this.revisionService.createRevisionEntry(revision);\n }\n}\n```\n\n========================================\n\nTop Answer:\nHi the problem is that If you want to preform database actions you would have to use: \n\n```\nevent.manager\n```\n\nand Don't use getEntityManager() or getRepository() or any other global function.\nThis is due to a transaction. Save is running in a transaction and your data is saved in a transaction which is not committed yet. But global functions you use are running out of transaction.\n\nmore about issue here:\n\nhttps://github.com/typeorm/typeorm/issues/681\n\n========================================\n\nCode:\n```text\n@Module({\n imports: [\n HttpModule,\n TypeOrmModule.forRoot({\n type: (process.env.DB_TYPE as any) || 'postgres',\n host: process.env.DB_HOST || '127.0.0.1',\n port: (process.env.DB_PORT as any) || 5432,\n username: process.env.DB_USER || 'root',\n password: process.env.DB_PASS || '',\n database: process.env.DB_NAME || 'test',\n entities: [join(__dirname, '**/**.entity{.ts,.js}')],\n synchronize: true,\n logging: 'all',\n logger: 'advanced-console',\n subscribers: [EntityModificationSubscriber],\n }),\n TypeOrmModule.forFeature([\n RevisionEntity,\n ]),\n TerminusModule.forRootAsync({\n // Inject the TypeOrmHealthIndicator provided by nestjs/terminus\n inject: [TypeOrmHealthIndicator, MicroserviceHealthIndicator],\n useFactory: (db, msg) => getTerminusOptions(db, msg),\n }),\n GraphQLModule.forRoot({\n debug: true,\n playground: true,\n typePaths: ['./**/*.graphql'],\n }),\n ],\n controllers: [AppController],\n providers: [\n RevisionService,\n EntityModificationSubscriber,\n ],\n})\n```\n\n```text\nimport {EntitySubscriberInterface, EventSubscriber, InsertEvent, RemoveEvent, UpdateEvent} from 'typeorm';\nimport {RevisionEntity, RevisonEntityStatus} from '../entities/revison.entity';\nimport {RevisionService} from '../services/revisions.service';\nimport {Injectable} from '@nestjs/common';\n\n@Injectable()\n@EventSubscriber()\nexport class EntityModificationSubscriber implements EntitySubscriberInterface {\n\n constructor(private revisionService: RevisionService) {\n }\n\n // tslint:disable-next-line:no-empty\n afterInsert(event: InsertEvent<any>): Promise<any> | void {\n const revision = new RevisionEntity();\n\n revision.action = RevisonEntityStatus.Created;\n }\n\n afterUpdate(event: UpdateEvent<any>): Promise<any> | void {\n }\n\n // tslint:disable-next-line:no-empty\n afterRemove(event: RemoveEvent<any>) {\n // this.revisionService.createRevisionEntry(revision);\n }\n}\n```\n\n```js\nimport { EntitySubscriberInterface, EventSubscriber, InsertEvent, RemoveEvent, UpdateEvent, Connection } from 'typeorm';\n import { RevisionEntity, RevisonEntityStatus } from '../entities/revison.entity';\n import { RevisionService } from '../services/revisions.service';\n import { Injectable } from '@nestjs/common';\n\n @Injectable()\n @EventSubscriber()\n export class EntityModificationSubscriber implements EntitySubscriberInterface {\n\n constructor(private readonly connection: Connection, private readonly revisionService: RevisionService) {\n connection.subscribers.push(this); // <---- THIS \n }\n\n // tslint:disable-next-line:no-empty\n afterInsert(event: InsertEvent<any>): Promise<any> | void {\n const revision = new RevisionEntity();\n\n revision.action = RevisonEntityStatus.Created;\n\n //this.revisionService <- should be working!\n }\n\n afterUpdate(event: UpdateEvent<any>): Promise<any> | void {\n }\n\n // tslint:disable-next-line:no-empty\n afterRemove(event: RemoveEvent<any>) {\n // this.revisionService.createRevisionEntry(revision);\n }\n }\n```\n\n```text\nsubscribers: [EntityModificationSubscriber],\n```\n\n```text\nevent.manager\n```\n\n```text\n@Module({\n imports: [CustomerModule, TypeOrmModule.forFeature([Cart, Customer, Product])],\n controllers: [CartController],\n providers: [CartService, CustomerCartSubscriber],\n exports: [CartService]\n})\n```\n\n```text\n@EventSubscriber()\nexport class CustomerCartSubscriber implements EntitySubscriberInterface<Customer> {\n constructor(\n @Inject(CartService) public readonly cartService: CartService,\n @Inject(DataSource) dataSource: DataSource\n ) {\n dataSource.subscribers.push(this);\n }\n\n listenTo() {\n return Customer;\n }\n\n async beforeInsert(event: InsertEvent<Customer>) {\n await this.cartService.createCart(event.entity);\n }\n}\n```\n\n========================================\n\nComments:\n- Do you get any errors with this, or is the service just undefined?\n- @JayMcDoniel The service just returns as undefined\n- @JPanda did you manage to fix it? I am having the same problem\n- For me, it seems to fail, because Connection cannot be injected.\n- I also had to register the subscriber as a provider as mentioned here: github.com/nestjs/typeorm/pull/27\n- thank you very much! you saved my architecture :) guys, if it doesn't work, check if you added this class to import in your nest module\n- At the moment, Connection and InjectConnection are deprecated. I don't know which solution should be correct right now.. EDIT: New solution => docs.nestjs.com/techniques/database#subscribers\n- @etienne-de-martel Thank you, I don’t give a lot of answers, so I’m not used to it. I'll correct it.\n- The important part for me here, was that I was passing the `subscribers` field into my ormconfig, and you have to remove that. Then you can register it manually like in the constructor here. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:44.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":258,"estimatedTokens":2028}}97{"id":"stack-72682474","source":"stackoverflow","questionId":72682474,"title":"Typeorm Migration:generate failure Not enough non-option arguments: got 0, need at least 1","tags":["typeorm"],"text":"Title: Typeorm Migration:generate failure Not enough non-option arguments: got 0, need at least 1\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI tried this command in different possible ways but the basic structure of my command was.\n\n```\nyarn typeorm migration:generate -n=consent-record -d=\\\"./src/db/CliDataSource.ts\\\"\n```\n\nthis is my typeorm command in the package.json for yarn berry\n\n```\n\"typeorm\": \"ts-node -P ./tsconfig.typeorm.json $(yarn bin typeorm) -d ./src/db/CliDataSource.ts\",\n```\n\nI also tried installing typeorm locally as an npm. and also tried with npx.\nbut they all give the following error. \"Not enough non-option arguments: got 0, need at least 1\"\nthis error clearly doesn't mention what is missing.\n\nmy CliDataSource goes like this.\n\n```\nexport const CliDataSource = new DataSource({\n type: 'postgres',\n host: 'localhost',\n port: 5436,\n username: '****',\n password: '******',\n database: 'consent',\n synchronize: false,\n logging: false,\n entities,\n migrations,\n migrationsRun: true,\n subscribers: [],\n});\n```\n\nhttps://i.sstatic.net/12vfR.png\n\nI am using typeorm \"^0.3.6\"\n\n========================================\n\nTop Answer:\nI had a similar issue but solved it initially using a util file like this\n\n```\n// contents of migration.ts\n\nimport { exec } from 'child_process';\n\nconst command = `npm run typeorm migration:create ./src/migrations/${process.argv[process.argv.length - 1]}`;\n\n(() => exec(command, (error, stdout, stderr) => {\n if (error !== null) {\n console.error(stderr);\n }\n console.log(stdout);\n}))();\n```\n\nIn the `package.json`:\n\n`\"migration:create\": \"ts-node migration.ts\"`\n\nAnd to use, type the following:\n\n`npm run migration:create unique-key-username`\n\nBut here's how it should be done after the latest changes in TypeORM:\n\n```\n// new syntax for TypeORM ormconfig.ts\n\nconst { DataSource } = require(\"typeorm\");\n\nrequire('dotenv').config();\nfor (const envName of Object.keys(process.env)) {\n process.env[envName] = process.env[envName].replace(/\\\\n/g, '\\n');\n}\n\nconst connectionSource = new DataSource({\n type: 'mysql',\n host: process.env.DB_HOST,\n port: +process.env.DB_PORT,\n username: process.env.DB_USERNAME,\n password: process.env.DB_PASSWORD,\n database: process.env.DB_DATABASE,\n entities: [__dirname + '/entities/**/*.{js,ts}'],\n migrations: [__dirname + '/dist/src/migrations/*.js'],\n});\n\nmodule.exports = {\n connectionSource,\n}\n```\n\n```\n// package.json\n\n\"typeorm\": \"ts-node node_modules/typeorm/cli.js\",\n\"migration:create\": \"ts-node migration.ts -d ./ormconfig.ts\",\n\"migration:run\": \"typeorm migration:run -d ./ormconfig.ts\",\n\"migration:revert\": \"typeorm migration:revert -d ./ormconfig.ts\",\n```\n\n========================================\n\nCode:\n```text\nyarn typeorm migration:generate -n=consent-record -d=\\\"./src/db/CliDataSource.ts\\\"\n```\n\n```text\n\"typeorm\": \"ts-node -P ./tsconfig.typeorm.json $(yarn bin typeorm) -d ./src/db/CliDataSource.ts\",\n```\n\n```text\nexport const CliDataSource = new DataSource({\n type: 'postgres',\n host: 'localhost',\n port: 5436,\n username: '****',\n password: '******',\n database: 'consent',\n synchronize: false,\n logging: false,\n entities,\n migrations,\n migrationsRun: true,\n subscribers: [],\n});\n```\n\n```text\n\"typeorm\": \"ts-node -P ./tsconfig.typeorm.json $(yarn bin typeorm) -d ./src/db/CliDataSource.ts\",\n```\n\n```text\nyarn typeorm migration:generate ./src/db/migrations/consent-record\n```\n\n```text\nnpx typeorm migration:generate Init -d dist/db/CliDataSource.js\n```\n\n```text\ntypeorm/src/db/CliDataSource.ts\n\n\n: pathToFileURL(filePath).toString(), \npackage.json module type check ->\n\ntypeorm/src/db/CliDataSource.ts/\n\n const isModule = (packageJson as any)?.type === \"module\"\n```\n\n```text\nnpx typeorm migration:generate Init -d ./src/db/CliDataSource.ts\n```\n\n```js\n// contents of migration.ts\n\nimport { exec } from 'child_process';\n\nconst command = `npm run typeorm migration:create ./src/migrations/${process.argv[process.argv.length - 1]}`;\n\n(() => exec(command, (error, stdout, stderr) => {\n if (error !== null) {\n console.error(stderr);\n }\n console.log(stdout);\n}))();\n```\n\n```js\n// new syntax for TypeORM ormconfig.ts\n\nconst { DataSource } = require(\"typeorm\");\n\nrequire('dotenv').config();\nfor (const envName of Object.keys(process.env)) {\n process.env[envName] = process.env[envName].replace(/\\\\n/g, '\\n');\n}\n\nconst connectionSource = new DataSource({\n type: 'mysql',\n host: process.env.DB_HOST,\n port: +process.env.DB_PORT,\n username: process.env.DB_USERNAME,\n password: process.env.DB_PASSWORD,\n database: process.env.DB_DATABASE,\n entities: [__dirname + '/entities/**/*.{js,ts}'],\n migrations: [__dirname + '/dist/src/migrations/*.js'],\n});\n\nmodule.exports = {\n connectionSource,\n}\n```\n\n```js\n// package.json\n\n\"typeorm\": \"ts-node node_modules/typeorm/cli.js\",\n\"migration:create\": \"ts-node migration.ts -d ./ormconfig.ts\",\n\"migration:run\": \"typeorm migration:run -d ./ormconfig.ts\",\n\"migration:revert\": \"typeorm migration:revert -d ./ormconfig.ts\",\n```\n\n```text\npackage.json\n```\n\n```text\n\"migration:create\": \"ts-node migration.ts\"\n```\n\n```text\nnpm run migration:create unique-key-username\n```\n\n```text\nng run\n```\n\n```text\nng serve\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":234,"estimatedTokens":1289}}98{"id":"stack-58722202","source":"stackoverflow","questionId":58722202,"title":"What are the different use cases for using QueryBuilder vs. Repository in TypeORM?","tags":["mysql","database","nestjs","typeorm"],"text":"Title: What are the different use cases for using QueryBuilder vs. Repository in TypeORM?\nTags: mysql, database, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm building an API using NestJS with TypeORM. I've been querying a MySQL database using the TypeORM Repository API mostly because the NestJS Database documentation section provided an example using `this.photoRepository.find()`. As I get further along, I've noticed many of my exploratory search results recommending using the TypeORM QueryBuilder API for performance and flexibility reasons.\n\nI'm getting the sense that the Repository approach is easier to use for simple needs and a great abstraction if I ever decide to switch my database framework. On the other hand, it also seems to me that QueryBuilder is more performant and customizable.\n\nCould we outline the different use cases for QueryBuilder vs. Repository in TypeORM?\n\n========================================\n\nCode:\n```text\nthis.photoRepository.find()\n```\n\n========================================\n\nComments:\n- @AndreFeijo I've updated the title and question to be answered with facts and citations instead of opinions. Could we re-open?\n- why not use them both? Use the query builder inside the repository functions","metadata":{"transformedAt":"2026-08-18T18:33:44.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":23,"estimatedTokens":312}}99{"id":"stack-53426715","source":"stackoverflow","questionId":53426715,"title":"typeorm: saving an entity with many-to-many relationship ids","tags":["typescript","typeorm"],"text":"Title: typeorm: saving an entity with many-to-many relationship ids\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nIs it possible to save an entity with many-to-many relation ids?\n\nsuppose I have following `Project` Entity with many-to-many relationship to userGroups table.\n\n```\n@Entity()\nexport class Project extends BaseEntity {\n @Column({ type: 'varchar', length: 255 })\n name: string\n\n @RelationId((project: Project) => project.userGroups)\n userGroupIds: number[]\n\n @ManyToMany(type => UserGroup, userGroup => userGroup.projects)\n @JoinTable()\n userGroups: UserGroup[]\n}\n```\n\nSince ids of the userGroups table are mapped to `userGroupIds` property of the Project class via `@RelationId` decorator, I thought I could save a new Project entity with userGroupIds like this:\n\n```\nlet prj = new Project()\nprj.name = 'foo'\nprj.userGroupIds = [1, 2, 3]\nprj.save()\n```\n\nbut the above code only creates a project record... (no record is created on project - userGroups many-to-many relation table)\n\n========================================\n\nTop Answer:\n**entity**\n\n```\n@Entity()\nexport class Project extends BaseEntity {\n @Column()\n name: string\n\n @ManyToMany(type => UserGroup, userGroup => userGroup.projects)\n @JoinTable()\n userGroups: UserGroup[]\n}\n```\n\n**resolver**\n\n```\nconst input = {\n userGroupList: ['id1' 'id2', 'id3'];\n};\n\nconst project = new Project();\nproject.name = 'Name of the Awesome Project';\nproject.userGroups = Promise.resolve(input.userGroupList.map(id => ({ id })) as UserGroup[]);\nproject.save(project);\n```\n\n`@RelationId`, you don't need to use this decorator. In TypeORM, when you add your `@ManyToMany()` and `@JoinTable()` decorators to `@Entity`, it automatically creates a table and creates the `userGroupId` and `projectId` cells within the table.\n\nWhen you instantiate a new Project entity, **TypeORM** also shows the relations as properties if any.\nWe make use of a *synthetic* `Promise.resolve()` to assign a value to the `project.userGroups` relations. Then we complete the relation by sending the project object into the `.save()` method.\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class Project extends BaseEntity {\n @Column({ type: 'varchar', length: 255 })\n name: string\n\n @RelationId((project: Project) => project.userGroups)\n userGroupIds: number[]\n\n @ManyToMany(type => UserGroup, userGroup => userGroup.projects)\n @JoinTable()\n userGroups: UserGroup[]\n}\n```\n\n```text\nlet prj = new Project()\nprj.name = 'foo'\nprj.userGroupIds = [1, 2, 3]\nprj.save()\n```\n\n```text\nProject\n```\n\n```text\nuserGroupIds\n```\n\n```text\n@RelationId\n```\n\n```js\n@Entity()\nexport class Project extends BaseEntity {\n @Column({ type: 'varchar', length: 255 })\n name: string\n\n @ManyToMany(type => UserGroup, userGroup => userGroup.projects, {\n cascade: true // this is the important line\n })\n @JoinTable()\n userGroups: UserGroup[]\n}\n```\n\n```js\nlet prj = new Project();\nprj.name = 'foo';\nprj.userGroups = [1, 2, 3].map((id) => ({ ...new UserGroup(), id })); \nprj.userGroups = [1, 2, 3].map((id) => ({ id })); // alternatively\nprj.save()\n```\n\n```text\ncascade\n```\n\n```text\n@Entity()\nexport class Project extends BaseEntity {\n @Column({ type: 'varchar', length: 255 })\n name: string\n\n // You shouldn't need this\n // @RelationId((project: Project) => project.userGroups)\n // userGroupIds: number[]\n\n @ManyToMany(type => UserGroup, userGroup => userGroup.projects)\n @JoinTable()\n userGroups: UserGroup[]\n}\n```\n\n```text\nidsToAdd = [1,2,3] // Assume these already exist\nlet prj = new Project()\nprj.name = 'foo'\nprj.userGroupIds = idsToAdd.map(id => ({...new UserGroup(), id})) // Convert each of the ids into the proper entity.\nprj.save() // Typeorm will ignore the other fields and only update the Ids, as you expect.\n```\n\n```text\nmap\n```\n\n```text\nid\n```\n\n```text\n{id: id}\n```\n\n```text\ncascade\n```\n\n```js\n@Entity()\nexport class Project extends BaseEntity {\n @Column()\n name: string\n\n @ManyToMany(type => UserGroup, userGroup => userGroup.projects)\n @JoinTable()\n userGroups: UserGroup[]\n}\n```\n\n```js\nconst input = {\n userGroupList: ['id1' 'id2', 'id3'];\n};\n\nconst project = new Project();\nproject.name = 'Name of the Awesome Project';\nproject.userGroups = Promise.resolve(input.userGroupList.map(id => ({ id })) as UserGroup[]);\nproject.save(project);\n```\n\n```text\n@RelationId\n```\n\n```text\n@ManyToMany()\n```\n\n```text\n@JoinTable()\n```\n\n```text\n@Entity\n```\n\n```text\nuserGroupId\n```\n\n```text\nprojectId\n```\n\n```text\nPromise.resolve()\n```\n\n```text\nproject.userGroups\n```\n\n```text\n.save()\n```\n\n========================================\n\nComments:\n- I think you should create the usergroup first, and add the created usergroup to project.\n- Thank you for your comment. You mean if i have 3 existing records(id=1,2,3) on user groups table, we need to create 3 instances of UserGroup entities from those records and add them to project entity?\n- yes, you can do like that.\n- I see. Thanks! Would be better if we could simply pass ids tho...\n- nope, because you don't always know the id, in test yes but in production you don't know\n- Also unable to save relation on existing entities this way `prj.userGroupIds = [1, 2, 3]`. With 1,2,3 being ids of existing entities. I am surprised this do not work. This `prj.userGroup = [{id:1}, {id:2}, {id:3}]` work but is kind of ugly.\n- Unfortunately, none of your suggested approaches worked - at least with TypeOrm.\n- Sorry, I tweaked my answer a bit to account for your scenario, but I did not need to use cascade. Perhaps you were saving more than just the ID?","metadata":{"transformedAt":"2026-08-18T18:33:44.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":243,"estimatedTokens":1392}}100{"id":"stack-42186674","source":"stackoverflow","questionId":42186674,"title":"How to use connection as standalone object with types?","tags":["node.js","typeorm"],"text":"Title: How to use connection as standalone object with types?\nTags: node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nNot working code just to illustrate what I'm trying to achieve\n\nSome connection file\n\n```\nimport { ConnectionManager } from 'typeorm';\n\nconst c = new ConnectionManager();\n// user ormconfig.conf file\nexport const connection = c.createAndConnect();\n```\n\nusing in some model\n\n```\n@Entity()\n@Table(\"annual_incomes\")\nexport class AnnualIncome\n{\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ length: 75 })\n variant: string;\n\n @Column(\"int\")\n sort: number;\n\n @Column()\n is_active: boolean;\n}\n```\n\nLater somewhere in the code, I want to get connection with all methods, something like:\n\n```\nimport { connection } from 'someconnection';\nimport { AnnualIncome } from 'entities';\n\n// some code here\n\napi.get('/incomes', async(ctx) => {\n ctx.body = await connection.getRepository(AnnualIncome).find();\n});\n```\n\nUsually, I'm getting an error from `tsc` that `.getRepository()` method was not found in `connection`. However if I do something like:\n\n```\nimport { connection } from 'someconnection';\nimport { AnnualIncome } from 'entities';\n\n// some code here\n\napi.get('/incomes', async(ctx) => {\n ctx.body = await connection.then(async connection => {\n return await connection.getRepository(AnnualIncome).find();\n }\n});\n```\n\nthe above code works with definitions and `tsc` does not complain about not-existing methods.\n\nI'd like to avoid an extra definition `connection.then()` and get plain `connection` with all methods defined in `` type.\n\n========================================\n\nCode:\n```text\nimport { ConnectionManager } from 'typeorm';\n\nconst c = new ConnectionManager();\n// user ormconfig.conf file\nexport const connection = c.createAndConnect();\n```\n\n```text\n@Entity()\n@Table(\"annual_incomes\")\nexport class AnnualIncome\n{\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ length: 75 })\n variant: string;\n\n @Column(\"int\")\n sort: number;\n\n @Column()\n is_active: boolean;\n}\n```\n\n```text\nimport { connection } from 'someconnection';\nimport { AnnualIncome } from 'entities';\n\n// some code here\n\napi.get('/incomes', async(ctx) => {\n ctx.body = await connection.getRepository(AnnualIncome).find();\n});\n```\n\n```text\nimport { connection } from 'someconnection';\nimport { AnnualIncome } from 'entities';\n\n// some code here\n\napi.get('/incomes', async(ctx) => {\n ctx.body = await connection.then(async connection => {\n return await connection.getRepository(AnnualIncome).find();\n }\n});\n```\n\n```text\ntsc\n```\n\n```text\n.getRepository()\n```\n\n```text\nconnection\n```\n\n```text\ntsc\n```\n\n```text\nconnection.then()\n```\n\n```text\nconnection\n```\n\n```text\n<Connection>\n```\n\n```text\nimport { AnnualIncome } from 'entities';\nimport { createConnection, getConnection } from 'typeorm';\n\n// somewhere in your app, better where you bootstrap express and other things\ncreateConnection(); // read config from ormconfig.json or pass them here\n\n// some code here\n\napi.get('/incomes', async(ctx) => {\n ctx.body = await getConnection().getRepository(AnnualIncome).find();\n});\n```\n\n```text\nimport { AnnualIncome } from 'entities';\nimport { getRepository } from 'typeorm';\n\n// some code here\n\napi.get('/incomes', async (ctx) => {\n ctx.body = await getRepository(AnnualIncome).find();\n});\n```\n\n```text\ncreateConnection\n```\n\n```text\ngetConnection()\n```\n\n```text\ngetRepository\n```\n\n========================================\n\nComments:\n- Thanks. I want to notice that if use just `getRepository()` I have to set up connection name `await getRepository(AnnualIncome, 'default')`\n- actually you can omit connection name parameter because its by default is `default`. You should use only when your name a specific connection name\n- probably there is collision between definitions or versions `https://github.com/typeorm/typeorm/blob/master/src/index.ts#‌​L259` because your example does not work for me in version `0.0.8` In my npm package I does not have this line `https://github.com/typeorm/typeorm/blob/master/src/index.ts#‌​L269`\n- Isn't it better/safer to open and close connection every time you use it (instead reusing same connection all the time)?\n- no, its not efficient because each time connection opening and closing takes too much time\n- I'm a bit confused (maybe I'm missing know-how about async/await): in my typeorm/index.d.ts (v.0.0.11) there is following definition (note that there is no promise): `export declare function getRepository(entityClass: ObjectType, connectionName: string): Repository;`. Has API changed?\n- right getRepository does not return promise. `find` method of it returns promise and we are await `find`, not `getRepository`.\n- @pleerock. How does `createConnection` work? where does the connection go? is it stored in memory?\n- getConnection is deprecated now, is there other option?","metadata":{"transformedAt":"2026-08-18T18:33:44.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":201,"estimatedTokens":1233}}101{"id":"stack-66169705","source":"stackoverflow","questionId":66169705,"title":"Bundle a NestJS + TypeORM application (with webpack)","tags":["nestjs","typeorm","bundling-and-minification"],"text":"Title: Bundle a NestJS + TypeORM application (with webpack)\nTags: nestjs, typeorm, bundling-and-minification\nSource: Stack Overflow\n\nQuestion:\nI recently have to think about a deployment method for a new piece of software that is written with:\n\n- NestJS 6 / Express\n\n- TypeORM 0.2\n\n- TypeScript is used\n\nThe software will be deployed on more than 160 servers, distributed all across Europe, and some of them have very bad Internet connections.\n\nI did some research and a lot of people explicitly advices **against** bundling. The main argument is that native extension will fails with bundlers like `webpack` or `rollup` (Spoiler: it's true, but there is a solution). In my opinion, it's largely due to the fact that people don't care for this: the author of `node-pre-gyp` used nearly the same words for this use case. So usually, I was told to either use `yarn install` or sync the `node_modules/` folder.\n\nThe project is new, but the `node_modules/` folder is already more than 480 MB. Using XZ with maximum compression gave me an archive of 20 MB. This is still way too large for me, and seems like a huge waste of resources.\n\nI also had a look at the following Q&A:\n\n- How to correctly build NestJS app for production with node_modules dependencies in bundle? Explains that NestJS support webpack **without** `node_modules/` out of the box.\n\n- Single file bundle with NestJS + Typescript + Webpack + node_modules Working answer, without further explanations. Also `IgnorePlugins` seems to be overkill.\n\n- How to bundle nestjs application with webpack Seems to copy/paste a working solution from ZenSoftware without quoting. Links to another answer.\n\n- NestJS optimization minimize not work with webpack Give an advice to disable minimization with NestJS application\n\nThere are also some separate Q&A for TypeORM, but all of them seems to require the installation of `ts-node` or `typescript`:\n\n- TypeORM + Webpack causes SyntaxError: Unexpected token for entity file\n\n- Isomoprhic application, problem with TypeORM && TypeScript && Express && Webpack setup\n\n- SyntaxError: Unexpected token import typeORM entity\n\n========================================\n\nCode:\n```text\nwebpack\n```\n\n```text\nrollup\n```\n\n```text\nnode-pre-gyp\n```\n\n```text\nyarn install\n```\n\n```text\nnode_modules/\n```\n\n```text\nnode_modules/\n```\n\n```text\nnode_modules/\n```\n\n```text\nIgnorePlugins\n```\n\n```text\nts-node\n```\n\n```text\ntypescript\n```\n\n```js\nentry: {\n main: './src/main.ts',\n console: \"./src/console.ts\",\n 'data-source': {\n import: './src/data-source.ts',\n library: {\n type: 'commonjs2'\n }\n },\n typeorm: './node_modules/typeorm/cli.js',\n },\n```\n\n```text\nwebpack.config.js\nwebpack\n├── migrations.config.js\n└── typeorm-cli.config.js\n```\n\n```js\n// webpack.config.js\nconst { NODE_ENV = 'production' } = process.env;\n\nconsole.log(`-- Webpack <${NODE_ENV}> build --`);\n\nmodule.exports = {\n target: 'node',\n mode: NODE_ENV,\n externals: [\n // Here are listed all optional dependencies of NestJS,\n // that are not installed and not required by my project\n {\n 'fastify-swagger': 'commonjs2 fastify-swagger',\n 'aws-sdk': 'commonjs2 aws-sdk',\n '@nestjs/websockets/socket-module': 'commonjs2 @nestjs/websockets/socket-module',\n '@nestjs/microservices/microservices-module': 'commonjs2 @nestjs/microservices/microservices-module',\n \n // I'll skip pg-native in the production deployement, and use the pure JS implementation\n 'pg-native': 'commonjs2 pg-native'\n }\n ],\n optimization: {\n // Minimization doesn't work with @Module annotation\n minimize: false,\n }\n};\n```\n\n```js\n// webpack/typeorm-cli.config.js\n\nconst path = require('path');\n// TypeScript compilation option\nconst TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');\n// Don't try to replace require calls to dynamic files\nconst IgnoreDynamicRequire = require('webpack-ignore-dynamic-require');\n\nconst { NODE_ENV = 'production' } = process.env;\n\nconsole.log(`-- Webpack <${NODE_ENV}> build for TypeORM CLI --`);\n\nmodule.exports = {\n target: 'node',\n mode: NODE_ENV,\n entry: './node_modules/typeorm/cli.js',\n output: {\n // Remember that this file is in a subdirectory, so the output should be in the dist/\n // directory of the project root\n path: path.resolve(__dirname, '../dist'),\n filename: 'migration.js',\n },\n resolve: {\n extensions: ['.ts', '.js'],\n // Use the same configuration as NestJS\n plugins: [new TsconfigPathsPlugin({ configFile: './tsconfig.build.json' })],\n },\n module: {\n rules: [\n { test: /\\.ts$/, loader: 'ts-loader' },\n // Skip the shebang of typeorm/cli.js\n { test: /\\.[tj]s$/i, loader: 'shebang-loader' }\n ],\n },\n externals: [\n {\n // I'll skip pg-native in the production deployement, and use the pure JS implementation\n 'pg-native': 'commonjs2 pg-native'\n }\n ],\n plugins: [\n // Let NodeJS handle are requires that can't be resolved at build time\n new IgnoreDynamicRequire()\n ]\n};\n```\n\n```js\n// webpack/migrations.config.js\n\nconst glob = require('glob');\nconst path = require('path');\n// TypeScript compilation option\nconst TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');\n// Minimization option\nconst TerserPlugin = require('terser-webpack-plugin');\n\nconst { NODE_ENV = 'production' } = process.env;\n\nconsole.log(`-- Webpack <${NODE_ENV}> build for migrations scripts --`);\n\nmodule.exports = {\n target: 'node',\n mode: NODE_ENV,\n // Dynamically generate a `{ [name]: sourceFileName }` map for the `entry` option\n // change `src/db/migrations` to the relative path to your migration folder\n entry: glob.sync(path.resolve('src/migration/*.ts')).reduce((entries, filename) => {\n const migrationName = path.basename(filename, '.ts');\n return Object.assign({}, entries, {\n [migrationName]: filename,\n });\n }, {}),\n resolve: {\n // assuming all your migration files are written in TypeScript\n extensions: ['.ts'],\n // Use the same configuration as NestJS\n plugins: [new TsconfigPathsPlugin({ configFile: './tsconfig.build.json' })],\n },\n module: {\n rules: [\n { test: /\\.ts$/, loader: 'ts-loader' }\n ]\n },\n output: {\n // Remember that this file is in a subdirectory, so the output should be in the dist/\n // directory of the project root\n path: __dirname + '/../dist/migration',\n // this is important - we want UMD (Universal Module Definition) for migration files.\n libraryTarget: 'umd',\n filename: '[name].js',\n },\n optimization: {\n minimizer: [\n // Migrations rely on class and function names, so keep them.\n new TerserPlugin({\n terserOptions: {\n mangle: true, // Note `mangle.properties` is `false` by default.\n keep_classnames: true,\n keep_fnames: true,\n }\n })\n ],\n },\n};\n```\n\n```js\n// webpack.config.js\nconst { merge } = require(\"webpack-merge\")\nconst path = require('path')\nconst glob = require('glob')\nconst TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')\nconst TerserPlugin = require('terser-webpack-plugin')\nconst MomentLocalesPlugin = require('moment-locales-webpack-plugin')\nconst IgnoreDynamicRequire = require('webpack-ignore-dynamic-require')\n\nconst { NODE_ENV = 'production', ENTRY, npm_lifecycle_event: lifecycle } = process.env\n\n// Build platform don't support ?? and ?. operators\nconst entry = ENTRY || (lifecycle && lifecycle.match(/bundle:(?<entry>\\w+)/).groups[\"entry\"])\n\nif (entry === undefined) {\n throw new Error(\"ENTRY must be defined\")\n}\n\nconsole.log(`-- Webpack <${NODE_ENV}> build for <${entry}> --`);\n\nconst BASE_CONFIG = {\n target: 'node',\n mode: NODE_ENV,\n resolve: {\n extensions: ['.ts', '.js'],\n plugins: [new TsconfigPathsPlugin({ configFile: './tsconfig.build.json' })],\n },\n module: {\n rules: [\n { test: /\\.ts$/, loader: 'ts-loader' }\n ]\n },\n output: {\n path: path.resolve(__dirname, 'dist/'),\n filename: '[name].js',\n },\n}\n\nconst MIGRATION_CONFIG = {\n // Dynamically generate a `{ [name]: sourceFileName }` map for the `entry` option\n // change `src/db/migrations` to the relative path to your migration folder\n entry: glob.sync(path.resolve('src/migration/*.ts')).reduce((entries, filename) => {\n const migrationName = path.basename(filename, '.ts')\n return Object.assign({}, entries, {\n [migrationName]: filename,\n })\n }, {}),\n output: {\n path: path.resolve(__dirname, 'dist/migration'),\n // this is important - we want UMD (Universal Module Definition) for migration files.\n libraryTarget: 'umd',\n filename: '[name].js',\n },\n optimization: {\n minimizer: [\n new TerserPlugin({\n terserOptions: {\n mangle: true, // Note `mangle.properties` is `false` by default.\n keep_classnames: true,\n keep_fnames: true,\n }\n })\n ],\n }\n}\n\nconst TYPEORM_CONFIG = {\n entry: {\n typeorm: './node_modules/typeorm/cli.js'\n },\n externals: [\n {\n 'pg-native': 'commonjs2 pg-native',\n }\n ],\n plugins: [\n new IgnoreDynamicRequire(),\n ],\n module: {\n rules: [\n { test: /\\.[tj]s$/i, loader: 'shebang-loader' }\n ],\n },\n}\n\nconst MAIN_AND_CONSOLE_CONFIG = {\n entry: {\n main: './src/main.ts',\n console: \"./src/console.ts\"\n },\n externals: [\n {\n 'pg-native': 'commonjs2 pg-native',\n 'fastify-swagger': 'commonjs2 fastify-swagger',\n '@nestjs/microservices/microservices-module': 'commonjs2 @nestjs/microservices/microservices-module',\n '@nestjs/websockets/socket-module': 'commonjs2 @nestjs/websockets/socket-module',\n // This one is a must have to generate the swagger document, but we remove it in production\n 'swagger-ui-express': 'commonjs2 swagger-ui-express',\n 'aws-sdk': 'commonjs2 aws-sdk',\n }\n ],\n plugins: [\n // We don't need moment locale\n new MomentLocalesPlugin()\n ],\n optimization: {\n // Full minization doesn't work with @Module annotation\n minimizer: [\n new TerserPlugin({\n terserOptions: {\n mangle: true, // Note `mangle.properties` is `false` by default.\n keep_classnames: true,\n keep_fnames: true,\n }\n })\n ],\n splitChunks: {\n cacheGroups: {\n commons: {\n test: /[\\\\/]node_modules[\\\\/]/,\n name: 'vendors',\n chunks: 'all'\n }\n }\n }\n }\n}\n\nconst withPlugins = (config) => (runtimeConfig) => ({\n ...config,\n plugins: [\n ...runtimeConfig.plugins,\n ...(config.plugins || [])\n ]\n})\n\nconst config = entry === \"migrations\" ? merge(BASE_CONFIG, MIGRATION_CONFIG)\n : entry === \"typeorm\" ? merge(BASE_CONFIG, TYPEORM_CONFIG)\n : entry === \"main\" ? merge(BASE_CONFIG, MAIN_AND_CONSOLE_CONFIG)\n : undefined\n\n\nmodule.exports = withPlugins(config)\n```\n\n```text\nconst TYPEORM_CONFIG = {\n entry: {\n 'data-source': {\n // Are you ready? You must provide a data source as TypeORM cli >= 0.3\n // But this will be a dynamic require(), so Webpack can't know how to handle it\n // in TypeORM code. Instead, export this data source as a library.\n // BUT, TypeORM expect it to be at the top level instead of a module variable, so\n // we MUST remove the library name to make webpack export each variable from data source into the module\n import: './src/data-source.ts',\n library: {\n type: 'commonjs2'\n }\n },\n typeorm: './node_modules/typeorm/cli.js'\n },\n externals: [\n {\n 'pg-native': 'commonjs2 pg-native',\n }\n ],\n plugins: [\n new IgnoreDynamicRequire(),\n ],\n module: {\n rules: [\n { test: /\\.[tj]s$/i, loader: 'shebang-loader' }\n ],\n },\n}\n```\n\n```json\n{\n \"scripts\": {\n \"bundle:application\": \"nest build --webpack\",\n \"bundle:migrations\": \"nest build --webpack --webpackPath webpack/typeorm-cli.config.js && nest build --webpack --webpackPath webpack/migrations.config.js\",\n \"bundle\": \"yarn bundle:application && yarn bundle:migrations\"\n },\n}\n```\n\n```text\n%build\nmkdir yarncache\nexport YARN_CACHE_FOLDER=yarncache\n\n# Setting to avoid node-gype trying to download headers\nexport npm_config_nodedir=/opt/rh/rh-nodejs10/root/usr/\n\n%{_yarnbin} install --offline --non-interactive --frozen-lockfile\n%{_yarnbin} bundle\n\nrm -r yarncache/\n\n%install\ninstall -D -m644 dist/main.js $RPM_BUILD_ROOT%{app_path}/main.js\n\ninstall -D -m644 dist/migration.js $RPM_BUILD_ROOT%{app_path}/migration.js\n# Migration path have to be changed, let's hack it.\nsed -ie 's/src\\/migration\\/\\*\\.ts/migration\\/*.js/' ormconfig.json\ninstall -D -m644 ormconfig.json $RPM_BUILD_ROOT%{app_path}/ormconfig.json\nfind dist/migration -name '*.js' -execdir install -D -m644 \"{}\" \"$RPM_BUILD_ROOT%{app_path}/migration/{}\" \\;\n```\n\n```ini\n[Unit]\nDescription=NestJS Server\nAfter=network.target\n\n[Service]\nType=simple\nUser=nestjs\nEnvironment=SCLNAME=rh-nodejs10\nExecStartPre=/usr/bin/scl enable $SCLNAME -- /usr/bin/env node migration migration:run\nExecStart=/usr/bin/scl enable $SCLNAME -- /usr/bin/env node main\nWorkingDirectory=/export/myapplication\nRestart=on-failure\n\n# Hardening\nPrivateTmp=true\nNoNewPrivileges=true\nProtectSystem=full\nProtectHome=read-only\n\n[Install]\nWantedBy=multi-user.target\n```\n\n```text\normconfig.json\n```\n\n```text\nlibrary\n```\n\n```text\nwebpack\n```\n\n```text\nwebpack\n```\n\n```text\nbcrypt\n```\n\n```text\nbcrypt\n```\n\n```text\nnode-pre-gyp\n```\n\n```text\nwebpack\n```\n\n```text\nbuild\n```\n\n```text\nwebpack\n```\n\n```text\nwebpack\n```\n\n```text\nwebpack\n```\n\n```text\nIgnorePlugin\n```\n\n```text\nexternals\n```\n\n```text\nshebang-loader\n```\n\n```text\nwebpack\n```\n\n```text\nrequire\n```\n\n```text\nenv\n```\n\n```text\nyarn add -D webpack-merge\n```\n\n```text\nwebpack.config.js\n```\n\n```text\nbundle:main\n```\n\n```text\nmain\n```\n\n```text\nconsole\n```\n\n```text\nsplitChunks\n```\n\n```text\nnode\n```\n\n```text\npackage.json\n```\n\n```text\npackage.json\n```\n\n```text\nyarn bundle\n```\n\n```text\ndist/\n```\n\n```text\normconfig.json\n```\n\n```text\n-f data-source.js\n```\n\n```text\nExecStartPre\n```\n\n```text\n.production.env\n```\n\n```text\normconfig.json\n```\n\n========================================\n\nComments:\n- can you provide a sample project with all these configuration ?\n- Good research, indeed. How do you set up the ormconfig.json file?\n- Nothing special in `ormconfig.json`. It is just written as in any TypeORM project, depending on your needs.\n- Had it working with no ormconfig.json, in the end. I've used the programatic way of configuring TypeORM stated here Thanks for the hint of `minimize: false`, it made the trick!","metadata":{"transformedAt":"2026-08-18T18:33:44.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":54,"totalLines":615,"estimatedTokens":3617}}102{"id":"stack-67240573","source":"stackoverflow","questionId":67240573,"title":"How do I explicitly set a table name?","tags":["typeorm"],"text":"Title: How do I explicitly set a table name?\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI can't find anything in the documentation about this, and strangely also not here - is there a way to do this?\n\n========================================\n\nCode:\n```text\n@Entity(\"users\")\nexport class User {\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":14,"estimatedTokens":76}}103{"id":"stack-65570680","source":"stackoverflow","questionId":65570680,"title":"what is getRepositoryToken in nestjs typeorm and when to use it?","tags":["jestjs","nestjs","typeorm"],"text":"Title: what is getRepositoryToken in nestjs typeorm and when to use it?\nTags: jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThe docs here are as below:\n\nWhen it comes to unit testing an application, we usually want to avoid\nmaking a database connection, keeping our test suites independent and\ntheir execution process as fast as possible. But our classes might\ndepend on repositories that are pulled from the connection instance.\nHow do we handle that? The solution is to create mock repositories. In\norder to achieve that, we set up custom providers. Each registered\nrepository is automatically represented by a Repository\ntoken, where EntityName is the name of your entity class.\n\nThe @nestjs/typeorm package exposes the getRepositoryToken() function\nwhich returns a prepared token based on a given entity.\n\nWhat does that even mean? Autocomplete docs just give the signature with no explanation.\n\n========================================\n\nCode:\n```js\n@Injectable()\nexport class FooService {\n constructor(@InjectRepository(Foo) private readonly fooRepo: Repository<Foo>) {}\n\n}\n```\n\n```js\n{\n provide: getRepositoryToken(Foo),\n useValue: {\n find: jest.fn(),\n insert: jest.fn(),\n },\n}\n```\n\n```text\ngetRepositoryToken()\n```\n\n```text\n@InjectRepository()\n```\n\n```text\nRepository\n```\n\n```text\nRepository\n```\n\n```text\nRepository\n```\n\n```text\nRepository\n```\n\n```text\n@InjectRepsitory()\n```\n\n========================================\n\nComments:\n- So let me see if I understand your answer correctly. This is specifically used when mocking and testing the service or thing that calls the injected repository? So in some cases I've seen where getRepository is not used, but I think in those cases it is only testing the repository directly and not the service calling the repository method?\n- Sounds about right. You could also use the `getRepositoryToken()` to properly inject the repository into a `useFactory` method for asynchronous registration of modules\n- Love your DND app btw. :) I'm still a bit curious about the difference in the end result. In practice, I see it still works without the getRespositoryToken method even when testing the above scenario, and I don't see any issues.\n- I'd probably have to see how you're testing things. This repo has a lot of different tests, and includes tests for typeorm, mongoose, and sequelize. None of them connect to a database during unit tests, so a database connection is not needed during them.\n- but if i need to reset the mock of `find` and insert between each test it can be done in this approach?\n- @MatanTubul you should be able to get the repository in the initial `beforeAll` using the `getRepositoryToken()` and then in an `afterEach` you can reset each method as necessary. Or just use `jest.resetAllMocks()`","metadata":{"transformedAt":"2026-08-18T18:33:44.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":79,"estimatedTokens":696}}104{"id":"stack-52030009","source":"stackoverflow","questionId":52030009,"title":"NestJS with TypeORM: When using custom repository, is a service needed anymore?","tags":["nestjs","typeorm"],"text":"Title: NestJS with TypeORM: When using custom repository, is a service needed anymore?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nNewbie question:\nWhen working with NestJS and TypeORM, and one has created a custom repository (which extends the standard repository), **is a seperate service class needed anymore?**\n\nAt the moment, I'm working only with the custom Repository class and it works fine, but I'm not sure if this is correct and perhaps has some side effects.\n\nBtw, in another project i have no custom repo, only a service which get's two standard repo's injected, and this works also fine.\n\nRegards,\n\nsagerobert\n\n========================================\n\nCode:\n```js\nimport {Controller, Get} from '@nestjs/common';\nimport {InjectRepository} from '@nestjs/typeorm';\nimport {Repository} from 'typeorm';\nimport {User} from './entities/User.entity';\n\n@Controller()\nexport class AppController {\n constructor(\n @InjectRepository(User)\n private readonly userRepository: Repository<User>,\n ) {\n }\n\n @Get()\n async root(): Promise<User> {\n return await this.userRepository.find(1);\n }\n}\n```\n\n========================================\n\nComments:\n- A separate repository layer does become useful if you want to use complex queries where you have lengthy sqls or complex query builders. This layer would abstract out all the db specific logic from the service layer.\n- Thanks for the great explantion, now I'm on it. The last sentence says it all: \"A service class is not needed. But it will help you keep your code clean\".\n- You are right, i should probably put it at the top and add a tldr mention\n- Do you know if it's possible to inject a Custom Repository into a Service when not using NestJS? Thanks.","metadata":{"transformedAt":"2026-08-18T18:33:44.690Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":47,"estimatedTokens":439}}105{"id":"stack-54965381","source":"stackoverflow","questionId":54965381,"title":"How to insert an entity with OneToMany relation in NestJS?","tags":["nestjs","typeorm"],"text":"Title: How to insert an entity with OneToMany relation in NestJS?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThere is the description how to do this in typeorm official docs https://typeorm.io/#/many-to-one-one-to-many-relations. But I can't do the same in NestJS with `Repository` and `insert` method.\n\nI have written these entities (other columns were omitted)\n\n```\n@Entity()\n export class News {\n @OneToMany(type => NewsImage, image => image.news)\n public images: NewsImage[];\n }\n \n @Entity()\n export class NewsImage {\n @ManyToOne(type => News, news => news.images)\n public news: News;\n }\n```\n\nI have tried something like this\n\n```\nfunction first() {\n const news = new News();\n const image = new NewsImage();\n news.images = [ image ];\n return from(this.newsRepo.insert(news))\n .pipe(\n switchMap(() => this.imageRepo.insert(image)),\n );\n }\n \n function second() {\n const news = new News();\n const image = new NewsImage();\n image.news = news;\n return from(this.imageRepo.insert(image))\n .pipe(\n switchMap(() => this.newsRepo.insert(news)),\n )\n }\n```\n\nIt inserts news and image, but image's `newsId` is `null`.\n\n========================================\n\nTop Answer:\nDeclaring `new News()` creates a new entity but does not save it to the database. You first need to `insert` or `.save()` the `news` object and then add it to `image`.\n\n```\nasync function first() {\n // you can .save() it however you want, the point is it must be saved to the db\n const news = await News.create({ title: 'Async rules the world' }).save()\n const image = new NewsImage()\n image.news = news // now news has an id from the database\n // ...\n}\n```\n\n========================================\n\nCode:\n```js\n@Entity()\n export class News {\n @OneToMany(type => NewsImage, image => image.news)\n public images: NewsImage[];\n }\n \n @Entity()\n export class NewsImage {\n @ManyToOne(type => News, news => news.images)\n public news: News;\n }\n```\n\n```js\nfunction first() {\n const news = new News();\n const image = new NewsImage();\n news.images = [ image ];\n return from(this.newsRepo.insert(news))\n .pipe(\n switchMap(() => this.imageRepo.insert(image)),\n );\n }\n \n function second() {\n const news = new News();\n const image = new NewsImage();\n image.news = news;\n return from(this.imageRepo.insert(image))\n .pipe(\n switchMap(() => this.newsRepo.insert(news)),\n )\n }\n```\n\n```text\nRepository\n```\n\n```text\ninsert\n```\n\n```text\nnewsId\n```\n\n```text\nnull\n```\n\n```js\n@Entity()\nexport class News {\n @OneToMany(type => NewsImage, image => image.news, { cascade: ['insert', 'update'] })\n public images: NewsImage[];\n}\n```\n\n```js\nlet news = {\n images: [{\n date: \"\",\n etc: \"\"\n }],\n title: \"\"\n }\n```\n\n```text\nthis.repository.save(news)\n```\n\n```text\nasync function first() {\n // you can .save() it however you want, the point is it must be saved to the db\n const news = await News.create({ title: 'Async rules the world' }).save()\n const image = new NewsImage()\n image.news = news // now news has an id from the database\n // ...\n}\n```\n\n```text\nnew News()\n```\n\n```text\ninsert\n```\n\n```text\n.save()\n```\n\n```text\nnews\n```\n\n```text\nimage\n```\n\n========================================\n\nComments:\n- Thanks, I tried this way, but `.insert` returns `InsertResult` object, not `news` entity. I retrieved `id` from `insertResults` and set `id` to `news`, created image entity with that news and it works!\n- How would you handle removing entities that are not in the images[] array, say for an update where an user removes one image from the array, it still exists in the database but instead of deleting the item typeorm/nestjs tries to set the newsId to null on the image @andressh11\n- here is a github issue regarding this : github.com/typeorm/typeorm/issues/1460 .","metadata":{"transformedAt":"2026-08-18T18:33:44.690Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":177,"estimatedTokens":976}}106{"id":"stack-62760579","source":"stackoverflow","questionId":62760579,"title":"TypeORM select alias of column name","tags":["mysql","node.js","typeorm"],"text":"Title: TypeORM select alias of column name\nTags: mysql, node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\n```\nthis.sampleRepo.find(\n {\n order: {\n id: \"DESC\"\n },\n select: ['id','group']\n }\n);\n```\n\nthis returns the `id` and `group` as expected, but how to return `id` as `user_id` ?\nand also how to select distinct values from group?\n\n========================================\n\nTop Answer:\nBelow code will give same column name and format\n\n```\n.select(\"id\", \"user_id\")\n.addSelect(\"group\", \"user_group\")\n```\n\nBelow will convert column name in Capital letter after response\n\n```\nselect: ['id AS user_id','group AS user_group']\n```\n\n========================================\n\nCode:\n```text\nthis.sampleRepo.find(\n {\n order: {\n id: \"DESC\"\n },\n select: ['id','group']\n }\n);\n```\n\n```text\nid\n```\n\n```text\ngroup\n```\n\n```text\nid\n```\n\n```text\nuser_id\n```\n\n```text\nselect: ['id AS user_id','group AS user_group']\n```\n\n```text\nthis.sampleRepo\n .createQueryBuilder('user')\n .orderBy('user.id', 'DESC')\n .select(['id AS user_id','group AS user_group'])\n .getRawMany() // or .getMany()\n```\n\n```text\ngetMany(): Promise<UserEntity[]> {\n return this.userRepo.createQueryBuilder('user')\n .where({ username: 'breckhouse0' })\n .select(['DISTINCT (user.username) AS user_name', 'user.id AS user_id'])\n .getRawMany();\n }\n```\n\n```text\n.select(\"id\", \"user_id\")\n.addSelect(\"group\", \"user_group\")\n```\n\n```text\nselect: ['id AS user_id','group AS user_group']\n```\n\n========================================\n\nComments:\n- 1) id as user_id: For now you can't or at least the value is mapped as the column name of the Entity class. See @Column decorator *name* option.\n- i saw the column name option but was thinking what to do if you need to send two different name in two different api, for example in api A , i wan to send id as userid, in api B , i want to send id as id. Column name decorator will not help here.\n- 2) You must use **QueryBuilder**. There is an open issue, see this, to add distinct for entity manager find options.\n- You want a remap? To do so: 1) Find all entities in an array 2) Map the array to rename the identification -> Note this is a really bad procedure since it has O(n) complexity and reduce the correct semantic to you api. I strongly suggest to choose one identifier to avoid efficiency problem and many more future issues.\n- For production identifier will be one, i'm just asking to learn how to do things if needed.\n- What is the standard way of doing this through query builder?\n- There is no standard de facto, it depend on you. For me, I always try to use find options but it's not powerful as querybuilder. See this.\n- For the first question, create an entity that is the same except for user_id and remap using map function on array the values. Remember, this is not good, keep you API as simple and coincise as possible.\n- this.sampleRepo.createQueryBuilder('user') .where ('user.id != 0') .select(['user.id','user.groups']) .orderBy(\"user.groups\", \"ASC\") .distinct(true) .getRawMany(); When i use this, the query works, when i use distinctOn ['user.groups'], it doesnt work, am i missing something?\n- Now it works with query builder, but for entity manager , it doesn't work. Please add the distinct option in the query with username column, ill accept the answer.\n- Ive accepted the answer , can you please help another point, how to do a query in find method , like i want to do a query where user id will be 1 or 2, for this i was giving return this.userRepository.find( { where : { id: In [\"1\",\"2\"] } } ); but its not working, my objective is to get all the user with id 1 or 2.\n- You missed round brackets `In()` - `return this.userRepository.find( { where : { id: In([\"1\",\"2\"]) } } )`\n- I got result with `getRawMany()` but not with `getMany()`\n- I got result with `getRawMany()` but not with `getMany()`\n- Me too. All's good in raw via `getRawMany()` but aliases seems not to be binded in entities.","metadata":{"transformedAt":"2026-08-18T18:33:44.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":113,"estimatedTokens":992}}107{"id":"stack-53473153","source":"stackoverflow","questionId":53473153,"title":"How to construct DTO in Nest.js for @Body","tags":["javascript","nestjs","typeorm"],"text":"Title: How to construct DTO in Nest.js for @Body\nTags: javascript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am a beginner in Nest.js and I found it extremely good. I read the official docs and learned about DTOs. When My Body is like this:\n\n\r\n\r\n\n```\n{\r\n \"username\" : \"username\",\r\n \"password\" : \"password\"\r\n}\n```\n\n\r\n\r\n\r\n\nthen I can simply create `user.dto.ts` like this:\n\n\r\n\r\n\n```\nimport { IsNotEmpty } from 'class-validator';\r\n\r\nexport class UserDTO {\r\n @IsNotEmpty()\r\n username: string;\r\n @IsNotEmpty()\r\n password: string;\r\n}\n```\n\n\r\n\r\n\r\n\nThen I use this in my controller like this.\n\n\r\n\r\n\n```\n@Post('login')\r\n @UsePipes(new ValidationPipe())\r\n login(@Body() data: UserDTO) {\r\n return this.userService.login(data);\r\n }\n```\n\n\r\n\r\n\r\n\nBut my question is what if my Body is something like this.\n\n\r\n\r\n\n```\n{\r\n \"data\": {\r\n \"username\": \"username\",\r\n \"password\": \"password\",\r\n }\r\n}\n```\n\n\r\n\r\n\r\n\nthen what modifications I need to make in my ```user.dto.ts`` file to make it work? Thanks\n\n========================================\n\nTop Answer:\nYou may create a wrapper class that would carry your dto such as\n\n```\nexport class Data {\n\n @ApiModelProperty()\n readonly data: T;\n\n constructor(data: any = {}) {\n this.data = data;\n }\n}\n```\n\nand in your controller you will have\n\n```\n@Post('login')\n@UsePipes(new ValidationPipe())\nlogin(@Body() data: Data) {\n return this.userService.login(data);\n}\n```\n\nin your service you will do something like\n\n```\nreturn new Data(this.userDto);\n```\n\n========================================\n\nCode:\n```js\n{\n \"username\" : \"username\",\n \"password\" : \"password\"\n}\n```\n\n```js\nimport { IsNotEmpty } from 'class-validator';\n\nexport class UserDTO {\n @IsNotEmpty()\n username: string;\n @IsNotEmpty()\n password: string;\n}\n```\n\n```js\n@Post('login')\n @UsePipes(new ValidationPipe())\n login(@Body() data: UserDTO) {\n return this.userService.login(data);\n }\n```\n\n```js\n{\n \"data\": {\n \"username\": \"username\",\n \"password\": \"password\",\n }\n}\n```\n\n```text\nuser.dto.ts\n```\n\n```text\n@Post('login')\n@UsePipes(new ValidationPipe())\nlogin(@Body('data') data: UserDTO) {\n // data will be your req.body.data which is your UserDTO\n return this.userService.login(data);\n}\n```\n\n```text\nDTO\n```\n\n```text\n@Body()\n```\n\n```text\n@Body(path?: string)\n```\n\n```text\n@Body()\n```\n\n```text\n@Body()\n```\n\n```text\nreq.body\n```\n\n```text\n@Body('path')\n```\n\n```text\nreq.body.path\n```\n\n```text\nreq.body['path']\n```\n\n```text\n'data'\n```\n\n```text\n@Body('data')\n```\n\n```text\nreq.body.data\n```\n\n```text\nDTO\n```\n\n```text\nexport class Data<T> {\n\n @ApiModelProperty()\n readonly data: T;\n\n constructor(data: any = {}) {\n this.data = data;\n }\n}\n```\n\n```text\n@Post('login')\n@UsePipes(new ValidationPipe())\nlogin(@Body() data: Data<UserDTO>) {\n return this.userService.login(data);\n}\n```\n\n```text\nreturn new Data(this.userDto);\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":237,"estimatedTokens":708}}108{"id":"stack-70137558","source":"stackoverflow","questionId":70137558,"title":"Does TypeORM provide transactions for different repositories?","tags":["nestjs","typeorm"],"text":"Title: Does TypeORM provide transactions for different repositories?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nCurrently, three different repositories have something to deal with as a single transaction.\n\nMy service code is written as follows. But unlike what I thought, each repository is generating its own transaction. How can I solve this problem?\n\n```\n// TrimService\n\n@Injectable()\nexport class TrimService {\n constructor(\n private readonly trimRepository: TrimRepository,\n private readonly tireRepository: TireRepository,\n private readonly userRepository: UserRepository\n ) {}\n\n async saveUserTrim(saveUserTrimDto: SaveUserTrimDto, res) {\n const queryRunner = await getConnection().createQueryRunner();\n await queryRunner.startTransaction();\n\n try {\n const findUser: User = await this.userRepository.findUser(\n saveUserTrimDto.id,\n queryRunner.manager\n );\n\n const createTrim: Trim = await this.trimRepository.saveUserTrim(\n findUser,\n saveUserTrimDto.trimId,\n queryRunner.manager\n );\n\n await this.tireRepository.saveTrimTire(\n createTrim,\n res,\n queryRunner.manager\n );\n\n await queryRunner.commitTransaction();\n return createTrim;\n } catch (err) {\n console.log(err);\n await queryRunner.rollbackTransaction();\n } finally {\n await queryRunner.release();\n }\n }\n}\n```\n\n```\n// userRepository\n\n@EntityRepository(User)\nexport class UserRepository extends Repository {\n async findUser(\n id: string,\n @TransactionManager() transactionManager?: EntityManager\n ) {\n const findUser = await this.findOne({ id: id });\n\n if (!findUser) {\n throw new NotFoundUserException();\n }\n\n return findUser;\n }\n}\n```\n\n========================================\n\nTop Answer:\nRemove queryRunner.manager from saveUserTrim method and try below code.\nIt works for me.\n\n```\nconst createTrim: Trim = await queryRunner.manager.getRepository(Trim).saveUserTrim(\n findUser,\n saveUserTrimDto.trimId\n );\n```\n\n========================================\n\nCode:\n```js\n// TrimService\n\n@Injectable()\nexport class TrimService {\n constructor(\n private readonly trimRepository: TrimRepository,\n private readonly tireRepository: TireRepository,\n private readonly userRepository: UserRepository\n ) {}\n\n async saveUserTrim(saveUserTrimDto: SaveUserTrimDto, res) {\n const queryRunner = await getConnection().createQueryRunner();\n await queryRunner.startTransaction();\n\n try {\n const findUser: User = await this.userRepository.findUser(\n saveUserTrimDto.id,\n queryRunner.manager\n );\n\n const createTrim: Trim = await this.trimRepository.saveUserTrim(\n findUser,\n saveUserTrimDto.trimId,\n queryRunner.manager\n );\n\n await this.tireRepository.saveTrimTire(\n createTrim,\n res,\n queryRunner.manager\n );\n\n await queryRunner.commitTransaction();\n return createTrim;\n } catch (err) {\n console.log(err);\n await queryRunner.rollbackTransaction();\n } finally {\n await queryRunner.release();\n }\n }\n}\n```\n\n```js\n// userRepository\n\n@EntityRepository(User)\nexport class UserRepository extends Repository<User> {\n async findUser(\n id: string,\n @TransactionManager() transactionManager?: EntityManager\n ) {\n const findUser = await this.findOne({ id: id });\n\n if (!findUser) {\n throw new NotFoundUserException();\n }\n\n return findUser;\n }\n}\n```\n\n```js\n// TrimService\n\n@Injectable()\nexport class TrimService {\n constructor(\n private readonly trimRepository: TrimRepository,\n private readonly tireRepository: TireRepository,\n private readonly userRepository: UserRepository\n ) {}\n\n async saveUserTrim(saveUserTrimDto: SaveUserTrimDto, res) {\n const queryRunner = await getConnection().createQueryRunner();\n await queryRunner.startTransaction();\n\n const findUser: User = await this.userRepository.findUser(\n saveUserTrimDto.id\n );\n\n try {\n const createTrim: Trim = await this.trimRepository.saveUserTrim(\n queryRunner.manager,\n findUser,\n saveUserTrimDto.trimId\n );\n\n await this.tireRepository.saveTrimTire(\n queryRunner.manager,\n createTrim,\n res\n );\n\n await queryRunner.commitTransaction();\n return createTrim;\n } catch (err) {\n console.log(err);\n await queryRunner.rollbackTransaction();\n } finally {\n await queryRunner.release();\n }\n }\n}\n```\n\n```js\n// TrimRepository\n\n@EntityRepository(Trim)\nexport class TrimRepository extends Repository<Trim> {\n async saveUserTrim(\n @TransactionManager() transactionManager: EntityManager,\n findUser: User,\n trimId: number\n ) {\n const findTrim = await transactionManager.findOne(Trim, {\n trimId: trimId,\n user: findUser\n });\n\n if (findTrim) {\n throw new TrimOverlapException();\n }\n\n const createTrim: Trim = await transactionManager.create(Trim, {\n trimId: trimId,\n user: findUser\n });\n\n return await transactionManager.save(Trim, createTrim);\n }\n}\n```\n\n```text\nconst createTrim: Trim = await queryRunner.manager.getRepository(Trim).saveUserTrim(\n findUser,\n saveUserTrimDto.trimId\n );\n```\n\n========================================\n\nComments:\n- Oh gosh, you saved my life man!","metadata":{"transformedAt":"2026-08-18T18:33:44.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":239,"estimatedTokens":1425}}109{"id":"stack-60582058","source":"stackoverflow","questionId":60582058,"title":"Typeorm relationships - save by id","tags":["nestjs","typeorm"],"text":"Title: Typeorm relationships - save by id\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI've been kinda confused by the relationships as I'm used to save relationship by id, while docs and examples I found suggest to get the entire object and use that instead (Isn't this strange???)\n\nI found this on github addressing this issue ( https://github.com/typeorm/typeorm/issues/447 ) , where they suggest to use an object with just the id property, but it's from 2017. Is that a good way to do it ? And is it still the only way to do it ? (I find it pretty lame tbh)\n\n```\nasync create( @Body() product: Product) {\n product.category = { id: product.category };\n return { payload: await this.repository.persist(product) };\n}\n```\n\nAnother one suggested to name the column as categoryId and it would work as expected (with id instead of object) but WHY? What does the name have to do with that ??\n\n```\n@Entity()\nclass Product {\n\n @Column({ type: \"int\", nullable: true })\n categoryId: number;\n\n @ManyToOne(type => Category)\n @JoinColumn({ name: \"categoryId\" })\n category: Category;\n\n}\n```\n\nI'm just confused, help ^_^\n\n========================================\n\nTop Answer:\nAccording to this GitHub thread, it seems you can also do something like this:\n\n```\nproduct.category = { id: 1 }\nproduct.save()\n\n// Or\nproduct.category = new Category().id = 1\nproduct.save()\n```\n\n========================================\n\nCode:\n```js\nasync create( @Body() product: Product) {\n product.category = <any>{ id: product.category };\n return { payload: await this.repository.persist(product) };\n}\n```\n\n```js\n@Entity()\nclass Product {\n\n @Column({ type: \"int\", nullable: true })\n categoryId: number;\n\n @ManyToOne(type => Category)\n @JoinColumn({ name: \"categoryId\" })\n category: Category;\n\n}\n```\n\n```text\nproduct.category = <any>3;\n// or\nproduct['category' as any] = 3;\nrepository.save(product) // I don't know how you have the persist() method.\n```\n\n```text\nproduct.category\n```\n\n```text\nCategory\n```\n\n```text\ncategory\n```\n\n```text\nCategory | number\n```\n\n```text\ncategory\n```\n\n```text\ncategoryId\n```\n\n```text\ncategoryId\n```\n\n```text\nname: 'actual_name'\n```\n\n```text\n@Column\n```\n\n```text\ncolumnId\n```\n\n```text\ncolumn\n```\n\n```js\nproduct.category = { id: 1 }\nproduct.save()\n\n// Or\nproduct.category = new Category().id = 1\nproduct.save()\n```\n\n```text\nproduct.category = Object.assign( new Category(), {\n id: id,\n});\n```\n\n```text\nroduct.category = { id: 1 }\n```\n\n```text\nproduct.category = new Category().id = 1\n```\n\n```text\nproduct.category = { id: 3 } as Category;\n```\n\n========================================\n\nComments:\n- What do you mean by \"you can just do product.category = 3\" ? I get a type error on that, do you mean that it works even if it gives a type error?\n- You are right. I was testing my code in node REPL and it worked because it's just js. I will edit my answer.\n- It's absurd that this still seems the only way to update related entities without setting the whole object. Did you ever manage to find a cleaner method?","metadata":{"transformedAt":"2026-08-18T18:33:44.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":156,"estimatedTokens":761}}110{"id":"stack-58529950","source":"stackoverflow","questionId":58529950,"title":"Import statement breaks typeorm enitities when registered through config.json file","tags":["javascript","node.js","typescript","koa","typeorm"],"text":"Title: Import statement breaks typeorm enitities when registered through config.json file\nTags: javascript, node.js, typescript, koa, typeorm\nSource: Stack Overflow\n\nQuestion:\nFollowing official docs, I created small koa/typeorm/postgres app. When I was using `createConnection` with config, importing entities in the same file, app was working fine, but typeorm cli coudn't find config file so I tried moving config to \"ormconfig.json\". Now I get this error:\n\n`SyntaxError: Cannot use import statement outside a module`\n\nIt looks as if typeorm isn't able to use es6 features.\n\nMy `ormconfig.json`:\n\n```\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": ****,\n \"password\": ****,\n \"database\": ****,\n \"synchronize\": true,\n \"entities\": [\"src/entity/**/*.ts\"],\n \"migrations\": [\"src/migration/**/*.ts\"],\n \"subscribers\": [\"src/subscriber/**/*.ts\"],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\nMy `tsconfig.json`:\n\n```\n{\n \"compilerOptions\": {\n \"lib\": [\"es5\", \"es6\"],\n \"target\": \"es6\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"outDir\": \"./dist\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n },\n \"exclude\": [\"node_modules\"]\n}\n```\n\nFile with error:\n\n```\nimport {\n BaseEntity,\n Column,\n Entity,\n PrimaryGeneratedColumn,\n CreateDateColumn,\n ManyToOne\n} from 'typeorm';\nimport { IsIn, IsPositive, IsNotEmpty } from 'class-validator';\n\nimport { LOAN_TYPE } from '../consts';\nimport { User } from './user';\n\n@Entity('loans')\nexport class Loan extends BaseEntity {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @CreateDateColumn({ type: 'timestamp' })\n public createdAt: Date;\n\n @Column()\n @IsNotEmpty()\n @IsPositive()\n public amount: number;\n\n @Column({ type: 'enum', enum: LOAN_TYPE })\n @IsNotEmpty()\n @IsIn(Object.values(LOAN_TYPE))\n public type: LOAN_TYPE;\n\n @Column({ default: false })\n public approvalStatus: boolean;\n\n @ManyToOne(type => User, user => user.loans)\n @IsNotEmpty()\n public user: User;\n}\n\nexport default Loan;\n```\n\n========================================\n\nTop Answer:\n- Make sure you have `\"module\": \"commonjs\"` in `\"compilerOptions\"` of `tsconfig.json`\n\n- Run typeorm cli using ts-node: `ts-node ./node_modules/typeorm/cli.js`\n\nSee docs\n\n========================================\n\nCode:\n```text\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": ****,\n \"password\": ****,\n \"database\": ****,\n \"synchronize\": true,\n \"entities\": [\"src/entity/**/*.ts\"],\n \"migrations\": [\"src/migration/**/*.ts\"],\n \"subscribers\": [\"src/subscriber/**/*.ts\"],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\n```text\n{\n \"compilerOptions\": {\n \"lib\": [\"es5\", \"es6\"],\n \"target\": \"es6\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"outDir\": \"./dist\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n },\n \"exclude\": [\"node_modules\"]\n}\n```\n\n```text\nimport {\n BaseEntity,\n Column,\n Entity,\n PrimaryGeneratedColumn,\n CreateDateColumn,\n ManyToOne\n} from 'typeorm';\nimport { IsIn, IsPositive, IsNotEmpty } from 'class-validator';\n\nimport { LOAN_TYPE } from '../consts';\nimport { User } from './user';\n\n@Entity('loans')\nexport class Loan extends BaseEntity {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @CreateDateColumn({ type: 'timestamp' })\n public createdAt: Date;\n\n @Column()\n @IsNotEmpty()\n @IsPositive()\n public amount: number;\n\n @Column({ type: 'enum', enum: LOAN_TYPE })\n @IsNotEmpty()\n @IsIn(Object.values(LOAN_TYPE))\n public type: LOAN_TYPE;\n\n @Column({ default: false })\n public approvalStatus: boolean;\n\n @ManyToOne(type => User, user => user.loans)\n @IsNotEmpty()\n public user: User;\n}\n\nexport default Loan;\n```\n\n```text\ncreateConnection\n```\n\n```text\nSyntaxError: Cannot use import statement outside a module\n```\n\n```text\normconfig.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\n\"entities\"\n```\n\n```text\normconfig.json\n```\n\n```text\n[\"dist/entity/**/*.js\"]\n```\n\n```text\n\"entitiesDir\"\n```\n\n```text\n\"dist/entity\"\n```\n\n```text\n\"module\": \"commonjs\"\n```\n\n```text\n\"compilerOptions\"\n```\n\n```text\ntsconfig.json\n```\n\n```text\nts-node ./node_modules/typeorm/cli.js\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n ...\n autoLoadEntities: true,\n }),\n ],\n})\nexport class AppModule {}\n```\n\n```text\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": ****,\n \"password\": ****,\n \"database\": ****,\n \"synchronize\": true,\n \"entities\": [\"dist/entity/**/*.js\"],\n \"migrations\": [\"dist/migration/**/*.js\"],\n \"subscribers\": [\"dist/subscriber/**/*.js\"],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\n========================================\n\nComments:\n- That was it, I figured it out later that night. It was confusing because I was following docs very closely.\n- @robfz: I was just facing the same issue, and know that the proposed solution works, but with my `synchronize: true` setting, it won't show an updated table for my entity, so I'm trying to point it to `src` since there must be issues with it on build that's showing up in the `dist` entity. The question: is there a reason why it doesn't work with `src` path even though docs show it that way?\n- having to use the transpiled code in development is an abomination.\n- The other answer of invoking the CLI via `ts-node` seems a bit nicer: `npx ts-node ./node_modules/typeorm/cli.js migration:generate -n Init`\n- Why down vote? Accepted answer is misleading, there is no need to point configuration to `dist` directory. If your entities are in typescript you should use `ts-node` to run CLI, as stated in the docs.\n- I second it. The accepted answer is misleading. this is the correct answer! Thanks, @joseph for the correct answer! You saved my time!\n- Totally agree too, during e2e test, it doesn't work, I had to use `https://docs.nestjs.com/techniques/database#auto-load-entiti‌​es` to autoload entities. Because during test, it's using ts-node transpiling code on the fly (in memory) and the dist directory is not present. So at the end. best option to work in any situation\n- a related github issue github.com/typeorm/typeorm/issues/3079#issuecomment-44971461‌​4\n- Side-note: If you don't have `ts-node` installed globally you can invoke it prefixed with `npx`, e.g.: `npx ts-node ./node_modules/typeorm/cli.js migration:generate -n Init`","metadata":{"transformedAt":"2026-08-18T18:33:44.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":284,"estimatedTokens":1672}}111{"id":"stack-63838204","source":"stackoverflow","questionId":63838204,"title":"Error when creating a new migration using TypeORM and NestJs with Typescript","tags":["node.js","typescript","npm","nestjs","typeorm"],"text":"Title: Error when creating a new migration using TypeORM and NestJs with Typescript\nTags: node.js, typescript, npm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a node application using typescript and I'm trying to create a new migration, following the documentation of the TypeORM.\n\nFirst I installed the CLI, set up my connection options like this and when I try to run this command:\n\n`npm run typeorm migration:create -- -n migrationNameHere`\nI get the following error:\n\nError during migration creation: TypeError: Cannot read property 'startsWith' of undefined\nat Object. (...\\src\\commands\\MigrationCreateCommand.ts:62:37)\nat step (...\\node_modules\\typeorm\\node_modules\\tslib\\tslib.js:141:27)\nat Object.throw (...\\node_modules\\typeorm\\node_modules\\tslib\\tslib.js:122:57)\nat rejected (...\\node_modules\\typeorm\\node_modules\\tslib\\tslib.js:113:69) npm ERR!\ncode ELIFECYCLE npm ERR! errno 1 npm ERR! backend@0.0.1 typeorm: node\n--require ts-node/register ./node_modules/typeorm/cli.js \"migration:create\" \"-n\" \"migrationNameHere\"` npm ERR! Exit status 1\n\nThese are my nest dependencies in package.json:\n\nMy node version is **v12.14.1**, nestjs is **7.0.0** and nestjs/typeorm is **7.1.3**\n\nMy app.module.ts is like this:\n\n```\nTypeOrmModule.forRoot({\n type: 'mysql',\n host: database().host,\n port: parseInt(database().port),\n username: database().username,\n password: database().password,\n database: database().schema,\n entities: [Question, QuestionOption],\n migrations: ['migration/*.js'],\n cli: {\n migrationsDir: 'migration'\n },\n synchronize: true,\n })\n```\n\nDoes anybody has ever faced this sort of problem?\n\n========================================\n\nCode:\n```text\nTypeOrmModule.forRoot({\n type: 'mysql',\n host: database().host,\n port: parseInt(database().port),\n username: database().username,\n password: database().password,\n database: database().schema,\n entities: [Question, QuestionOption],\n migrations: ['migration/*.js'],\n cli: {\n migrationsDir: 'migration'\n },\n synchronize: true,\n })\n```\n\n```text\nnpm run typeorm migration:create -- -n migrationNameHere\n```\n\n```text\nnpx typeorm migration:create -n YourName -d src/migrations\n```\n\n========================================\n\nComments:\n- Thanks, the secret was the -d src/migrations, with that, the migration file was created. One strange thing is that I configured that in the app.module.ts (see migrationDir), where I tried to add src/migration too but the same error happened, but your solution worked pretty well","metadata":{"transformedAt":"2026-08-18T18:33:44.691Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":77,"estimatedTokens":638}}112{"id":"stack-62460079","source":"stackoverflow","questionId":62460079,"title":"TypeORM foreign key not showing on a find call","tags":["node.js","nestjs","typeorm"],"text":"Title: TypeORM foreign key not showing on a find call\nTags: node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\n```\nexport class Contact extends BaseEntity {\n ...\n @ManyToOne(() => User, { nullable: false })\n @JoinColumn({ name: 'user_id' })\n user: User;\n ...\n}\n\nconst repo = new Repository ();\nconst response = await repo.findAll();\nconsole.log(response);\n\nconsole.log:\n[\n Contact {\n id: 1,\n ...\n },\n Contact {\n id: 2,\n ...\n }\n]\n```\n\nI am trying to fetch all the columns included on my `Contact`, but I only able to fetch the columns that does not have any relationship from the other entity.\nIt does not include user_id columns. Why can't to get foreign key for instance?\n\n========================================\n\nTop Answer:\nYou can set `eager: true` in order to load User with the find command\n\n```\n@ManyToOne(() => User, { nullable: false, eager: true })\n @JoinColumn({ name: 'user_id' })\n user: User;\n```\n\nLink: https://orkhan.gitbook.io/typeorm/docs/relations\n\n========================================\n\nCode:\n```text\nexport class Contact extends BaseEntity {\n ...\n @ManyToOne(() => User, { nullable: false })\n @JoinColumn({ name: 'user_id' })\n user: User;\n ...\n}\n\nconst repo = new Repository<User> ();\nconst response = await repo.findAll();\nconsole.log(response);\n\nconsole.log:\n[\n Contact {\n id: 1,\n ...\n },\n Contact {\n id: 2,\n ...\n }\n]\n```\n\n```text\nContact\n```\n\n```text\nexport class Contact extends BaseEntity {\n ...\n // add column explicitly here\n @Column({ name: 'user_id' })\n userId: number;\n\n @ManyToOne(() => User, { nullable: false })\n @JoinColumn({ name: 'user_id' })\n user: User;\n ...\n}\n```\n\n```text\nuserId\n```\n\n```text\n@JoinColumn\n```\n\n```text\n@ManyToOne(() => User, { nullable: false, eager: true })\n @JoinColumn({ name: 'user_id' })\n user: User;\n```\n\n```text\neager: true\n```\n\n========================================\n\nComments:\n- Btw, should I add `{ nullable: false }` to `userId` column?\n- Sure I believe you could add whatever you want ;)\n- \"eager: true\" => now I can see foreign keys in response body. Thanks !","metadata":{"transformedAt":"2026-08-18T18:33:44.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":118,"estimatedTokens":515}}113{"id":"stack-29577235","source":"stackoverflow","questionId":29577235,"title":"Javascript node.js ORM that follows data-mapper pattern","tags":["javascript","node.js","orm","datamapper","typeorm"],"text":"Title: Javascript node.js ORM that follows data-mapper pattern\nTags: javascript, node.js, orm, datamapper, typeorm\nSource: Stack Overflow\n\nQuestion:\nI've been working with active record and data mapper implementations of ORM enough to know the problems with using active record implemented ORM in my large projects. Right now I'm thinking to migrate one of my projects to node.js and trying to find the similar tools Im using right now. After research I didn't found any node.js ORM that follows data mapper pattern. They all are active record. Maybe I missing something, and you can tell me is there is a good popular ORM for node.js that doesn't active record pattern?\n\nThe libraries Ive looked on:\n\n- http://docs.sequelizejs.com/\n\n- https://github.com/dresende/node-orm2\n\n- http://bookshelfjs.org/\n\n- some others\n\n========================================\n\nTop Answer:\nI wrote an ORM for Node.js called node-data-mapper; it's available here: https://www.npmjs.com/package/node-data-mapper. It's an ORM for Node.js that uses the data-mapper pattern. The developer uses plain old JavaScript objects when reading from and writing to the database. Relationships between tables are not rigidly defined, which makes joining very flexible--in my opinion, anyway--albeit somewhat verbose. The actual data mapping algorithm is fast and short, and the complexity is linear (the transformation from tabular DB data to a normalized JavaScript object is done in one loop).\n\nI also did my best to make it fairly fault tolerant. There's 100% code coverage and, while I know that doesn't prove the absence of defects, I did try to test as thoroughly as possible.\n\nI modeled the interface very loosely after Doctrine 1. (I've used LINQ, Doctrine 1 and 2, and Hibernate fairly extensively, and of those ORMs I like the interface for Doctrine 1 the best. node-data-mapper is not a JavaScript port of Doctrine by any means, though, and the interface is significantly different.) The query interface returns promises using the deferred module.\n\nI modeled the conditions (e.g. WHERE and ON clauses) after MongoDB's conditions. Hopefully that makes the conditions somewhat intuitive while providing a way for making reusable queries (specifically, complex SELECT queries that can be filtered securely in many different ways). The conditions are treated as a domain-specific language, and are lexed, parsed, and compiled.\n\nAnyway, the module is something that I use in my personal projects, but I'd love to get some feedback from other developers in the community! I tried to provide plenty of examples to get people up and running quickly. Currently the module supports MySQL only, but I'm working on adding support for MSSQL.\n\n========================================\n\nComments:\n- Try StrongLoop, you can map types to tables and generate a REST client to be used with the REST API generated by the mappings. Dont know if this is what you are looking for but doesnt hurt putting it out there as a comment? :)\n- @furier it doesnt look like orm\n- actually it does make sense in javascript too. I have already worked with client side javascript libraries that follows active record pattern and they just was killing my app util I didnt rewrite the same libraries into data mapper style\n- active record and data mapper are completely different patterns with different designs. Doesn't matter if it's JavaScript or Java, the pattern is likely the same.","metadata":{"transformedAt":"2026-08-18T18:33:44.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":37,"estimatedTokens":857}}114{"id":"stack-59107360","source":"stackoverflow","questionId":59107360,"title":"Is there a way to auto create a databse in typeORM?","tags":["node.js","nestjs","typeorm"],"text":"Title: Is there a way to auto create a databse in typeORM?\nTags: node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am migrating from sequelizeORM to typeORM. In sequelize-cli there are nice commands to drop database and create a new one for example:\n\n```\nnode_modules/.bin/sequelize db:drop\nnode_modules/.bin/sequelize db:create\nnode_modules/.bin/sequelize db:migrate\n```\n\nOk, for typeORM I know how to run migration but I can't find anywhere how to automatically create or drop a database. Tnx in advance.\n\n========================================\n\nTop Answer:\nyou can use the CLI tool `typeorm schema:drop` or if you want to drop and recreate the database on each startup, you can use\n\n```\n{\n...\n dropSchema: true,\n... \n \"migrations\": [\n \"dist/migrations/**/*.js\"\n ]\n}\n```\n\nwhere you do your connection options and set migrations path, and so forth.\n\n========================================\n\nCode:\n```text\nnode_modules/.bin/sequelize db:drop\nnode_modules/.bin/sequelize db:create\nnode_modules/.bin/sequelize db:migrate\n```\n\n```js\nimport {createDatabase} from \"typeorm-extension\";\n\n(async () => {\n await createDatabase({ifNotExist: true});\n \n await dropDatabase({ifExist: true});\n\n process.exit(0);\n})();\n```\n\n```js\ncreateDatabase({ifNotExist: true, characterSet: \"UTF8\"});\n```\n\n```js\ncreateDatabase({ifNotExist: true, charset: \"utf8mb4_general_ci\", characterSet: \"utf8mb4\"});\n```\n\n```text\ncreate\n```\n\n```text\ndrop\n```\n\n```text\ncharset\n```\n\n```text\ncharacterSet\n```\n\n```text\ncharset\n```\n\n```text\ncharacterSet\n```\n\n```text\ncreateDatabase()\n```\n\n```text\n{\n...\n dropSchema: true,\n... \n \"migrations\": [\n \"dist/migrations/**/*.js\"\n ]\n}\n```\n\n```text\ntypeorm schema:drop\n```\n\n========================================\n\nComments:\n- Be careful not to use it on the production environment!!!\n- Production environments should always be handled with care 🙈🙆♂️ Although if you have seeds and “runMigrations: true” you might be able to get away with it, depending on circumstances\n- does it really answer the question? What is the way to create database?\n- @РоманСоляник Setting 'dropSchema: true' drops the database when the application is started, after which the database specified with entities and migrations (given that runMigrations is set to true) is created. So in effect it's a sort of \"drop and recreate\".\n- Be careful about using this library on production, any unwanted changes in the library can wipe out your database!","metadata":{"transformedAt":"2026-08-18T18:33:44.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":113,"estimatedTokens":613}}115{"id":"stack-52797727","source":"stackoverflow","questionId":52797727,"title":"Process of testing with TypeORM and Nestjs, and jest using mocks?","tags":["testing","tdd","nestjs","typeorm"],"text":"Title: Process of testing with TypeORM and Nestjs, and jest using mocks?\nTags: testing, tdd, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\n**This question can likely be generalized to stubbing repositories in a service and how to properly test and provide coverage in the context of this question.**\n\nI am in the process of learning more about testing, but am stuck with how to properly perform testing that involves the DB. \n\nI have a User entity that defines the columns and some initial validation logic.\n\n```\nimport { IsAlphanumeric, IsEmail, MinLength } from 'class-validator';\n import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n @Entity()\n export class User {\n @PrimaryGeneratedColumn()\n public id!: number;\n\n @Column()\n public name!: string;\n\n @IsEmail()\n @Column()\n public email!: string;\n\n @MinLength(8)\n @Column()\n public password!: string;\n }\n```\n\nAnd I have a UserService that injects the Repository for the entity.\n\n```\nimport { Injectable } from '@nestjs/common';\n import { InjectRepository } from '@nestjs/typeorm';\n import { validateOrReject } from 'class-validator';\n import { Repository } from 'typeorm';\n import { CreateUserDTO } from './dto/create-user.dto';\n import { User } from './user.entity';\n\n @Injectable()\n export class UserService {\n constructor(\n @InjectRepository(User) private readonly userRepository: Repository\n ) {}\n\n public async create(dto: CreateUserDTO) {\n const user = this.userRepository.create(dto);\n await validateOrReject(user);\n await this.userRepository.save(user);\n }\n\n public async findAll(): Promise {\n return await this.userRepository.find();\n }\n\n public async findByEmail(email: string): Promise {\n return await this.userRepository.findOne({\n where: {\n email,\n },\n });\n }\n }\n```\n\nAnd here is my preliminary test so you can my train of thought...\n\n```\nimport { Test, TestingModule } from '@nestjs/testing';\n import { getRepositoryToken } from '@nestjs/typeorm';\n import { User } from './user.entity';\n import { UserService } from './user.service';\n\n const createMock = jest.fn((dto: any) => {\n return dto;\n });\n\n const saveMock = jest.fn((dto: any) => {\n return dto;\n });\n\n const MockRepository = jest.fn().mockImplementation(() => {\n return {\n create: createMock,\n save: saveMock,\n };\n });\n const mockRepository = new MockRepository();\n\n describe('UserService', () => {\n let service: UserService;\n\n beforeAll(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n UserService,\n {\n provide: getRepositoryToken(User),\n useValue: mockRepository,\n },\n ],\n }).compile();\n service = module.get(UserService);\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n\n it('should not create invalid user', async () => {\n // ??\n });\n });\n```\n\nSo while I can make the test run and everything, I am not sure what I am actually supposed to be testing. I can obviously test that it validates on create, and for other things like findAll, I feel like I am just mocking the database? For me to properly test this, would it need to be connected to a database so I can check that the right data is returned?\n\nThe nest documents say \"we usually want to avoid any database connection\", but doesn't doing that defeat the purpose since we aren't *really* testing the functionality? Because while I can mock that the save returns a value, I am not testing for any errors that can occur with unique columns, nullable data, incrementing values to be set, etc... right?\n\n========================================\n\nTop Answer:\nWhat @AyKarsi suggest is better than nothing, but it's still a bad practice.\n\nUnit testing should mock databases and third party API calls.\n\nIntegration testing should test what has been mocked with the real database, and that part only.\n\nEnd-to-end testing is there to check that the whole app is well connected altogether.\n\nFor more details, you can read : https://martinfowler.com/articles/practical-test-pyramid.html\n\n========================================\n\nCode:\n```js\nimport { IsAlphanumeric, IsEmail, MinLength } from 'class-validator';\n import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n @Entity()\n export class User {\n @PrimaryGeneratedColumn()\n public id!: number;\n\n @Column()\n public name!: string;\n\n @IsEmail()\n @Column()\n public email!: string;\n\n @MinLength(8)\n @Column()\n public password!: string;\n }\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\n import { InjectRepository } from '@nestjs/typeorm';\n import { validateOrReject } from 'class-validator';\n import { Repository } from 'typeorm';\n import { CreateUserDTO } from './dto/create-user.dto';\n import { User } from './user.entity';\n\n @Injectable()\n export class UserService {\n constructor(\n @InjectRepository(User) private readonly userRepository: Repository<User>\n ) {}\n\n public async create(dto: CreateUserDTO) {\n const user = this.userRepository.create(dto);\n await validateOrReject(user);\n await this.userRepository.save(user);\n }\n\n public async findAll(): Promise<User[]> {\n return await this.userRepository.find();\n }\n\n public async findByEmail(email: string): Promise<User | undefined> {\n return await this.userRepository.findOne({\n where: {\n email,\n },\n });\n }\n }\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing';\n import { getRepositoryToken } from '@nestjs/typeorm';\n import { User } from './user.entity';\n import { UserService } from './user.service';\n\n const createMock = jest.fn((dto: any) => {\n return dto;\n });\n\n const saveMock = jest.fn((dto: any) => {\n return dto;\n });\n\n const MockRepository = jest.fn().mockImplementation(() => {\n return {\n create: createMock,\n save: saveMock,\n };\n });\n const mockRepository = new MockRepository();\n\n describe('UserService', () => {\n let service: UserService;\n\n beforeAll(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n UserService,\n {\n provide: getRepositoryToken(User),\n useValue: mockRepository,\n },\n ],\n }).compile();\n service = module.get<UserService>(UserService);\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n\n it('should not create invalid user', async () => {\n // ??\n });\n });\n```\n\n========================================\n\nComments:\n- \"I am not sure what I am actually supposed to be testing\", exactly, because you basically have nothing to test in your service. The only thing you could test is if your service properly call the repository methods you want it to call and with the proper parameters and for that you will use a \"spyOn\" or \"toHaveBeenCalledWith\". TypeORM is already a tested library, so you don't want to test TypeORM. Testing against a database is a functional test, not a unit test, in that case, I would reorganize your test in a End-to-End fashion, calling your API endpoint and testing the database after the call.\n- Okay thank you I really appreciate the feedback. I ended up doing something really similar. I decided to use sqljs for the test database and have TypeORM setup to drop the DB after each test and to synchronize at the start of each test. It is still really fast, and like you said simplifies things greatly. Thanks!\n- In general, there is nothing bad about testing against the database, as long it not part of the unit test. And it's actually impossible to make e2e test without hitting the database. So, all depends of the use-case, the only important part is to not mix-up all your tests together.\n- @AyKarsi How can I import real database repository into my Test module?\n- I think it's OK to test with an one-off database such as SQLite `:memory:`, demo: stackoverflow.com/a/59483875/5172890\n- @kenberkeley your development database should match your production database though","metadata":{"transformedAt":"2026-08-18T18:33:44.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":250,"estimatedTokens":2030}}116{"id":"stack-61581755","source":"stackoverflow","questionId":61581755,"title":"Returning ID of inserted query in TypeORM and MySQL","tags":["typescript","typeorm"],"text":"Title: Returning ID of inserted query in TypeORM and MySQL\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI,m new to TypeORM and I have problem that I'm trying to solve.\nI'm wondering how to retrieve ID after INSERT query. \nI have column @PrimaryGeneratedColumn() with id number in my entity and my code looks similar to this:\n\n```\nawait getConnection()\n .createQueryBuilder()\n .insert()\n .into(Test)\n .values([\n { firstName: \"test\", lastName: \"test\" }\n ])\n .execute();\n```\n\nWhat I want to archieve is to return ID of inserted row after executing this function.\n\nEDIT: I'm using MySQL.\n\nIs that possible?\n\nThanks.\n\n========================================\n\nTop Answer:\nTry this\n\n```\nlet test: Test = [{ firstName: \"test\", lastName: \"test\" }];\ntest = await getRepository(Test).insert(test).generatedMaps[0];\n```\n\n========================================\n\nCode:\n```text\nawait getConnection()\n .createQueryBuilder()\n .insert()\n .into(Test)\n .values([\n { firstName: \"test\", lastName: \"test\" }\n ])\n .execute();\n```\n\n```text\nawait getConnection()\n .createQueryBuilder()\n .insert()\n .into(Test)\n .values([\n { firstName: \"test\", lastName: \"test\" }\n ])\n .returning(\"your_id_column_name\")\n .execute();\n```\n\n```text\n.returning(\"your_id_column_name\")\n```\n\n```text\nlet test: Test = [{ firstName: \"test\", lastName: \"test\" }];\ntest = await getRepository(Test).insert(test).generatedMaps[0];\n```\n\n```text\nconst testRepo = getRepository(Test) \nlet insert = await testRepo()\n .createQueryBuilder()\n .insert()\n .into(Test)\n .values([\n { firstName: \"test\", lastName: \"test\" }\n ])\n .execute();\nconsole.log(\"id: \",insert.raw.insertId);\n```\n\n```text\nqueryRunner.query('insert into .... returning *);\n```\n\n========================================\n\nComments:\n- I tried that also but it is only supported by Microsoft SQL and PostgreSQL. I forget to mention that I'm using MySQL.\n- Did you try using different strategy for insert? such as `Test.save({ firstName: \"test\", lastName: \"test\" })`\n- Thanks for good idea. I didn't know that strategy and now when I used it, all is working as expected.\n- Typeorm have many different ways to implement the same functionality, checkout BaseEntity, EntityManager, EntityRepository, Connection.\n- In case anyone wonders what `inserted` is, it is the literal word `inserted`.","metadata":{"transformedAt":"2026-08-18T18:33:44.691Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":98,"estimatedTokens":609}}117{"id":"stack-66193796","source":"stackoverflow","questionId":66193796,"title":"Using test database when e2e-testing NestJS","tags":["javascript","nestjs","e2e-testing","typeorm"],"text":"Title: Using test database when e2e-testing NestJS\nTags: javascript, nestjs, e2e-testing, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn this project, it uses NestJS along with TypeORM. For real API requests, CRUD operation is being operated on MySQL(which is using AWS RDS).\n\nNow I am trying to use SQLite(In-Memory) to test API results.\n\nI successfully implemented this in Unit Test, as the code below.\n\nFirst, below is `create-memory-db.ts`, which returns a connection to in-memory SQLite database.\n\n```\ntype Entity = Function | string | EntitySchema;\n\nexport async function createMemoryDB(entities: Entity[]) {\n return createConnection({\n type: 'sqlite',\n database: ':memory:',\n entities,\n logging: false,\n synchronize: true,\n });\n}\n```\n\n- And by using the exported function above, I successfully ran Unit test, like below.\n\n```\ndescribe('UserService Logic Test', () => {\n let userService: UserService;\n let connection: Connection;\n let userRepository: Repository;\n\n beforeAll(async () => {\n connection = await createMemoryDB([User]);\n userRepository = await connection.getRepository(User);\n userService = new UserService(userRepository);\n });\n\n afterAll(async () => {\n await connection.close();\n });\n\n afterEach(async () => {\n await userRepository.query('DELETE FROM users');\n });\n\n // testing codes.\n});\n```\n\nI am trying to do the same thing on e2e tests. I tried below code.\n\n```\n// user.e2e-spec.ts\n\ndescribe('UserController (e2e)', () => {\n let userController: UserController;\n let userService: UserService;\n let userRepository: Repository;\n let connection: Connection;\n let app: INestApplication;\n const NAME = 'NAME';\n const EMAIL = 'test@test.com';\n const PASSWORD = '12345asbcd';\n\n beforeAll(async () => {\n connection = await createMemoryDB([User]);\n userRepository = await connection.getRepository(User);\n userService = new UserService(userRepository);\n userController = new UserController(userService);\n\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [],\n controllers: [UserController],\n providers: [UserService],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n });\n\n afterAll(async () => {\n await connection.close();\n });\n\n afterEach(async () => {\n // await userRepository.query('DELETE FROM users');\n });\n\n it('[POST] /user : Response is OK if conditions are right', () => {\n const dto = new UserCreateDto();\n dto.name = NAME;\n dto.email = EMAIL;\n dto.password = PASSWORD;\n\n return request(app.getHttpServer())\n .post('/user')\n .send(JSON.stringify(dto))\n .expect(HttpStatus.CREATED);\n });\n});\n```\n\nI cannot create `UserModule` since it doesn't have a constructor with `Connection` parameter.\nThe code itself has no compile error, but gets results below when e2e test is executed.\n\n```\nNest can't resolve dependencies of the UserService (?). Please make sure that the argument UserRepository at index[0] is available in the RootTestModule context.\n\nPotential solutions:\n- If UserRepository is a provider, is it part of the current RootTestModule?\n- If UserRepository is exported from a seperate @Module, is that module imported within RootTestModule?\n @Module({\n imports: [/* The module containing UserRepository */]\n })\n\nTypeError: Cannot read property 'getHttpServer' of undefined.\n```\n\nAny help would be greatly appreciated. Thanks :)\n\n- UPDATE : New error occured after trying below.\n\n```\ndescribe('UserController (e2e)', () => {\n let userService: UserService;\n let userRepository: Repository;\n let connection: Connection;\n let app: INestApplication;\n const NAME = 'NAME';\n const EMAIL = 'test@test.com';\n const PASSWORD = '12345asbcd';\n\n beforeAll(async () => {\n connection = await createMemoryDB([User]);\n userRepository = await connection.getRepository(User);\n userService = new UserService(userRepository);\n\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [UserModule],\n })\n .overrideProvider(UserService)\n .useClass(userService)\n .compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n });\n\n afterAll(async () => {\n await connection.close();\n });\n\n afterEach(async () => {\n await userRepository.query('DELETE FROM users');\n });\n\n it('[POST] /user : Response is OK if conditions are right', async () => {\n const dto = new UserCreateDto();\n dto.name = NAME;\n dto.email = EMAIL;\n dto.password = PASSWORD;\n\n const result = await request(app.getHttpServer())\n .post('/user')\n .send(JSON.stringify(dto))\n .expect({ status: HttpStatus.CREATED });\n });\n});\n```\n\n- I checked if query is working, and was able to see that it is using SQLite database as I wanted. But new error appeared in console.\n\n```\nTypeError: metatype is not a constructor.\n\nTypeError: Cannot read property 'getHttpServer' of undefined.\n```\n\n========================================\n\nTop Answer:\nFor those looking for setup e2e tests that hit endpoints and assert the response body, you can do something like this:\n\n```\n// app.module.ts\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n useFactory: async (configService: ConfigService) => {\n if (process.env.APPLICATION_ENV === 'test') {\n return {\n type: 'sqlite',\n database: ':memory:',\n entities: [Entity],\n synchronize: true,\n }\n }\n return {\n // your default options\n };\n },\n }),\n ]\n})\n```\n\n========================================\n\nCode:\n```text\ntype Entity = Function | string | EntitySchema<any>;\n\nexport async function createMemoryDB(entities: Entity[]) {\n return createConnection({\n type: 'sqlite',\n database: ':memory:',\n entities,\n logging: false,\n synchronize: true,\n });\n}\n```\n\n```text\ndescribe('UserService Logic Test', () => {\n let userService: UserService;\n let connection: Connection;\n let userRepository: Repository<User>;\n\n beforeAll(async () => {\n connection = await createMemoryDB([User]);\n userRepository = await connection.getRepository(User);\n userService = new UserService(userRepository);\n });\n\n afterAll(async () => {\n await connection.close();\n });\n\n afterEach(async () => {\n await userRepository.query('DELETE FROM users');\n });\n\n // testing codes.\n});\n```\n\n```text\n// user.e2e-spec.ts\n\ndescribe('UserController (e2e)', () => {\n let userController: UserController;\n let userService: UserService;\n let userRepository: Repository<User>;\n let connection: Connection;\n let app: INestApplication;\n const NAME = 'NAME';\n const EMAIL = 'test@test.com';\n const PASSWORD = '12345asbcd';\n\n beforeAll(async () => {\n connection = await createMemoryDB([User]);\n userRepository = await connection.getRepository(User);\n userService = new UserService(userRepository);\n userController = new UserController(userService);\n\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [],\n controllers: [UserController],\n providers: [UserService],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n });\n\n afterAll(async () => {\n await connection.close();\n });\n\n afterEach(async () => {\n // await userRepository.query('DELETE FROM users');\n });\n\n it('[POST] /user : Response is OK if conditions are right', () => {\n const dto = new UserCreateDto();\n dto.name = NAME;\n dto.email = EMAIL;\n dto.password = PASSWORD;\n\n return request(app.getHttpServer())\n .post('/user')\n .send(JSON.stringify(dto))\n .expect(HttpStatus.CREATED);\n });\n});\n```\n\n```text\nNest can't resolve dependencies of the UserService (?). Please make sure that the argument UserRepository at index[0] is available in the RootTestModule context.\n\nPotential solutions:\n- If UserRepository is a provider, is it part of the current RootTestModule?\n- If UserRepository is exported from a seperate @Module, is that module imported within RootTestModule?\n @Module({\n imports: [/* The module containing UserRepository */]\n })\n\n\nTypeError: Cannot read property 'getHttpServer' of undefined.\n```\n\n```text\ndescribe('UserController (e2e)', () => {\n let userService: UserService;\n let userRepository: Repository<User>;\n let connection: Connection;\n let app: INestApplication;\n const NAME = 'NAME';\n const EMAIL = 'test@test.com';\n const PASSWORD = '12345asbcd';\n\n beforeAll(async () => {\n connection = await createMemoryDB([User]);\n userRepository = await connection.getRepository(User);\n userService = new UserService(userRepository);\n\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [UserModule],\n })\n .overrideProvider(UserService)\n .useClass(userService)\n .compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n });\n\n afterAll(async () => {\n await connection.close();\n });\n\n afterEach(async () => {\n await userRepository.query('DELETE FROM users');\n });\n\n it('[POST] /user : Response is OK if conditions are right', async () => {\n const dto = new UserCreateDto();\n dto.name = NAME;\n dto.email = EMAIL;\n dto.password = PASSWORD;\n\n const result = await request(app.getHttpServer())\n .post('/user')\n .send(JSON.stringify(dto))\n .expect({ status: HttpStatus.CREATED });\n });\n});\n```\n\n```text\nTypeError: metatype is not a constructor.\n\nTypeError: Cannot read property 'getHttpServer' of undefined.\n```\n\n```text\ncreate-memory-db.ts\n```\n\n```text\nUserModule\n```\n\n```text\nConnection\n```\n\n```text\ndescribe('UserController (e2e)', () => {\n let userService: UserService;\n let userRepository: Repository<User>;\n let app: INestApplication;\n const NAME = 'NAME';\n const EMAIL = 'test@test.com';\n const PASSWORD = '12345asbcd';\n\n beforeAll(async () => {\n const moduleFixture: TestingModule = await Test.createTestingModule({\n imports: [\n UserModule,\n TypeOrmModule.forRoot({\n type: 'sqlite',\n database: ':memory:',\n entities: [User],\n logging: true,\n synchronize: true,\n }),\n ],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n userRepository = moduleFixture.get('UserRepository');\n userService = new UserService(userRepository);\n });\n\n afterAll(async () => {\n await app.close();\n });\n\n afterEach(async () => {\n await userRepository.query('DELETE FROM users');\n });\n});\n```\n\n```text\nTypeOrm.forRoot()\n```\n\n```text\nTest.createTestingModule\n```\n\n```text\n// app.module.ts\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n useFactory: async (configService: ConfigService) => {\n if (process.env.APPLICATION_ENV === 'test') {\n return {\n type: 'sqlite',\n database: ':memory:',\n entities: [Entity],\n synchronize: true,\n }\n }\n return {\n // your default options\n };\n },\n }),\n ]\n})\n```\n\n========================================\n\nComments:\n- This is really helpful to me! Thanks for your own answer.\n- @CasimirCrystal My pleasure :)","metadata":{"transformedAt":"2026-08-18T18:33:44.693Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":457,"estimatedTokens":2733}}118{"id":"stack-55598213","source":"stackoverflow","questionId":55598213,"title":"Enums not working with nestjs and graphql","tags":["typescript","enums","graphql","nestjs","typeorm"],"text":"Title: Enums not working with nestjs and graphql\nTags: typescript, enums, graphql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have recently moved from using typegraphql and typeorm directly to using them with nestjs. Mostly this has been a straightforward experience. I however have one issue with respect to enums.\n\nI have a set of custom decorators that I have combined together so that I can easily decorate up my models without having both typeorm, typegraphql and class validator decorators. This worked great before and works fine now in all cases other than enums.\n\nAs an example here is an @OptionalDecimal decorator:\n\n```\nimport { IsNumber } from 'class-validator'\nimport { Field, Float } from 'type-graphql'\nimport { Column } from 'typeorm'\n\nexport function OptionalDecimal() {\n const typeDecorator = IsNumber()\n const fieldDecorator = Field(type => Float, { nullable: true })\n const columnDecorator = Column('decimal', { nullable: true })\n\n return (target: any, key: string) => {\n typeDecorator(target, key)\n fieldDecorator(target, key)\n columnDecorator(target, key)\n }\n}\n```\n\nMy @Enum decorator is as so:\n\n```\nimport { IsEnum } from 'class-validator'\nimport { Field } from 'type-graphql'\nimport { Column } from 'typeorm'\nimport { IEnumOptions } from './IEnumOptions'\n\nexport function Enum(\n typeFunction: (type?: any) => object,\n options: IEnumOptions = {}\n) {\n const isEnumDecorator = IsEnum(typeFunction())\n const fieldDecorator = Field(typeFunction)\n const columnDecorator = Column({\n default: options.default,\n enum: typeFunction(),\n type: 'enum',\n })\n\n return (target: any, key: string) => {\n isEnumDecorator(target, key)\n fieldDecorator(target, key)\n columnDecorator(target, key)\n }\n}\n```\n\nI define my enums in separate files like so:\n\n```\nimport { registerEnumType } from 'type-graphql'\n\nexport enum AccountState {\n ACTIVE,\n SUSPENDED,\n CLOSED,\n}\n\nregisterEnumType(AccountState, { name: 'AccountState' })\n```\n\nAnd is used thusly:\n\n```\n@EntityType()\nexport class Member extends VersionedEntity {\n @IdentifierNewGuid()\n public readonly id: string\n\n @Enum(type => AccountState, { default: AccountState.ACTIVE })\n public accountState: AccountState\n...\n```\n\nMy database is returning numeric ids for the enumerations and the field type in the database (mysql) is `enum`. As an example where my database is returning 1 for accountState which should be SUSPENDED I receive a graphql error:\n\n```\n\"errors\": [\n {\n \"message\": \"Expected a value of type \\\"AccountState\\\" but received: 1\",\n \"locations\": [\n {\n \"line\": 3,\n \"column\": 5\n }\n ],\n \"path\": [\n \"searchMembers\",\n 0,\n \"accountState\"\n ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"stacktrace\": [\n \"Error: Expected a value of type \\\"AccountState\\\" but received: 1\",\n \" at completeLeafValue\n```\n\nSo to recap this approach worked fine with typeorm and typegraphql directly but sadly fails to work now. All the other decorators I have appear to work fine (50+) so it's just something that's up specifically with enums.\n\nThis is a major blocker for me and any help would be greatly appreciated as I am currently out of ideas.\n\nEdit - In response to Shusson, when I add the decorators manually it also does not work actually:\n\n```\n@Column({\n default: AccountState.ACTIVE,\n enum: AccountState,\n type: 'enum',\n })\n@Field(type => AccountState)\npublic accountState: AccountState\n```\n\nCheers,\nMark\n\n========================================\n\nTop Answer:\nSince this is still an issue in 2022, here is a solution I came up with that does not require you to change your integer enums to string ones with the keys exactly matching the values. You can use the `@Transform` decorator from the `class-transformer` package.\n\n```\n@ArgsType()\nexport class SomeArgs {\n @Field(() => SomeEnum, {\n nullable: true,\n defaultValue: SomeEnum.SOME_KEY,\n })\n @Transform(({ value }) => \n typeof value === 'string' ? SomeEnum[value] : value\n )\n someEnumProp?: SomeEnum = SomeEnum.SOME_KEY;\n}\n```\n\nWhere SomeEnum is like:\n\n```\nexport enum SomeEnum {\n SOME_KEY = 1, \n SOME_OTHER_KEY = 2, \n}\n\nregisterEnumType(SomeEnum, {name: 'SomeEnum'})\n```\n\n========================================\n\nCode:\n```text\nimport { IsNumber } from 'class-validator'\nimport { Field, Float } from 'type-graphql'\nimport { Column } from 'typeorm'\n\nexport function OptionalDecimal() {\n const typeDecorator = IsNumber()\n const fieldDecorator = Field(type => Float, { nullable: true })\n const columnDecorator = Column('decimal', { nullable: true })\n\n return (target: any, key: string) => {\n typeDecorator(target, key)\n fieldDecorator(target, key)\n columnDecorator(target, key)\n }\n}\n```\n\n```text\nimport { IsEnum } from 'class-validator'\nimport { Field } from 'type-graphql'\nimport { Column } from 'typeorm'\nimport { IEnumOptions } from './IEnumOptions'\n\nexport function Enum(\n typeFunction: (type?: any) => object,\n options: IEnumOptions = {}\n) {\n const isEnumDecorator = IsEnum(typeFunction())\n const fieldDecorator = Field(typeFunction)\n const columnDecorator = Column({\n default: options.default,\n enum: typeFunction(),\n type: 'enum',\n })\n\n return (target: any, key: string) => {\n isEnumDecorator(target, key)\n fieldDecorator(target, key)\n columnDecorator(target, key)\n }\n}\n```\n\n```text\nimport { registerEnumType } from 'type-graphql'\n\nexport enum AccountState {\n ACTIVE,\n SUSPENDED,\n CLOSED,\n}\n\nregisterEnumType(AccountState, { name: 'AccountState' })\n```\n\n```text\n@EntityType()\nexport class Member extends VersionedEntity {\n @IdentifierNewGuid()\n public readonly id: string\n\n @Enum(type => AccountState, { default: AccountState.ACTIVE })\n public accountState: AccountState\n...\n```\n\n```text\n\"errors\": [\n {\n \"message\": \"Expected a value of type \\\"AccountState\\\" but received: 1\",\n \"locations\": [\n {\n \"line\": 3,\n \"column\": 5\n }\n ],\n \"path\": [\n \"searchMembers\",\n 0,\n \"accountState\"\n ],\n \"extensions\": {\n \"code\": \"INTERNAL_SERVER_ERROR\",\n \"exception\": {\n \"stacktrace\": [\n \"Error: Expected a value of type \\\"AccountState\\\" but received: 1\",\n \" at completeLeafValue\n```\n\n```text\n@Column({\n default: AccountState.ACTIVE,\n enum: AccountState,\n type: 'enum',\n })\n@Field(type => AccountState)\npublic accountState: AccountState\n```\n\n```text\nenum\n```\n\n```text\nexport enum AccountState {\n ACTIVE='ACTIVE',\n SUSPENDED='SUSPENDED',\n CLOSED='CLOSED',\n}\n```\n\n```text\n@ArgsType()\nexport class SomeArgs {\n @Field(() => SomeEnum, {\n nullable: true,\n defaultValue: SomeEnum.SOME_KEY,\n })\n @Transform(({ value }) => \n typeof value === 'string' ? SomeEnum[value] : value\n )\n someEnumProp?: SomeEnum = SomeEnum.SOME_KEY;\n}\n```\n\n```text\nexport enum SomeEnum {\n SOME_KEY = 1, \n SOME_OTHER_KEY = 2, \n}\n\nregisterEnumType(SomeEnum, {name: 'SomeEnum'})\n```\n\n```text\n@Transform\n```\n\n```text\nclass-transformer\n```\n\n```text\nexport enum AccountState {\n ACTIVE,\n SUSPENDED,\n CLOSED,\n}\n\n// Make to register before creating resolver\nregisterEnumType(AccountState, { name: 'AccountState' })\n\nexport const accountStateResolver: Record<keyof typeof AccountState, any> = {\n ACTIVE: 0,\n SUSPENDED: 1,\n CLOSED: 2\n};\n```\n\n```text\n@Module({\n ...\n imports:[\n ...\n GraphQLModule.forRoot({\n ...\n resolvers: {\n AccountState: accountStateResolver,\n }\n }),\n ...\n ]\n ...\n})\n```\n\n```text\nexport function createGQLEnumType<T>(enumType: T): { [key: string]: string } {\n const result = {} as { [key: string]: string }\n for (const key in enumType) {\n if (Object.prototype.hasOwnProperty.call(enumType, key)) {\n const value = enumType[key as keyof T] as string\n result[value] = value\n }\n }\n return result\n}\n```\n\n```text\nconst AccountStateGQLEnum = createGQLEnumType(AccountState)\nregisterEnumType(AccountStateGQLEnum, { name: 'AccountState' })\n\n@InputType({ description: 'Sample input type' })\nexport class SampleInput {\n\n @Field(() => AccountStateGQLEnum!)\n accountState: AccountState\n}\n```\n\n========================================\n\nComments:\n- Have you tried replacing the custom enum decorator with the standard typeorm declaration?\n- I have updated my question, thanks for your response @shusson\n- You're awesome man.. I just missed the registerEnumType(), I was using the string Enums, however it was not working, I saw your code and BAM.... I got the hint... In my case enum with Numeric value also working.. Just declare mongoose document using interface with int enum.\n- Thanks, glad I could be of help :)\n- i'm using the @Field decorator in nestjs/graphql pkg. Tried setting the defaultValue as an array containing an enum member...graphql playground threw an error stating `\"each value in ... must be a valid enum value\"`. It was only after setting the enum member to equal its string equivalent was there no longer an error... Your solution helped solve my problem. Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:44.693Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":371,"estimatedTokens":2250}}119{"id":"stack-51054702","source":"stackoverflow","questionId":51054702,"title":"Using different ormconfig.json files depending on env","tags":["node.js","typescript","typeorm"],"text":"Title: Using different ormconfig.json files depending on env\nTags: node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nMy ormconfig.json is static of course, it looks like:\n\n```\n{\n \"type\": \"mariadb\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"root\",\n \"password\": \"moove\",\n \"database\": \"moove_db\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"dist/entity/**/*.js\"\n ],\n \"migrations\": [\n \"dist/migration/**/*.js\"\n ],\n \"subscribers\": [\n \"dist/subscriber/**/*.js\"\n ],\n \"cli\": {\n \"entitiesDir\": \"dist/entity\",\n \"migrationsDir\": \"dist/migration\",\n \"subscribersDir\": \"dist/subscriber\"\n }\n}\n```\n\nbut what if I want to create another config for our production server?\nDo I create another config file? How do I point typeorm to the other config file?\n\n========================================\n\nTop Answer:\nDon't use the ormconfig.json. You can pass a config object directly to createConnection() like\n\n```\nimport { createConnection } from \"typeorm\";\n\nconst config:any = {\n \"port\": process.env.port || \"28017\",\n \"entities\": [\n // ...\n ],\n \"migrations\": [\n // ...\n ],\n \"subscribers\": [\n // ...\n ],\n \"cli\": {\n // ...\n }\n }\n createConnection(config).then(async connection => {\n await loadPosts(connection);\n }).catch(error => console.log(error));\n```\n\n========================================\n\nCode:\n```text\n{\n \"type\": \"mariadb\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"root\",\n \"password\": \"moove\",\n \"database\": \"moove_db\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"dist/entity/**/*.js\"\n ],\n \"migrations\": [\n \"dist/migration/**/*.js\"\n ],\n \"subscribers\": [\n \"dist/subscriber/**/*.js\"\n ],\n \"cli\": {\n \"entitiesDir\": \"dist/entity\",\n \"migrationsDir\": \"dist/migration\",\n \"subscribersDir\": \"dist/subscriber\"\n }\n}\n```\n\n```text\nmodule.exports = {\n \"port\": process.env.port,\n \"entities\": [\n // ...\n ],\n \"migrations\": [\n // ...\n ],\n \"subscribers\": [\n // ...\n ],\n \"cli\": {\n // ...\n }\n}\n```\n\n```text\normconfig.json\n```\n\n```text\normconfig.js\n```\n\n```text\nimport { createConnection } from \"typeorm\";\n\nconst config:any = {\n \"port\": process.env.port || \"28017\",\n \"entities\": [\n // ...\n ],\n \"migrations\": [\n // ...\n ],\n \"subscribers\": [\n // ...\n ],\n \"cli\": {\n // ...\n }\n }\n createConnection(config).then(async connection => {\n await loadPosts(connection);\n }).catch(error => console.log(error));\n```\n\n========================================\n\nComments:\n- you can also type it as `const config: ConnectionOptions` (imported from `typeorm`)\n- TypeORM CLI cannot be used with this approach.","metadata":{"transformedAt":"2026-08-18T18:33:44.693Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":149,"estimatedTokens":680}}120{"id":"stack-60401666","source":"stackoverflow","questionId":60401666,"title":"How can I set AUTO_INCREMENT for @PrimaryColumn()?","tags":["node.js","orm","typeorm"],"text":"Title: How can I set AUTO_INCREMENT for @PrimaryColumn()?\nTags: node.js, orm, typeorm\nSource: Stack Overflow\n\nQuestion:\nHow can I set `AUTO_INCREMENT` for `@PrimaryColumn()`?\n\nI know that `@PrimaryGeneratedColumn()` does this but I want to have ID from the `double` type.\n\nIs it possible to have `@PrimaryGeneratedColumn()` with `double` type? if not have can I set `AUTO_INCREMENT` for `@PrimaryColumn()`?\n\n========================================\n\nCode:\n```text\nAUTO_INCREMENT\n```\n\n```text\n@PrimaryColumn()\n```\n\n```text\n@PrimaryGeneratedColumn()\n```\n\n```text\ndouble\n```\n\n```text\n@PrimaryGeneratedColumn()\n```\n\n```text\ndouble\n```\n\n```text\nAUTO_INCREMENT\n```\n\n```text\n@PrimaryColumn()\n```\n\n```text\nimport {Entity, PrimaryGeneratedColumn} from 'typeorm';\n\n@Entity()\nexport class SomeWhat{\n\n @PrimaryGeneratedColumn('increment')\n public id: number;\n....\n```\n\n```text\nexport declare function PrimaryGeneratedColumn(): Function;\nexport declare function PrimaryGeneratedColumn(options: PrimaryGeneratedColumnNumericOptions): Function;\nexport declare function PrimaryGeneratedColumn(strategy: \"increment\", options?: PrimaryGeneratedColumnNumericOptions): Function;\nexport declare function PrimaryGeneratedColumn(strategy: \"uuid\", options?: PrimaryGeneratedColumnUUIDOptions): Function;\n```\n\n```text\nexport declare function PrimaryColumn(options?: ColumnOptions): Function;\nexport declare function PrimaryColumn(type?: ColumnType, options?: ColumnOptions): Function;\n```\n\n```text\ndouble\n```\n\n```text\nAUTO_INCREMENT\n```\n\n```text\nAUTO_INCREMENT\n```\n\n```text\nint\n```\n\n```text\n@PrimaryGeneratedColumn\n```\n\n```text\nAUTO_INCREMENT\n```\n\n```text\n@PrimaryGeneratedColumn\n```\n\n```text\n@PrimaryGeneratedColumn\n```\n\n```text\n@PrimaryColumn\n```\n\n```text\n@PrimaryColumn\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.693Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":108,"estimatedTokens":440}}121{"id":"stack-60347894","source":"stackoverflow","questionId":60347894,"title":"How do you inject a service in NestJS into a typeorm repository?","tags":["typescript","nestjs","typeorm"],"text":"Title: How do you inject a service in NestJS into a typeorm repository?\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a `UserRepository` which handles creating/authenticating users infront of the database. I want to perform hashing & validation for the user's password, so I created a seperate service for that purpose, trying to single repsonsibility principle, which is declared like this:\n\n```\n@Injectable()\nexport default class HashService\n```\n\nAnd I import it in my module:\n\n```\n@Module({\n imports: [TypeOrmModule.forFeature([UserRepository])],\n controllers: [AuthController],\n providers: [AuthService, HashService],\n})\nexport class AuthModule {}\n```\n\nI wish to inject it into `UserRepository`, I tried passing in it as a constructor parameter but it didn't work because it's base class already accepts 2 parameters there, so I tried injecting my service after them like so:\n\n```\n@EntityRepository(User)\nexport default class UserRepository extends Repository {\n constructor(\n entityManager: EntityManager,\n entityMetadata: EntityMetadata,\n @Inject() private readonly hashService: HashService,\n ) {\n super();\n }\n\n // Logic...\n}\n```\n\nBut `hashService` was undefined, I also tried without the `@Inject()` decorator.\nWhat would be the best way to inject `HashService` into my repository? Do I have to create a new instance of it?\n\n========================================\n\nTop Answer:\nYou can add it manually from the module service like this:\n\naskers.service.ts:\n\n```\nconstructor(\n @InjectRepository(AskersRepository)\n private repository: AskersRepository,\n private logger: LoggingService,\n) {\n this.repository.logger = logger;\n}\n```\n\naskers.repository.ts:\n\n```\nlogger: LoggingService;\n```\n\nAnd then the logger service will be available in the repository like it has been injected.\n\nHere is an article I wrote about the hacking of injecting a service with request scope into TypeORM (© to me.. - 😉)\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport default class HashService\n```\n\n```text\n@Module({\n imports: [TypeOrmModule.forFeature([UserRepository])],\n controllers: [AuthController],\n providers: [AuthService, HashService],\n})\nexport class AuthModule {}\n```\n\n```text\n@EntityRepository(User)\nexport default class UserRepository extends Repository<User> {\n constructor(\n entityManager: EntityManager,\n entityMetadata: EntityMetadata,\n @Inject() private readonly hashService: HashService,\n ) {\n super();\n }\n\n // Logic...\n}\n```\n\n```text\nUserRepository\n```\n\n```text\nUserRepository\n```\n\n```text\nhashService\n```\n\n```text\n@Inject()\n```\n\n```text\nHashService\n```\n\n```text\nRepository\n```\n\n```text\nTypeOrmModule.forFeature\n```\n\n```text\nCustomRepository\n```\n\n```text\n@Injectable()\nexport class CatalogService {\n constructor (\n private readonly cacheService: CacheService,\n public readonly catalogRepository: CatalogRepository\n ) {\n this.catalogRepository.cacheService = this.cacheService;\n }\n}\n```\n\n```text\n@EntityRepository(CatalogEntity)\nexport class CatalogRepository extends Repository<CatalogEntity> {\n cacheService: CacheService;\n cacheExpirySeconds = 60*60;\n}\n```\n\n```text\nconstructor(\n @InjectRepository(AskersRepository)\n private repository: AskersRepository,\n private logger: LoggingService,\n) {\n this.repository.logger = logger;\n}\n```\n\n```text\nlogger: LoggingService;\n```\n\n========================================\n\nComments:\n- This implementation does the trick like DI would have thanks.\n- See the article here - medium.com/@israellev770/…","metadata":{"transformedAt":"2026-08-18T18:33:44.693Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":173,"estimatedTokens":901}}122{"id":"stack-54361685","source":"stackoverflow","questionId":54361685,"title":"NestJs TypeORM configuration using env files","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: NestJs TypeORM configuration using env files\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have two .env files like `dev.env` and `staging.env`. I am using typeorm as my database ORM. I would like to know how to let typeorm read either of the config file whenever I run the application. `Error: No connection options were found in any of configurations file` from typeormmodule.\n\n========================================\n\nTop Answer:\n**1) i'm using `typeorm` to to use migration, but in this case i want to use two different folders for migrations(table structure) and seeds(default data to table)**\n\n**2) so this is how i resolved this in `nestjs` with `typeorm`**\n\n```\n// config for typeorm and used for mysql driver also\nimport { DataSource, DataSourceOptions } from 'typeorm';\nimport { config } from 'dotenv';\nconfig();\nconst { MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE, PATH_TO_RUN \n} =\nprocess.env;\nexport const dbConfig: DataSourceOptions = {\n type: 'mysql',\n host: MYSQL_HOST,\n port: 3306,\n username: MYSQL_USER,\n password: MYSQL_PASSWORD,\n database: MYSQL_DATABASE,\n entities: ['dist/**/*.entity.js'],\n migrations: [`dist/db/${PATH_TO_RUN}/*.js`], // update this path with env\n};\nexport default new DataSource(dbConfig);\n```\n\n**3) package.json look like after using `cross-env` this for typeorm**\n\n```\n// DON'T PLACE `cross-env` in build script use it in `typeorm` execution script\nscript: {\n\"migration:run\": \"yarn build && cross-env PATH_TO_RUN=migrations yarn typeorm migration:run -d dist/db/mysql.config.js\",\n\"seed:run\": \"yarn build && cross-env PATH_TO_RUN=seeds yarn typeorm migration:run -d dist/db/mysql.config.js\"\n}\n```\n\n**4) to run this npm script use this below command**\n\nyarn migration:run // to use migrations folder in typeorm\n\nyarn seed:run // to use seeds folder in typeorm\n\n**!! Before using Yarn and Cross-env please make sure it is installed !!**\n\n```\nnpm install --global yarn\nyarn add cross-env\n```\n\n========================================\n\nCode:\n```text\ndev.env\n```\n\n```text\nstaging.env\n```\n\n```text\nError: No connection options were found in any of configurations file\n```\n\n```text\n\"start:dev\": \"cross-env NODE_ENV=dev ts-node -r tsconfig-paths/register src/main.ts\",\n\"start:staging\": \"cross-env NODE_ENV=staging node dist/src/main.js\",\n```\n\n```text\n@Injectable()\nexport class ConfigService {\n private readonly envConfig: EnvConfig;\n\n constructor() {\n this.envConfig = dotenv.parse(fs.readFileSync(`${process.env.NODE_ENV}.env`));\n }\n\n get databaseHost(): string {\n return this.envConfig.DATABASE_HOST;\n }\n}\n```\n\n```text\nTypeOrmModule.forRootAsync({\n imports:[ConfigModule],\n useFactory: async (configService: ConfigService) => ({\n type: configService.getDatabase()\n // ...\n }),\n inject: [ConfigService]\n}),\n```\n\n```text\nNODE_ENV\n```\n\n```text\nNODE_ENV\n```\n\n```text\nConfigService\n```\n\n```text\n// config for typeorm and used for mysql driver also\nimport { DataSource, DataSourceOptions } from 'typeorm';\nimport { config } from 'dotenv';\nconfig();\nconst { MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE, PATH_TO_RUN \n} =\nprocess.env;\nexport const dbConfig: DataSourceOptions = {\n type: 'mysql',\n host: MYSQL_HOST,\n port: 3306,\n username: MYSQL_USER,\n password: MYSQL_PASSWORD,\n database: MYSQL_DATABASE,\n entities: ['dist/**/*.entity.js'],\n migrations: [`dist/db/${PATH_TO_RUN}/*.js`], // update this path with env\n};\nexport default new DataSource(dbConfig);\n```\n\n```text\n// DON'T PLACE `cross-env` in build script use it in `typeorm` execution script\nscript: {\n\"migration:run\": \"yarn build && cross-env PATH_TO_RUN=migrations yarn typeorm migration:run -d dist/db/mysql.config.js\",\n\"seed:run\": \"yarn build && cross-env PATH_TO_RUN=seeds yarn typeorm migration:run -d dist/db/mysql.config.js\"\n}\n```\n\n```text\nnpm install --global yarn\nyarn add cross-env\n```\n\n```text\ntypeorm\n```\n\n```text\nnestjs\n```\n\n```text\ntypeorm\n```\n\n```text\ncross-env\n```\n\n========================================\n\nComments:\n- in this approach you will need second configuration file in order to use typeorm CLI\n- Did you put this in the app.module.ts? I am getting errors saying `Error: No connection options were found in any of configurations file.`.\n- @rhlsthrm Yes, in `app.module.ts`. I haven't had an error like this, would need to look at this in more detail. If you can't solve it, maybe open a new question for it. :-)\n- @KimKern, thanks for the response. I opened a new question.\n- @grexlort is right, you will need a default export config file to use TypeORM CLI managing your migration for example. But this could be imported in your ConfigService as an exception or you can be generic and import them this way","metadata":{"transformedAt":"2026-08-18T18:33:44.693Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":174,"estimatedTokens":1182}}123{"id":"stack-52157791","source":"stackoverflow","questionId":52157791,"title":"How do you set a custom default unique id string for the @PrimaryGeneratedColumn in a TypeORM Entity?","tags":["javascript","entity","typeorm"],"text":"Title: How do you set a custom default unique id string for the @PrimaryGeneratedColumn in a TypeORM Entity?\nTags: javascript, entity, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a use case that calls for a custom string primary key in my tables. (I don't want to use the default 'uuid' provided by GraphQL, but instead want to use the shortid library to generate a custom unique id instead.)\n\nI'm a TypeORM beginner, and I'm not finding anything about setting a custom default primary key in the docs. Is it possible to achieve what I want in the TypeORM PrimaryGeneratedColumn, or do I have to accomplish what I want by other means?\n\nUPDATE: I learned I can use the @BeforeInsert listener to modify entities before saving them, but TypeORM still doesn't let me override the PrimaryGeneratedColumn('uuid') and use a shortId string because the shortId string is not a valid uuid.\n\n========================================\n\nTop Answer:\n@Timshel's answer does not work when using SQLite, because default values must be constant. It gives the following error:\n\n```\nUnhandledPromiseRejectionWarning: QueryFailedError: SQLITE_ERROR: default value of column [id] is not constant\n```\n\nInstead, you can use @BeforeInsert to achieve the desired result, like so:\n\n```\n@Field(() => ID)\n@PrimaryColumn(\"varchar\", {\n length: 20\n})\nid: string;\n\n@BeforeInsert()\nsetId() {\n this.id = shortid.generate();\n}\n```\n\n========================================\n\nCode:\n```text\n@PrimaryGeneratedColumn('uuid')\n```\n\n```text\nuuid\n```\n\n```text\ntypescript\n@PrimaryColumn('varchar', { length: <max shortId length>, default: () => `'${shortid.generate()}'` })\n```\n\n```text\nUnhandledPromiseRejectionWarning: QueryFailedError: SQLITE_ERROR: default value of column [id] is not constant\n```\n\n```text\n@Field(() => ID)\n@PrimaryColumn(\"varchar\", {\n length: 20\n})\nid: string;\n\n@BeforeInsert()\nsetId() {\n this.id = shortid.generate();\n}\n```\n\n```text\nshortid\n```\n\n```text\nnanoid\n```\n\n========================================\n\nComments:\n- Depending on which database you are using, specifing `@PrimaryGeneratedColumn('uuid')` means that the database field type will be `uuid`, which you can't insert a non-valid UUID in. I'd suggest decorating with @PrimaryColumn('char', { length: }) and using a `@BeforeInsert` listener as you describe. This will give you a fixed-length character primary key for the shortId.\n- Looking again at the shortId docs, I noticed that the generated ID may be variable length; if so you'll want to use `@PrimaryColumn('varchar', { length: })` instead of the above...\n- @PrimaryColumn is exactly what I needed. I'm such a noob I didn't even know PrimaryColumn was a decorator :# my code ended up looking like this `@PrimaryColumn('varchar', { default: shortid.generate(), length: 14 })` thanks for your help! I'd vote up your comments but it won't let me :/\n- Posted as answer so you can up-vote it! BTW with the column `default` option, are you passing the function itself (ie `default: shortid.generate`) or calling it and defaulting to its return value (`default: shortid.generate()`)? Unless I'm mistaken you'll need the former - otherwise TypeORM will have a single default value each time your app starts and will allow inserting one record but then error with a duplicate key violation for subsequent records.\n- @Timshel you are correct, I ran into duplicate key violation. However, when I tried the change you recommended, I kept running into a `column \"gz68lzqnmn\" does not exist` (the id changes each time) error. The only way around this I found was to keep `default: shortid.generate()` but then in the BeforeInsert hook I added `this.id = shortid.generate()`. Very hacky and sad :( but it works. If you want to look further into this you could pull this repo and `yarn start` to reproduce. No pressure though. Thanks again! github.com/podverse/podverse-api/tree/primaryDefaultBug\n- I'm pretty sure this is a quoting issue - the returned ID isn't quoted so is being interpreted as a column. Wrapping `shortid.generate()` and quoting the value should be all that is needed - e.g. `default: () => `'${shortid.generate()}'`` (note the single quotes around the ID).\n- @Timshel's answer also doesn't work for most other drivers. I tested it out using MySQL and when I created a migration from my entity the migration included: `ALTER TABLE user CHANGE id id char(36) NOT NULL DEFAULT 177f7044-0805-4891-870e-8352cffa77bf`. Looks like if you want TypeORM to do the value generation you have to use `@BeforeInsert`\n- other problem arises as it's either not possible to update entities OR its possible to expose a way to create entities with arbitrary IDs\n- Please note that you have to pass an instance of the entity (and not a plain object) to the `save()` method.\n- But what if nanoid will create id with the same value? You wil get an error, no?","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":89,"estimatedTokens":1211}}124{"id":"stack-64512831","source":"stackoverflow","questionId":64512831,"title":"Docker Compose getting error ECONNREFUSED 127.0.0.1:3306 with MySQL and NodeJS","tags":["mysql","node.js","docker","docker-compose","typeorm"],"text":"Title: Docker Compose getting error ECONNREFUSED 127.0.0.1:3306 with MySQL and NodeJS\nTags: mysql, node.js, docker, docker-compose, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to setup some containers for my NestJS + TypeORM + MySQL environment by using Docker Compose in a Windows 10 host, but I am getting an ECONNREFUSED error:\n\n```\nconnect ECONNREFUSED 127.0.0.1:3306 +2ms\nbackend_1 | Error: connect ECONNREFUSED 127.0.0.1:3306\nbackend_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1145:16)\nbackend_1 | --------------------\nbackend_1 | at Protocol._enqueue (/usr/src/app/node_modules/mysql/lib/protocol/Protocol.js:144:48)\nbackend_1 | at Protocol.handshake (/usr/src/app/node_modules/mysql/lib/protocol/Protocol.js:51:23) \nbackend_1 | at PoolConnection.connect (/usr/src/app/node_modules/mysql/lib/Connection.js:116:18)\nbackend_1 | at Pool.getConnection (/usr/src/app/node_modules/mysql/lib/Pool.js:48:16)\nbackend_1 | at /usr/src/app/node_modules/typeorm/driver/mysql/MysqlDriver.js:793:18\nbackend_1 | at new Promise ()\nbackend_1 | at MysqlDriver.createPool (/usr/src/app/node_modules/typeorm/driver/mysql/MysqlDriver.js:790:16)\nbackend_1 | at MysqlDriver. (/usr/src/app/node_modules/typeorm/driver/mysql/MysqlDriver.js:278:51)\nbackend_1 | at step (/usr/src/app/node_modules/typeorm/node_modules/tslib/tslib.js:141:27)\nbackend_1 | at Object.next (/usr/src/app/node_modules/typeorm/node_modules/tslib/tslib.js:122:57)\n```\n\nI have created the following `Dockerfile` to configure the NestJS API container:\n\n```\nFROM node:12-alpine\nWORKDIR /usr/src/app\n\nCOPY package.json .\nRUN npm install\n\nEXPOSE 3000\n\n#CMD [\"npm\", \"start\"]\n\nCMD /wait-for-it.sh db:3306 -- npm start\n\nCOPY . .\n```\n\nAnd then I reference this from Docker Compose with the following `docker-compose.yml`:\n\n```\nversion: \"3.8\"\n\nnetworks:\n app-tier:\n driver: bridge\n\nservices:\n db:\n image: mysql\n command: --default-authentication-plugin=mysql_native_password\n restart: always\n expose:\n - \"3306\"\n ports:\n - \"3306:3306\" \n networks:\n - app-tier \n environment:\n MYSQL_DATABASE: school\n MYSQL_ALLOW_EMPTY_PASSWORD: ok\n MYSQL_ROOT_PASSWORD: root\n MYSQL_USER: dbuser\n MYSQL_PASSWORD: dbuser\n MYSQL_ROOT_HOST: '%'\n backend:\n depends_on:\n - db\n build: .\n ports:\n - \"3000:3000\"\n networks:\n - app-tier\n```\n\nFinally, I set the TypeORM configuration to match with the Docker Compose file:\n\n```\nexport const DB_CONFIG: TypeOrmModuleOptions = {\n type: 'mysql',\n host: 'db',\n port: 3306,\n username: 'dbuser',\n password: 'dbuser',\n database: 'school',\n entities: [], // We specify the entities in the App Module.\n synchronize: true,\n};\n```\n\nI am kind of new to Docker Compose, but I have tried many things like changing the output port to 3307, setting an explicit network... and the port 3306 is free in my host OS when I run it. Any help?\n\n### Edit 1\n\nI have included `MYSQL_ROOT_HOST` and `wait-for-it.sh` as suggested, but still no results.\n\n========================================\n\nTop Answer:\nYou can utilize health checks to gracefully check if a service is in a healthy state and fail gracefully if it doesn't reach that state after a max number of tries.\n\nthe health check on db service might look something like\n\n```\nhealthcheck:\n test: mysqladmin ping -h mysql --user=$$MYSQL_USER --password=$$MYSQL_ROOT_PASSWORD\n interval: 30s\n timeout: 12s\n retries: 10\n```\n\nand then on backend add a depends\n\n```\ndepends_on:\n db:\n condition: service_healthy\n```\n\nThis will boot your backend after the db is healthy and fail after trying 10 times waiting 30 seconds between each try. This is advantageous to the previous answer because it won't hang forever if mysql never comes up\n\n========================================\n\nCode:\n```text\nconnect ECONNREFUSED 127.0.0.1:3306 +2ms\nbackend_1 | Error: connect ECONNREFUSED 127.0.0.1:3306\nbackend_1 | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1145:16)\nbackend_1 | --------------------\nbackend_1 | at Protocol._enqueue (/usr/src/app/node_modules/mysql/lib/protocol/Protocol.js:144:48)\nbackend_1 | at Protocol.handshake (/usr/src/app/node_modules/mysql/lib/protocol/Protocol.js:51:23) \nbackend_1 | at PoolConnection.connect (/usr/src/app/node_modules/mysql/lib/Connection.js:116:18)\nbackend_1 | at Pool.getConnection (/usr/src/app/node_modules/mysql/lib/Pool.js:48:16)\nbackend_1 | at /usr/src/app/node_modules/typeorm/driver/mysql/MysqlDriver.js:793:18\nbackend_1 | at new Promise (<anonymous>)\nbackend_1 | at MysqlDriver.createPool (/usr/src/app/node_modules/typeorm/driver/mysql/MysqlDriver.js:790:16)\nbackend_1 | at MysqlDriver.<anonymous> (/usr/src/app/node_modules/typeorm/driver/mysql/MysqlDriver.js:278:51)\nbackend_1 | at step (/usr/src/app/node_modules/typeorm/node_modules/tslib/tslib.js:141:27)\nbackend_1 | at Object.next (/usr/src/app/node_modules/typeorm/node_modules/tslib/tslib.js:122:57)\n```\n\n```text\nFROM node:12-alpine\nWORKDIR /usr/src/app\n\nCOPY package.json .\nRUN npm install\n\nEXPOSE 3000\n\n#CMD [\"npm\", \"start\"]\n\nCMD /wait-for-it.sh db:3306 -- npm start\n\nCOPY . .\n```\n\n```text\nversion: \"3.8\"\n\nnetworks:\n app-tier:\n driver: bridge\n\nservices:\n db:\n image: mysql\n command: --default-authentication-plugin=mysql_native_password\n restart: always\n expose:\n - \"3306\"\n ports:\n - \"3306:3306\" \n networks:\n - app-tier \n environment:\n MYSQL_DATABASE: school\n MYSQL_ALLOW_EMPTY_PASSWORD: ok\n MYSQL_ROOT_PASSWORD: root\n MYSQL_USER: dbuser\n MYSQL_PASSWORD: dbuser\n MYSQL_ROOT_HOST: '%'\n backend:\n depends_on:\n - db\n build: .\n ports:\n - \"3000:3000\"\n networks:\n - app-tier\n```\n\n```text\nexport const DB_CONFIG: TypeOrmModuleOptions = {\n type: 'mysql',\n host: 'db',\n port: 3306,\n username: 'dbuser',\n password: 'dbuser',\n database: 'school',\n entities: [], // We specify the entities in the App Module.\n synchronize: true,\n};\n```\n\n```text\nDockerfile\n```\n\n```text\ndocker-compose.yml\n```\n\n```text\nMYSQL_ROOT_HOST\n```\n\n```text\nwait-for-it.sh\n```\n\n```text\nversion: \"3.8\"\n\nnetworks:\n app-tier:\n driver: bridge\n\nservices:\n db:\n image: mysql\n command: --default-authentication-plugin=mysql_native_password\n restart: always\n expose:\n - \"3306\"\n ports:\n - \"3306:3306\" \n networks:\n - app-tier \n environment:\n MYSQL_DATABASE: school\n MYSQL_ALLOW_EMPTY_PASSWORD: ok\n MYSQL_ROOT_PASSWORD: root\n MYSQL_USER: dbuser\n MYSQL_PASSWORD: dbuser\n MYSQL_ROOT_HOST: '%'\n backend:\n depends_on:\n - db\n build: .\n command: bash -c 'while !</dev/tcp/db/3306; do sleep 1; done; npm start'\n ports:\n - \"3000:3000\"\n networks:\n - app-tier\n```\n\n```text\nhealthcheck:\n test: mysqladmin ping -h mysql --user=$$MYSQL_USER --password=$$MYSQL_ROOT_PASSWORD\n interval: 30s\n timeout: 12s\n retries: 10\n```\n\n```text\ndepends_on:\n db:\n condition: service_healthy\n```\n\n========================================\n\nComments:\n- Is docker starting the mysql container, and is the database starting correctly within the container? Can you check the container logs?\n- Try these steps, error seems similar stackoverflow.com/a/64487298/13961165\n- Hello. Yes, the \"db\" container is running on port 3306, and I am able to log in to check the default tables. But the \"backend\" fails. As for the logs, I am unsure if there is more than this.\n- You need to use `db:3306` (container name and port) in your application rather than `127.0.0.1:3306`.\n- @LeelaPrasad Thanks, I have updated the question but still no results.\n- @hisener Yes, but in my TypeORM I have already specified the host to be \"db\" instead of \"localhost\", if that is what you mean.\n- Hmm, interesting. The application logs still say `Error: connect ECONNREFUSED 127.0.0.1:3306` though.\n- Thank you, it worked. I just had to add `RUN apk update && apk add bash` in my Dockerfile so it can execute bash.\n- where did you added the this command in Dockerfile ?\n- what does the `command: bash -c 'while !</dev/tcp/db/5432; do sleep 1; done; npm start'` do? I presume \"while there is nothing in 5432, sleep 1; afterwards, npm start\"\n- My guy Corey, this worked and saved me after spending hours on docker compose debugging. Appreciate it!","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":289,"estimatedTokens":2073}}125{"id":"stack-64260584","source":"stackoverflow","questionId":64260584,"title":"How to select only single/multiple fields from joined entity in Typeorm","tags":["database","typescript","orm","typeorm"],"text":"Title: How to select only single/multiple fields from joined entity in Typeorm\nTags: database, typescript, orm, typeorm\nSource: Stack Overflow\n\nQuestion:\naccord to TypeOrm doc: https://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#joining-relations\n\nWe can query the joined entity's field that will populate all its field into the response. I am not sure how to restrict only to few selected fields(single/multiple), I tried adding 'select([])' but it is not working in the generated SQL query I can see it is querying all the fields.\n\ncode:\n\n```\nimport {Entity, PrimaryGeneratedColumn, Column, OneToMany} from \"typeorm\";\nimport {Photo} from \"./Photo\";\n\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToMany(type => Photo, photo => photo.user)\n photos: Photo[];\n}\nimport {Entity, PrimaryGeneratedColumn, Column, ManyToOne} from \"typeorm\";\nimport {User} from \"./User\";\n\n@Entity()\nexport class Photo {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n url: string;\n\n @Column()\n alt: string;\n\n @ManyToOne(type => User, user => user.photos)\n user: User;\n}\n```\n\nand on the code:\n\n```\nconst user = await createQueryBuilder(\"user\")\n .leftJoinAndSelect(\"user.photos\", \"photo\")\n .where(\"user.name = :name\", { name: \"Timber\" })\n .getOne();\n```\n\nThe above code gives the output as -\n\n```\n{\n id: 1,\n name: \"Timber\",\n photos: [{\n id: 1,\n url: \"me-with-chakram.jpg\",\n alt: \"Me With Chakram\"\n }, {\n id: 2,\n url: \"me-with-trees.jpg\",\n alt: \"Me With Trees\"\n }]\n}\n```\n\nIs there a way I can query only 'url' and 'alt' so the output will look something like this -\n\n```\n{\n id: 1,\n name: \"Timber\",\n photos: [{\n url: \"me-with-chakram.jpg\",\n alt: \"Me With Chakram\"\n }, {\n url: \"me-with-trees.jpg\",\n alt: \"Me With Trees\"\n }]\n}\n```\n\n========================================\n\nTop Answer:\nThe first answer given by Art Olshansky is right (the second one doesn't), so, you must stand \"the base\" entity but, if you don't need all/any user fields you can just apply\n\n\r\n\r\n\n```\nconst user = await createQueryBuilder(\"user\")\n .leftJoinAndSelect(\"user.photos\", \"photo\")\n .select(['user.id', 'photo.url', 'photo.alt'])\n .where(\"user.name = :name\", { name: \"Timber\" })\n .getOne();\n```\n\n========================================\n\nCode:\n```text\nimport {Entity, PrimaryGeneratedColumn, Column, OneToMany} from \"typeorm\";\nimport {Photo} from \"./Photo\";\n\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToMany(type => Photo, photo => photo.user)\n photos: Photo[];\n}\nimport {Entity, PrimaryGeneratedColumn, Column, ManyToOne} from \"typeorm\";\nimport {User} from \"./User\";\n\n@Entity()\nexport class Photo {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n url: string;\n\n @Column()\n alt: string;\n\n @ManyToOne(type => User, user => user.photos)\n user: User;\n}\n```\n\n```text\nconst user = await createQueryBuilder(\"user\")\n .leftJoinAndSelect(\"user.photos\", \"photo\")\n .where(\"user.name = :name\", { name: \"Timber\" })\n .getOne();\n```\n\n```text\n{\n id: 1,\n name: \"Timber\",\n photos: [{\n id: 1,\n url: \"me-with-chakram.jpg\",\n alt: \"Me With Chakram\"\n }, {\n id: 2,\n url: \"me-with-trees.jpg\",\n alt: \"Me With Trees\"\n }]\n}\n```\n\n```text\n{\n id: 1,\n name: \"Timber\",\n photos: [{\n url: \"me-with-chakram.jpg\",\n alt: \"Me With Chakram\"\n }, {\n url: \"me-with-trees.jpg\",\n alt: \"Me With Trees\"\n }]\n}\n```\n\n```text\nconst user = await createQueryBuilder(\"user\")\n .leftJoinAndSelect(\"user.photos\", \"photo\")\n .select(['user', 'photo.url', 'photo.alt'])\n .where(\"user.name = :name\", { name: \"Timber\" })\n .getOne();\n```\n\n```text\nconst user = await createQueryBuilder(\"user\")\n .leftJoinAndSelect(\"user.photos\", \"photo\")\n .addSelect(['photo.url', 'photo.alt'])\n .where(\"user.name = :name\", { name: \"Timber\" })\n .getOne();\n```\n\n```js\nconst user = await createQueryBuilder(\"user\")\n .leftJoinAndSelect(\"user.photos\", \"photo\")\n .select(['user.id', 'photo.url', 'photo.alt'])\n .where(\"user.name = :name\", { name: \"Timber\" })\n .getOne();\n```\n\n```text\nconst user = await createQueryBuilder(\"user\")\n .leftJoin(\"user.photos\", \"photos\")\n .addSelect(['photos.url','photos.alt'])\n .where(\"user.name = :name\", { name: \"Timber\" })\n .getOne();\n```\n\n========================================\n\nComments:\n- Thanks for your answer. I figured eventually but you were quick with your response :)\n- The first one is correct, the second is idle for function use (SUM, AVG, etc).\n- This returns ALL photo fields\n- Is the output of query same as requested question?\n- How your answer is different from the accepted one?\n- My answer is just a complement, and refers to the fact you can not remove at all the `user` entity (who owns relationship) from `select` statement regardless you don't need any field from `user` just `photo`, you must select at least one field from `user` entity","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":223,"estimatedTokens":1254}}126{"id":"stack-71879806","source":"stackoverflow","questionId":71879806,"title":"How can I specify the migrations directory for typeorm CLI?","tags":["node.js","postgresql","typeorm"],"text":"Title: How can I specify the migrations directory for typeorm CLI?\nTags: node.js, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nAfter the new typeorm release I am having some troubles to work with migrations.\n\nSome time ago I was using this code and it worked -\n\n```\nentities: ['./src/modules/**/infra/typeorm/entities/*.ts'],\nmigrations: ['./src/shared/infra/typeorm/migrations/*.ts'],\ncli: {\n migrationsDir: './src/shared/infra/typeorm/migrations'\n}\n```\n\nBut now I can't specify the CLI property. To create a new migration, I have to specify the entire migration path -\n\n```\nnpm run typeorm migration:create ./src/database/migrations -n SomeTest\n```\n\nIs there another way to do that without specifying the entire path?\n\n========================================\n\nTop Answer:\nCreate ormconfig.ts\n\n```\nimport { DataSource } from 'typeorm';\n\nexport const AppDataSource = new DataSource({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'password',\n database: 'postgres',\n entities: ['dist/**/*.entity.js'],\n logging: true,\n synchronize: false,\n migrationsRun: false,\n migrations: ['dist/**/migrations/*.js'],\n migrationsTableName: 'history',\n});\n```\n\nInstall \"cross-var\" package\nAdd commands in your package.json file\n\n```\n\"typeorm\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli -d ormconfig.ts\",\n\"migration:create\": \"cross-var ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli migration:create ./src/migrations/$npm_config_name\",\n\"migration:generate\": \"cross-var npm run typeorm -- migration:generate ./src/migrations/$npm_config_name\",\n\"migration:run\": \"npm run build && npm run typeorm -- migration:run\",\n\"migration:revert\": \"npm run typeorm -- migration:revert\"\n```\n\nExample command\n\n```\n\"npm run migration:create --name=Test1\"\n```\n\nLook this project\n\n========================================\n\nCode:\n```text\nentities: ['./src/modules/**/infra/typeorm/entities/*.ts'],\nmigrations: ['./src/shared/infra/typeorm/migrations/*.ts'],\ncli: {\n migrationsDir: './src/shared/infra/typeorm/migrations'\n}\n```\n\n```text\nnpm run typeorm migration:create ./src/database/migrations -n SomeTest\n```\n\n```text\n-n MigrationName\n```\n\n```text\nnpx typeorm-ts-node-esm migration:create src/database/migration/MigrationFileName\n```\n\n```text\nMigrationFileName\n```\n\n```text\nsrc/database/migration/\n```\n\n```text\nnpx typeorm-ts-node-commonjs migration:create\n```\n\n```text\nimport { DataSource } from 'typeorm';\n\nexport const AppDataSource = new DataSource({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'password',\n database: 'postgres',\n entities: ['dist/**/*.entity.js'],\n logging: true,\n synchronize: false,\n migrationsRun: false,\n migrations: ['dist/**/migrations/*.js'],\n migrationsTableName: 'history',\n});\n```\n\n```text\n\"typeorm\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli -d ormconfig.ts\",\n\"migration:create\": \"cross-var ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli migration:create ./src/migrations/$npm_config_name\",\n\"migration:generate\": \"cross-var npm run typeorm -- migration:generate ./src/migrations/$npm_config_name\",\n\"migration:run\": \"npm run build && npm run typeorm -- migration:run\",\n\"migration:revert\": \"npm run typeorm -- migration:revert\"\n```\n\n```text\n\"npm run migration:create --name=Test1\"\n```\n\n```text\n\"migration:create\":\"cd src/migrations && npx typeorm-ts-node-commonjs migration:create\",\n\"migration:generate\":\"cd src/migrations && npx typeorm-ts-node-commonjs migration:generate -d <YOUR_DATASOURCE_CONFIG_PATH>\",\n```\n\n```text\n$npm_config\n```\n\n```json\n\"migration:run\": \"typeorm -d src/datasource/datasource.ts migration:run\",\n\"migration:create\":\"cd ./src/db/migrations && typeorm-ts-node-commonjs migration:create\",\n```\n\n```text\nnpm run migration:create nameOfMigration\n```\n\n```text\n\"scripts\": {\n \"migrate:create\": \"typeorm migration:create ./src/schemas/typeorm/migration/%NAME%\"\n},\n```\n\n```text\nNAME=test2 typeorm migration:create\n```\n\n```text\n./src/schemas/typeorm/migration/%NAME%\n```\n\n```text\n{\"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"build\": \"npx tsc && tsc-alias -p tsconfig.json\",\n \"start\": \"node dist/index.js\",\n \"dev\": \"nodemon src/index.ts\",\n \"typeorm\": \"typeorm-ts-node-commonjs\",\n \"migrate\": \"typeorm migration:run -- -d ./src/database/connection.ts\",\n \"migrate:create\": \"ts-node ./src/scripts/createMigration.ts\",\n \"migrate:rollback\": \"typeorm migration:revert -- -d ./src/database/connection.ts\"\n }},\n```\n\n```text\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nconst defaultMigrationPath = './src/database/migrations';\nconst dataSourcePath = './src/database/connection.ts';\n\nasync function createMigration(migrationName: string): Promise<void> {\n const migrationFullPath = `${defaultMigrationPath}/${migrationName}`;\n \n try {\n const { stdout, stderr } = await execAsync(\n `npm run typeorm migration:create ${migrationFullPath} -- -d ${dataSourcePath}`\n );\n\n console.log(stdout);\n if (stderr) {\n console.error('Error:', stderr);\n }\n } catch (error) {\n console.error('Failed to create migration:', error);\n }\n}\n\nconst migrationName = process.argv[2];\nconsole.log('name', migrationName);\n\nif (!migrationName) {\n console.error('Please provide a name for the migration.');\n process.exit(1);\n}\n\ncreateMigration(migrationName);\n```\n\n========================================\n\nComments:\n- You're a legend, thanks @Bohdan","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":220,"estimatedTokens":1387}}127{"id":"stack-67595318","source":"stackoverflow","questionId":67595318,"title":"CloudRun Suddenly got `Improper path /cloudsql/{SQL_CONNECTION_NAME} to connect to Postgres Cloud SQL instance \"{SQL_CONNECTION_NAME}\"`","tags":["postgresql","google-cloud-platform","google-cloud-sql","typeorm","google-cloud-run"],"text":"Title: CloudRun Suddenly got `Improper path /cloudsql/{SQL_CONNECTION_NAME} to connect to Postgres Cloud SQL instance \"{SQL_CONNECTION_NAME}\"`\nTags: postgresql, google-cloud-platform, google-cloud-sql, typeorm, google-cloud-run\nSource: Stack Overflow\n\nQuestion:\nWe have been running a service using NestJS and TypeORM on fully managed CloudRun without issues for several months. Yesterday PM we started getting `Improper path /cloudsql/{SQL_CONNECTION_NAME} to connect to Postgres Cloud SQL instance \"{SQL_CONNECTION_NAME}\"` errors in our logs.\n\nWe didn't make any server/SQL changes around this timestamp. Currently there is no impact to the service so we are not sure if this is a serious issue.\n\nThis error is not from our code, and our third party modules shouldn't know if we use Cloud SQL, so I have no idea where this errors come from.\n\nMy assumption is Cloud SQL Proxy or any SQL client used in Cloud Run is making this error. We use --add-cloudsql-instances flag when deploying with \"gcloud run deploy\" CLI command.\n\nLink to the issue here\n\n========================================\n\nCode:\n```text\nImproper path /cloudsql/{SQL_CONNECTION_NAME} to connect to Postgres Cloud SQL instance \"{SQL_CONNECTION_NAME}\"\n```\n\n========================================\n\nComments:\n- I see this too in my logs, we were really scared\n- This error causes our monitoring system to get crazy. Now we can not distinguish between real errors and this one. Can we know when this fix will be rolled out?\n- Can confirm, BPM was sky high this morning.\n- Can confirm as well, seeing a ton of these messages but the connection is working just fine.\n- Same happening here @urosp can you confirm when the fix will be rolled out?\n- Apologies for the delay. This has rolled out around 5/29, please let me know if you still see any issues.","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":31,"estimatedTokens":454}}128{"id":"stack-56795035","source":"stackoverflow","questionId":56795035,"title":"Connecting to MongoDB Atlas with TypeOrm?","tags":["mongodb","typeorm","mongodb-atlas"],"text":"Title: Connecting to MongoDB Atlas with TypeOrm?\nTags: mongodb, typeorm, mongodb-atlas\nSource: Stack Overflow\n\nQuestion:\nI am trying to connect to Mongodb Atlas with TypeOrm.\n\nHere is my `ormconfig.json` :\n\n```\n{\n \"type\": \"mongodb\",\n \"host\": \"cluster0-****.mongodb.net\",\n \"port\": 27017,\n \"username\": \"testUser\",\n \"password\": \"******\",\n \"database\": \"test\",\n \"useNewUrlParser\": true,\n \"synchronize\": true,\n \"logging\": true,\n \"entities\": [\"src/entity/*.*\"]\n}\n```\n\nAnd then when I try to `createConnection()` is get this error :\n`(node:10392) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [cluster0-****.mongodb.net:27017] on first connect [MongoNetworkError: getaddrinfo ENOTFOUND cluster0-****.mongodb.net cluster0-****.mongodb.net:27017]`\n\nActually I can not find any information on how to do this.\n\nIs my port right ? And if it is not where can I found it ? Where can I find my database name on Atlas ?\n\n========================================\n\nTop Answer:\nThe TYPEORM documentation is not so clear on mongodb connection issues, and maybe not updated frequently with. So I'm dropping this here for future readers.\n\n- You need to make sure that your IP is whitelisted. (You can do so by going to `project => network access [tab] => IP whitelist [tab]` and add your ip address or use `0.0.0.0`.\n\n- Enable SSL for your connection by setting `ssl:true` in your orm config file.\n\n- Don't forget to add your authentication database using `authSource:admin`.\n\nBelow is an example of my `.env` file\n\n```\nTYPEORM_CONNECTION=mongodb\nTYPEORM_HOST=cluster0-shard-00-02-xxxxx.mongodb.net\nTYPEORM_PORT=27017\nTYPEORM_USERNAME=root\nTYPEORM_PASSWORD=password\nTYPEORM_DATABASE=mydatabase\nTYPEORM_SYNCHRONIZE=true\nTYPEORM_LOGGING=true\nTYPEORM_ENTITIES=./dist/**/*.entity.js\nTYPEORM_DRIVER_EXTRA={\"ssl\":true, \"authSource\": \"admin\"}\n```\n\n========================================\n\nCode:\n```text\n{\n \"type\": \"mongodb\",\n \"host\": \"cluster0-****.mongodb.net\",\n \"port\": 27017,\n \"username\": \"testUser\",\n \"password\": \"******\",\n \"database\": \"test\",\n \"useNewUrlParser\": true,\n \"synchronize\": true,\n \"logging\": true,\n \"entities\": [\"src/entity/*.*\"]\n}\n```\n\n```text\normconfig.json\n```\n\n```text\ncreateConnection()\n```\n\n```text\n(node:10392) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [cluster0-****.mongodb.net:27017] on first connect [MongoNetworkError: getaddrinfo ENOTFOUND cluster0-****.mongodb.net cluster0-****.mongodb.net:27017]\n```\n\n```text\n{\n \"type\": \"mongodb\",\n \"url\": \"mongodb+srv://testUser:<password>@cluster0-****.mongodb.net/test?retryWrites=true&w=majority\",\n \"useNewUrlParser\": true,\n \"synchronize\": true,\n \"logging\": true,\n \"entities\": [\"src/entity/*.*\"]\n}\n```\n\n```sh\nTYPEORM_CONNECTION=mongodb\nTYPEORM_HOST=cluster0-shard-00-02-xxxxx.mongodb.net\nTYPEORM_PORT=27017\nTYPEORM_USERNAME=root\nTYPEORM_PASSWORD=password\nTYPEORM_DATABASE=mydatabase\nTYPEORM_SYNCHRONIZE=true\nTYPEORM_LOGGING=true\nTYPEORM_ENTITIES=./dist/**/*.entity.js\nTYPEORM_DRIVER_EXTRA={\"ssl\":true, \"authSource\": \"admin\"}\n```\n\n```text\nproject => network access [tab] => IP whitelist [tab]\n```\n\n```text\n0.0.0.0\n```\n\n```text\nssl:true\n```\n\n```text\nauthSource:admin\n```\n\n```text\n.env\n```\n\n========================================\n\nComments:\n- thank you! I got stuck for 1 hour not being able to login, until I found out that `ssl` and authSource options were necessary.","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":135,"estimatedTokens":850}}129{"id":"stack-59831159","source":"stackoverflow","questionId":59831159,"title":"TypeORM relationship: Only IDs instead of whole instances","tags":["foreign-keys","relationship","typeorm"],"text":"Title: TypeORM relationship: Only IDs instead of whole instances\nTags: foreign-keys, relationship, typeorm\nSource: Stack Overflow\n\nQuestion:\nAccording to the documentation, in TypeORM a relationship is defined as follows: \nA user has exactly one profile. \n\n```\nimport {Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn} from \"typeorm\";\nimport {Profile} from \"./Profile\";\n\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToOne(type => Profile)\n @JoinColumn()\n profile: Profile;\n\n}\n```\n\n**Issue**\n\nWhen creating a new user, why do I have to pass a complete instance of the entity (**profile: Profile**) instead of - as usual - only one ID? Like this:\n\n```\n@OneToOne(type => Profile)\n @JoinColumn()\n profileId: number;\n```\n\nIsn't there another way?\n\nThis procedure causes a large, unnecessary overhead, if you have to make 4 queries for 4 foreign keys to get the corresponding instance instead of the ID.\n\nI would be very grateful for help to get around this!\n\n========================================\n\nTop Answer:\nTo complete iY1NQ's answer, if your column names are in snake_case, but you want to use another name in TypeORM, you can use the `name` attribute, from the `@JoinColumn()` and `@Column()` decorators.\n\n```\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToOne(type => Profile)\n @JoinColumn({name: \"profile_id\"}) // the associated column will be profile_id\n profile: Profile;\n\n @Column({name: \"profile_id\"}) // the associated column will be profile_id\n profileId: number; // profile_id is replaced by profileId in the code\n}\n```\n\nSo in your database the foreign key will be `profile_id`, but in the entity it will be `profileId`.\n\n========================================\n\nCode:\n```text\nimport {Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn} from \"typeorm\";\nimport {Profile} from \"./Profile\";\n\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToOne(type => Profile)\n @JoinColumn()\n profile: Profile;\n\n}\n```\n\n```text\n@OneToOne(type => Profile)\n @JoinColumn()\n profileId: number;\n```\n\n```ts\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToOne(type => Profile)\n @JoinColumn()\n profile: Profile;\n\n @Column()\n profileId: number;\n\n}\n```\n\n```text\nprofile\n```\n\n```text\nprofileId\n```\n\n```js\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToOne(type => Profile)\n @JoinColumn({name: \"profile_id\"}) // the associated column will be profile_id\n profile: Profile;\n\n @Column({name: \"profile_id\"}) // the associated column will be profile_id\n profileId: number; // profile_id is replaced by profileId in the code\n}\n```\n\n```text\nname\n```\n\n```text\n@JoinColumn()\n```\n\n```text\n@Column()\n```\n\n```text\nprofile_id\n```\n\n```text\nprofileId\n```\n\n========================================\n\nComments:\n- Amazingly simple, but it works - thank you very much, that helps me a lot! But that's not in the documentation, is it? At this point, I find that TypeORM takes away too much control and does some things in the background that are not quite obvious and expectable.\n- It is mentioned here in a slightly different context. You are right with your concerns that TypeORM is abstracting/hiding a lot of things and the result is sometimes not foreseeable, but mostly reading the source code clarifies things.\n- You guys know anything about if I can have relationships with an Entity that has ID type String (varchar)??\n- What happens when the Profile is deleted? profileId is not nulled.","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":171,"estimatedTokens":938}}130{"id":"stack-61253282","source":"stackoverflow","questionId":61253282,"title":"Typeorm decorator is not a function","tags":["typescript","jestjs","typeorm","ts-jest"],"text":"Title: Typeorm decorator is not a function\nTags: typescript, jestjs, typeorm, ts-jest\nSource: Stack Overflow\n\nQuestion:\nI have the following controller that I want to test :\n\n```\nclass Album {\n public static getAlbums(): Promise {\n return getRepository(AlbumModel).find({ relations: ['pictures'] });\n }\n}\n```\n\nWhich is linked to a model, i'm using typeorm with decoractors. This is where the problem come from when I use Jest\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column, JoinTable, ManyToMany } from 'typeorm';\nimport { PicturesModel } from '../pictures/pictures.model';\n\n@Entity({\n name: 'T_ALBUM_AL',\n synchronize: true,\n})\nexport class AlbumModel {\n @PrimaryGeneratedColumn({\n name: 'AL_id',\n })\n id: number;\n\n @Column({\n name: 'AL_name',\n })\n name: string;\n\n @ManyToMany(() => PicturesModel, (picture: PicturesModel) => picture.id)\n @JoinTable({\n name: 'TJ_PICTURE_ALBUM_PA',\n joinColumn: {\n name: 'AL_id',\n referencedColumnName: 'id',\n },\n inverseJoinColumn: {\n name: 'PI_id',\n referencedColumnName: 'id',\n },\n })\n pictures: PicturesModel[];\n}\n```\n\nTo test this controller, i'm using ts-jest. This is my unit test :\n\n```\nimport Album from './album.controller';\n\nconst getRepMock = jest.fn(() => ({\n find: jest.fn().mockImplementation(),\n}));\n\njest.mock('typeorm', () => ({\n getRepository: getRepMock,\n}));\n\ndescribe('Album', () => {\n it('Should work', () => {\n Album.getAlbums();\n expect(getRepMock).toBeCalled();\n });\n});\n```\n\nWhen I run my test, I'm getting the following error :\n\n```\nFAIL src/api/v1/album/album.test.ts\n ● Test suite failed to run\n\n TypeError: typeorm_1.PrimaryGeneratedColumn is not a function\n\n 6 | })\n 7 | export class PicturesModel {\n > 8 | @PrimaryGeneratedColumn({\n | ^\n 9 | name: 'PI_id',\n 10 | })\n 11 | id: number;\n```\n\nWhat is wrong with it ? \n\nThis is a part of my package.json\n\n```\n\"jest\": {\n \"preset\": \"ts-jest\",\n \"testEnvironment\": \"node\",\n \"coveragePathIgnorePatterns\": [\n \"/node_modules/\"\n ]\n },\n \"dependencies\": {\n \"@types/dotenv\": \"^8.2.0\",\n \"body-parser\": \"^1.19.0\",\n \"dotenv\": \"^8.2.0\",\n \"express\": \"^4.17.1\",\n \"express-boom\": \"^3.0.0\",\n \"glob\": \"^7.1.6\",\n \"morgan\": \"^1.10.0\",\n \"mysql\": \"^2.14.1\",\n \"pg\": \"^7.18.2\",\n \"reflect-metadata\": \"^0.1.10\",\n \"ts-jest\": \"^25.3.1\",\n \"typeorm\": \"0.2.24\"\n },\n \"devDependencies\": {\n \"@types/express\": \"^4.17.3\",\n \"@types/express-boom\": \"^3.0.0\",\n \"@types/glob\": \"^7.1.1\",\n \"@types/jest\": \"^25.2.1\",\n \"@types/morgan\": \"^1.9.0\",\n \"@types/node\": \"^8.0.29\",\n \"@types/supertest\": \"^2.0.8\",\n \"@typescript-eslint/eslint-plugin\": \"^2.24.0\",\n \"@typescript-eslint/parser\": \"^2.24.0\",\n \"eslint\": \"^6.8.0\",\n \"eslint-config-airbnb-base\": \"^14.1.0\",\n \"eslint-import-resolver-alias\": \"^1.1.2\",\n \"eslint-plugin-import\": \"^2.20.1\",\n \"eslint-plugin-module-resolver\": \"^0.16.0\",\n \"jest\": \"^25.3.0\",\n \"nodemon\": \"^2.0.2\",\n \"supertest\": \"^4.0.2\",\n \"ts-node\": \"3.3.0\",\n \"typescript\": \"3.3.3333\",\n \"typescript-eslint\": \"^0.0.1-alpha.0\"\n }\n```\n\n========================================\n\nTop Answer:\nI like to leave as much of `typeorm` automocked as possible so I opt for a different approach. I mock all of `typeorm` and then only override specific decorators that I am using:\n\n```\njest.mock('typeorm')\nmocked(EntityRepository).mockImplementation(() => jest.fn())\nmocked(Entity).mockImplementation(() => jest.fn())\nmocked(Column).mockImplementation(() => jest.fn())\nmocked(PrimaryGeneratedColumn).mockImplementation(() => jest.fn())\nmocked(CreateDateColumn).mockImplementation(() => jest.fn())\nmocked(UpdateDateColumn).mockImplementation(() => jest.fn())\nmocked(DeleteDateColumn).mockImplementation(() => jest.fn())\nmocked(OneToMany).mockImplementation(() => jest.fn())\nmocked(ManyToOne).mockImplementation(() => jest.fn())\nmocked(TableInheritance).mockImplementation(() => jest.fn())\nmocked(ChildEntity).mockImplementation(() => jest.fn())\n```\n\nThen when I want to mock certain methods like `.find()` I mock specific methods of the `EntityManager`:\n\n```\nmocked(EntityManager.prototype.getCustomRepository).mockReturnValue(repository);\nmocked(EntityManager.prototype.transaction as transactionOp).mockImplementation(async (runInTransaction) => runInTransaction(entityManager));\nmocked(EntityManager.prototype.findOne).mockResolvedValue({\n id: 1,\n name: 'Cool Album',\n});\n```\n\n========================================\n\nCode:\n```text\nclass Album {\n public static getAlbums(): Promise<AlbumModel[]> {\n return getRepository(AlbumModel).find({ relations: ['pictures'] });\n }\n}\n```\n\n```text\nimport { Entity, PrimaryGeneratedColumn, Column, JoinTable, ManyToMany } from 'typeorm';\nimport { PicturesModel } from '../pictures/pictures.model';\n\n@Entity({\n name: 'T_ALBUM_AL',\n synchronize: true,\n})\nexport class AlbumModel {\n @PrimaryGeneratedColumn({\n name: 'AL_id',\n })\n id: number;\n\n @Column({\n name: 'AL_name',\n })\n name: string;\n\n @ManyToMany(() => PicturesModel, (picture: PicturesModel) => picture.id)\n @JoinTable({\n name: 'TJ_PICTURE_ALBUM_PA',\n joinColumn: {\n name: 'AL_id',\n referencedColumnName: 'id',\n },\n inverseJoinColumn: {\n name: 'PI_id',\n referencedColumnName: 'id',\n },\n })\n pictures: PicturesModel[];\n}\n```\n\n```text\nimport Album from './album.controller';\n\nconst getRepMock = jest.fn(() => ({\n find: jest.fn().mockImplementation(),\n}));\n\njest.mock('typeorm', () => ({\n getRepository: getRepMock,\n}));\n\ndescribe('Album', () => {\n it('Should work', () => {\n Album.getAlbums();\n expect(getRepMock).toBeCalled();\n });\n});\n```\n\n```text\nFAIL src/api/v1/album/album.test.ts\n ● Test suite failed to run\n\n TypeError: typeorm_1.PrimaryGeneratedColumn is not a function\n\n 6 | })\n 7 | export class PicturesModel {\n > 8 | @PrimaryGeneratedColumn({\n | ^\n 9 | name: 'PI_id',\n 10 | })\n 11 | id: number;\n```\n\n```text\n\"jest\": {\n \"preset\": \"ts-jest\",\n \"testEnvironment\": \"node\",\n \"coveragePathIgnorePatterns\": [\n \"/node_modules/\"\n ]\n },\n \"dependencies\": {\n \"@types/dotenv\": \"^8.2.0\",\n \"body-parser\": \"^1.19.0\",\n \"dotenv\": \"^8.2.0\",\n \"express\": \"^4.17.1\",\n \"express-boom\": \"^3.0.0\",\n \"glob\": \"^7.1.6\",\n \"morgan\": \"^1.10.0\",\n \"mysql\": \"^2.14.1\",\n \"pg\": \"^7.18.2\",\n \"reflect-metadata\": \"^0.1.10\",\n \"ts-jest\": \"^25.3.1\",\n \"typeorm\": \"0.2.24\"\n },\n \"devDependencies\": {\n \"@types/express\": \"^4.17.3\",\n \"@types/express-boom\": \"^3.0.0\",\n \"@types/glob\": \"^7.1.1\",\n \"@types/jest\": \"^25.2.1\",\n \"@types/morgan\": \"^1.9.0\",\n \"@types/node\": \"^8.0.29\",\n \"@types/supertest\": \"^2.0.8\",\n \"@typescript-eslint/eslint-plugin\": \"^2.24.0\",\n \"@typescript-eslint/parser\": \"^2.24.0\",\n \"eslint\": \"^6.8.0\",\n \"eslint-config-airbnb-base\": \"^14.1.0\",\n \"eslint-import-resolver-alias\": \"^1.1.2\",\n \"eslint-plugin-import\": \"^2.20.1\",\n \"eslint-plugin-module-resolver\": \"^0.16.0\",\n \"jest\": \"^25.3.0\",\n \"nodemon\": \"^2.0.2\",\n \"supertest\": \"^4.0.2\",\n \"ts-node\": \"3.3.0\",\n \"typescript\": \"3.3.3333\",\n \"typescript-eslint\": \"^0.0.1-alpha.0\"\n }\n```\n\n```text\nimport { Repository, SelectQueryBuilder } from 'typeorm';\nimport { mock } from 'jest-mock-extended';\n\nconst repositoryMock = mock<Repository<any>>();\nconst qbuilderMock = mock<SelectQueryBuilder<any>>();\n\njest.mock('typeorm', () => {\n qbuilderMock.where.mockReturnThis();\n qbuilderMock.select.mockReturnThis();\n repositoryMock.createQueryBuilder.mockReturnValue(qbuilderMock);\n\n return {\n getRepository: () => repositoryMock,\n\n BaseEntity: class Mock {},\n ObjectType: () => {},\n Entity: () => {},\n InputType: () => {},\n Index: () => {},\n PrimaryGeneratedColumn: () => {},\n Column: () => {},\n CreateDateColumn: () => {},\n UpdateDateColumn: () => {},\n OneToMany: () => {},\n ManyToOne: () => {},\n }\n})\n```\n\n```text\ntypeorm\n```\n\n```text\njest.mock('typeorm')\nmocked(EntityRepository).mockImplementation(() => jest.fn())\nmocked(Entity).mockImplementation(() => jest.fn())\nmocked(Column).mockImplementation(() => jest.fn())\nmocked(PrimaryGeneratedColumn).mockImplementation(() => jest.fn())\nmocked(CreateDateColumn).mockImplementation(() => jest.fn())\nmocked(UpdateDateColumn).mockImplementation(() => jest.fn())\nmocked(DeleteDateColumn).mockImplementation(() => jest.fn())\nmocked(OneToMany).mockImplementation(() => jest.fn())\nmocked(ManyToOne).mockImplementation(() => jest.fn())\nmocked(TableInheritance).mockImplementation(() => jest.fn())\nmocked(ChildEntity).mockImplementation(() => jest.fn())\n```\n\n```text\nmocked(EntityManager.prototype.getCustomRepository).mockReturnValue(repository);\nmocked(EntityManager.prototype.transaction as transactionOp).mockImplementation(async (runInTransaction) => runInTransaction(entityManager));\nmocked(EntityManager.prototype.findOne).mockResolvedValue({\n id: 1,\n name: 'Cool Album',\n});\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeorm\n```\n\n```text\n.find()\n```\n\n```text\nEntityManager\n```\n\n========================================\n\nComments:\n- How would I add this to an existing project? Its own file and imported, the .spec.ts file, or something else entirely?\n- You just need to add it to the test file","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":376,"estimatedTokens":2286}}131{"id":"stack-59160515","source":"stackoverflow","questionId":59160515,"title":"NestJS nodejs load nested comments in one query with relations?","tags":["node.js","typeorm"],"text":"Title: NestJS nodejs load nested comments in one query with relations?\nTags: node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have the following models:\n\n`User`, `Customer`, `Comment`\n\nUser can comment on a `Customer`, user can reply to another user's comment, recursively unlimited.\n\nI have done this but it's limited to just one reply, and I want to get all replies NESTED:\n\n```\npublic async getCommentsForCustomerId(customerId: string): Promise {\n return this.find({where: {customer: {id: customerId}, parentComment: null}, relations: ['childComments']});\n}\n```\n\nHowever the response I get is only nested on one level:\n\n```\n[\n {\n \"id\": \"7b5b654a-efb0-4afa-82ee-c00c38725072\",\n \"content\": \"test\",\n \"created_at\": \"2019-12-03T15:14:48.000Z\",\n \"updated_at\": \"2019-12-03T15:14:49.000Z\",\n \"childComments\": [\n {\n \"id\": \"7b5b654a-efb0-4afa-82ee-c00c38725073\",\n \"content\": \"test reply\",\n \"created_at\": \"2019-12-03T15:14:48.000Z\",\n \"updated_at\": \"2019-12-03T15:14:49.000Z\",\n \"parentCommentId\": \"7b5b654a-efb0-4afa-82ee-c00c38725072\"\n }\n ]\n }\n]\n```\n\nHow can I make a query to nest them all in typeorm?\n\nEntity definition **(note customer renamed to Lead)**:\n\n```\n@Entity('leads_comments')\nexport class LeadComment {\n\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @ManyToOne(type => LeadComment, comment => comment.childComments, {nullable: true})\n parentComment: LeadComment;\n\n @OneToMany(type => LeadComment, comment => comment.parentComment)\n @JoinColumn({name: 'parentCommentId'})\n childComments: LeadComment[];\n\n @RelationId((comment: LeadComment) => comment.parentComment)\n parentCommentId: string;\n\n @ManyToOne(type => User, {cascade: true})\n user: User | string;\n\n @RelationId((comment: LeadComment) => comment.user, )\n userId: string;\n\n @ManyToOne(type => Lead, lead => lead.comments, {cascade: true})\n lead: Lead | string;\n\n @RelationId((comment: LeadComment) => comment.lead)\n leadId: string;\n\n @Column('varchar')\n content: string;\n\n @CreateDateColumn()\n created_at: Date;\n\n @UpdateDateColumn()\n updated_at: Date;\n}\n```\n\n========================================\n\nTop Answer:\nAs Gabriel said, other data models are better to do what you want performance wise. Still if you can't change the database design, you can use alternatives (which are less performant or pretty, but what works in production is all that matters in the end).\n\nAs you set the Lead value in your LeadComment, I can suggest that you set this value also on replies on the root comment on reply creation (should be easy in the code). This way you can fetch all comments on your customer in one query (including the replies). \n\n```\nconst lead = await leadRepository.findOne(id);\nconst comments = await commentRepository.find({lead});\n```\n\nOf course, you will have to run a SQL batch to populate the missing column values, but it is a one time thing, and once your codebase is patched as well you won't have to run anything afterwards. And it doesn't change the structure of your database (just the way data is populated).\n\nThen you can build in nodejs the whole stuff (lists of replies). To get the \"root\" comment, simply filter by comment that are not replies (that don't have parents). If you just want the root comments from the database you can even change the query to only these ones (with parentComment null in SQL column).\n\n```\nfunction sortComment(c1: LeadComment , c2: LeadComment ): number {\n if (c1.created_at.getTime() > c2.created_at.getTime()) {\n return 1;\n }\n if (c1.created_at.getTime() !c.parentComment)\n .sort(sortComment);\n```\n\nThen you can get replies on the rootComments and build the whole list recursively in node.\n\n```\nfunction buildCommentList(currentList: LeadComment[], allComments: LeadComment[]): LeadComment[] {\n const lastComment = currentList[currentList.length - 1];\n const childComments = allComments\n .filter(c => c.parentComment?.id === lastComment.id)\n .sort(sortComment);\n if (childComments.length === 0) {\n return currentList;\n }\n const childLists = childComments.flatMap(c => buildCommentList([c], allComments));\n return [...currentList, ...childLists];\n}\n\nconst listsOfComments = rootComments.map(r => buildCommentList([r], comments));\n```\n\nThere are probably more optimized ways to compute these lists, this is for me one of the simplest that can be made.\n\nDepending on the number of comments it can get slow (you can limit results by timestamp and number for instance so that it should be good enough?) so beware, don't fetch the universe of comments on a \"Justin Bieber\" Lead that get many comments...\n\n========================================\n\nCode:\n```text\npublic async getCommentsForCustomerId(customerId: string): Promise<CustomerComment[]> {\n return this.find({where: {customer: {id: customerId}, parentComment: null}, relations: ['childComments']});\n}\n```\n\n```text\n[\n {\n \"id\": \"7b5b654a-efb0-4afa-82ee-c00c38725072\",\n \"content\": \"test\",\n \"created_at\": \"2019-12-03T15:14:48.000Z\",\n \"updated_at\": \"2019-12-03T15:14:49.000Z\",\n \"childComments\": [\n {\n \"id\": \"7b5b654a-efb0-4afa-82ee-c00c38725073\",\n \"content\": \"test reply\",\n \"created_at\": \"2019-12-03T15:14:48.000Z\",\n \"updated_at\": \"2019-12-03T15:14:49.000Z\",\n \"parentCommentId\": \"7b5b654a-efb0-4afa-82ee-c00c38725072\"\n }\n ]\n }\n]\n```\n\n```text\n@Entity('leads_comments')\nexport class LeadComment {\n\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @ManyToOne(type => LeadComment, comment => comment.childComments, {nullable: true})\n parentComment: LeadComment;\n\n @OneToMany(type => LeadComment, comment => comment.parentComment)\n @JoinColumn({name: 'parentCommentId'})\n childComments: LeadComment[];\n\n @RelationId((comment: LeadComment) => comment.parentComment)\n parentCommentId: string;\n\n @ManyToOne(type => User, {cascade: true})\n user: User | string;\n\n @RelationId((comment: LeadComment) => comment.user, )\n userId: string;\n\n @ManyToOne(type => Lead, lead => lead.comments, {cascade: true})\n lead: Lead | string;\n\n @RelationId((comment: LeadComment) => comment.lead)\n leadId: string;\n\n @Column('varchar')\n content: string;\n\n @CreateDateColumn()\n created_at: Date;\n\n @UpdateDateColumn()\n updated_at: Date;\n}\n```\n\n```text\nUser\n```\n\n```text\nCustomer\n```\n\n```text\nComment\n```\n\n```text\nCustomer\n```\n\n```text\n@Entity()\n@Tree(\"nested-set\") // or @Tree(\"materialized-path\") or @Tree(\"closure-table\")\nexport class Category {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @TreeChildren()\n children: Category[];\n\n @TreeParent()\n parent: Category;\n}\n```\n\n```text\nconst manager = getManager();\nconst trees = await manager.getTreeRepository(Category).findTrees();\n```\n\n```text\nAdjacency list Tree\n```\n\n```text\nfindTrees(), findRoots(), findDescendants(), findDescendantsTree()\n```\n\n```text\nconst lead = await leadRepository.findOne(id);\nconst comments = await commentRepository.find({lead});\n```\n\n```text\nfunction sortComment(c1: LeadComment , c2: LeadComment ): number {\n if (c1.created_at.getTime() > c2.created_at.getTime()) {\n return 1;\n }\n if (c1.created_at.getTime() < c2.created_at.getTime()) {\n return -1;\n }\n return 0;\n}\nconst rootComments = comments\n .filter(c => !c.parentComment)\n .sort(sortComment);\n```\n\n```text\nfunction buildCommentList(currentList: LeadComment[], allComments: LeadComment[]): LeadComment[] {\n const lastComment = currentList[currentList.length - 1];\n const childComments = allComments\n .filter(c => c.parentComment?.id === lastComment.id)\n .sort(sortComment);\n if (childComments.length === 0) {\n return currentList;\n }\n const childLists = childComments.flatMap(c => buildCommentList([c], allComments));\n return [...currentList, ...childLists];\n}\n\nconst listsOfComments = rootComments.map(r => buildCommentList([r], comments));\n```\n\n========================================\n\nComments:\n- Can you add your entity definitions?\n- @zenbeni Added thanks\n- How can i fetch tree result from user? I mean, i wanna fetch user comments with tree relation!","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":288,"estimatedTokens":2023}}132{"id":"stack-50928311","source":"stackoverflow","questionId":50928311,"title":"How to use in-memory database with TypeORM in Nest","tags":["typescript","typeorm","nestjs"],"text":"Title: How to use in-memory database with TypeORM in Nest\nTags: typescript, typeorm, nestjs\nSource: Stack Overflow\n\nQuestion:\nI have a Nest server that other services depends on. In order to simplify testing of these other services, I would like to spin up a version of the Nest server that does not use a real database. Instead, it should use an in-memory db, like mongo-unit.\n\nMy idea would be to have a production main module, and a test main module, where the test module would keep everything the same, but use the in-memory db. However, I'm having trouble figuring out how to set this up.\n\nI know that I can use `async` providers, but I don't know how that works with imports, which is what `@nestjs/typeorm` exposes:\n\n```\n// app.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [\n ...\n TypeOrmModule.forRoot({\n type: 'mongodb',\n host: 'localhost',\n port: 27017,\n database: 'production',\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n }),\n ...\n ],\n})\nexport class AppModule {}\n```\n\nIt needs to be async, because mongo-unit returns a promise with the URL that it listens to. So I need to spin up mongo-unit, before I can initialize TypeORM. I imagine something like this:\n\n```\n// app.test.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport * as mongoUnit from 'mongo-unit';\n\n@Module({})\nexport class AppModule {\n static async forRoot() {\n const dbUrl = new URL(await mongoUnit.start());\n return {\n imports: [\n TypeOrmModule.forRoot({\n type: 'mongodb',\n host: dbUrl.host,\n port: dbUrl.port,\n database: 'test',\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n }),\n ],\n };\n }\n}\n```\n\nHow can I swap out the database, if it is asynchronously started?\n\n(If there is another approach to this problem than two separate modules, then please tell me! :) )\n\n========================================\n\nCode:\n```text\n// app.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [\n ...\n TypeOrmModule.forRoot({\n type: 'mongodb',\n host: 'localhost',\n port: 27017,\n database: 'production',\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n }),\n ...\n ],\n})\nexport class AppModule {}\n```\n\n```text\n// app.test.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport * as mongoUnit from 'mongo-unit';\n\n@Module({})\nexport class AppModule {\n static async forRoot() {\n const dbUrl = new URL(await mongoUnit.start());\n return {\n imports: [\n TypeOrmModule.forRoot({\n type: 'mongodb',\n host: dbUrl.host,\n port: dbUrl.port,\n database: 'test',\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n }),\n ],\n };\n }\n}\n```\n\n```text\nasync\n```\n\n```text\n@nestjs/typeorm\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":127,"estimatedTokens":753}}133{"id":"stack-64285189","source":"stackoverflow","questionId":64285189,"title":"How to save array of json object in postgres using typeorm","tags":["postgresql","nestjs","typeorm"],"text":"Title: How to save array of json object in postgres using typeorm\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to save an array of object in jsonb type in postgres\n\n**Entity**\n\n```\n@Column({type: 'jsonb', array: true, nullable: true})\ntestJson: object[];\n```\n\nThe json I am sending in postman\n\n```\n{\n \n \"testJson\": [\n {\"skill\": \"docker\", \"experience\": true},\n {\"skill\": \"kubernetes\", \"experience\": false}\n ]\n}\n```\n\nI am getting error 'malformed array literal:'\n\nAlso kindly tell if I can query such data types?\n\n========================================\n\nTop Answer:\nAbove answer is helpful.\nBut it needs some update.\nFollowing code worked for me in nest.js.\n\n```\ninterface dataType {\n key: number;\n asset: string;\n owner: string;\n value: string;\n}\n\n@Entity()\nexport class Will {\n @Column({\n type: \"json\",\n nullable: true,\n transformer: {\n to(value: dataType[]): string {\n return JSON.stringify(value);\n },\n from(value: string): dataType[] {\n return JSON.parse(value);\n },\n },\n })\n dataOutSideWill?: dataType[];\n}\n```\n\n========================================\n\nCode:\n```text\n@Column({type: 'jsonb', array: true, nullable: true})\ntestJson: object[];\n```\n\n```text\n{\n \n \"testJson\": [\n {\"skill\": \"docker\", \"experience\": true},\n {\"skill\": \"kubernetes\", \"experience\": false}\n ]\n}\n```\n\n```text\n@Column('jsonb', {nullable: true})\ntestJson?: object[];\n```\n\n```text\ninterface dataType {\n key: number;\n asset: string;\n owner: string;\n value: string;\n}\n\n@Entity()\nexport class Will {\n @Column({\n type: \"json\",\n nullable: true,\n transformer: {\n to(value: dataType[]): string {\n return JSON.stringify(value);\n },\n from(value: string): dataType[] {\n return JSON.parse(value);\n },\n },\n })\n dataOutSideWill?: dataType[];\n}\n```\n\n========================================\n\nComments:\n- Quick question, why are you doing the transformation here, wouldn't that slow down the time it takes to fetch the data in terms of complex queries?","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":116,"estimatedTokens":506}}134{"id":"stack-55136111","source":"stackoverflow","questionId":55136111,"title":"Typeorm subquery add select","tags":["typeorm","typeorm-datamapper"],"text":"Title: Typeorm subquery add select\nTags: typeorm, typeorm-datamapper\nSource: Stack Overflow\n\nQuestion:\nI am new for using `typeorm` and this is the second time I am confused with `typeorm`, I have the following query :\n\n```\nSELECT t1.a,t1.b,t2.a\n (SELECT TOP 1 t1.a\n FROM table1 t1\n WHERE t1.b = t2.a\n ORDER BY t1.a DESC\n ) AS MaxT1\nFROM Table1 t1\nINNER JOIN Table2 t2 ON t1.a = t2.a\n```\n\nI tried this:\n\n```\nlet query = await getManager()\n .createQueryBuilder(Bid, 'bid')\n .select([\n 'l.ID_anv_Lot',\n 'l.LotNumber',\n 'w.WineryName',\n 'bid.BidAmount',\n 'bid.ProxyBidAmount',\n 'er.ID_Contact'\n ])\n .addSelect(Table1, t1)\n .innerJoin(Lot, 'l', 'l.lotNumber = bid.lotNum AND l.paddleNumber = bid.paddleNumber')\n```\n\nbut the result is all of the rows on table1\n\n========================================\n\nTop Answer:\nYou can use subselects in SELECT statements:\n\n```\nlet query = await this.createQueryBuilder('t1')\n .select()\n .innnerJoin('t1.t2', 't2', 't1.a = t2.a')\n .addSelect(subQuery => { \n return subQuery \n .select('_t1.a') \n .from(Table1, '_t1')\n .where('_t1.b = t2.a'); \n }, 'MaxT1')\n .getRawMany()\n```\n\nYou can find more here: https://orkhan.gitbook.io/typeorm/docs/select-query-builder\n\n========================================\n\nCode:\n```sql\nSELECT t1.a,t1.b,t2.a\n (SELECT TOP 1 t1.a\n FROM table1 t1\n WHERE t1.b = t2.a\n ORDER BY t1.a DESC\n ) AS MaxT1\nFROM Table1 t1\nINNER JOIN Table2 t2 ON t1.a = t2.a\n```\n\n```js\nlet query = await getManager()\n .createQueryBuilder(Bid, 'bid')\n .select([\n 'l.ID_anv_Lot',\n 'l.LotNumber',\n 'w.WineryName',\n 'bid.BidAmount',\n 'bid.ProxyBidAmount',\n 'er.ID_Contact'\n ])\n .addSelect(Table1, t1)\n .innerJoin(Lot, 'l', 'l.lotNumber = bid.lotNum AND l.paddleNumber = bid.paddleNumber')\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeorm\n```\n\n```js\nconst posts = await connection.getRepository(Post)\n .createQueryBuilder(\"post\")\n .where(qb => {\n const subQuery = qb.subQuery()\n .select(\"usr.name\")\n .from(User, \"usr\")\n .where(\"usr.registered = :registered\")\n .getQuery();\n return \"post.title IN \" + subQuery;\n })\n .setParameter(\"registered\", true)\n .orderBy(\"post.id\")\n .getMany();\n```\n\n```text\nlet query = await this.createQueryBuilder('t1')\n .select()\n .innnerJoin('t1.t2', 't2', 't1.a = t2.a')\n .addSelect(subQuery => { \n return subQuery \n .select('_t1.a') \n .from(Table1, '_t1')\n .where('_t1.b = t2.a'); \n }, 'MaxT1')\n .getRawMany()\n```\n\n========================================\n\nComments:\n- could you solve it? i have a similar problem stackoverflow.com/questions/58087849/…","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":127,"estimatedTokens":706}}135{"id":"stack-76465393","source":"stackoverflow","questionId":76465393,"title":"Passing undefined value in WHERE condition behaves as true/matching condition in typeorm","tags":["typescript","nestjs","typeorm"],"text":"Title: Passing undefined value in WHERE condition behaves as true/matching condition in typeorm\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI discovered this strange behaviour of typeorm, which is that if the property in the condition of WHERE clause of the FIND query (find, findOne, findBy etc) is undefined, then it behaves like a true condition and returns records (first record for findOne and all records for find).\n\nI know this can be prevented using validators or an IF statement to check against undefined property, but I want to know a direct way with typeorm itself to handle it, apart from this.\n\nHere is what I am doing:\n\n```\nconst client = await this.clientRepository.findOne({\n where: {\n id: payload.clientId //undefined\n }\n });\n```\n\nI got the first record of the client table, even though the clientId was undefined.\n\n========================================\n\nCode:\n```text\nconst client = await this.clientRepository.findOne({\n where: {\n id: payload.clientId //undefined\n }\n });\n```\n\n```text\nconst client = await this.clientRepository.findOne({\n where: {\n id: Equal(payload.clientId)\n }\n});\n```\n\n```text\nEqual()\n```\n\n========================================\n\nComments:\n- I think this is intended behaviour and you should not work with an id that's obligatory in first place when it's undefined or not an ID.\n- I know it can be prevented by pre-hand validation, but my question was if it can be done without any validations using Typeorm. @mechaadi answered my question.","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":49,"estimatedTokens":390}}136{"id":"stack-49618719","source":"stackoverflow","questionId":49618719,"title":"Why does TypeORM need reflect-metadata?","tags":["node.js","typescript","typeorm","reflect-metadata"],"text":"Title: Why does TypeORM need reflect-metadata?\nTags: node.js, typescript, typeorm, reflect-metadata\nSource: Stack Overflow\n\nQuestion:\nI'm currently learning TypeScript with Node. Reading about TypeORM, I saw that the `reflect-metadata` package is needed for TypeORM to work. What is the reason for this package being needed?\n\n========================================\n\nCode:\n```text\nreflect-metadata\n```\n\n========================================\n\nComments:\n- Why do you think it isn't? Please offer some reasoning as to why you think it wouldn't be so that we can help you understand the utility of the package.\n- Well, you say to the orm what are the entities he must map. So i don't understand why the orm needs additional data (i came from jpa because that i don't understant it)","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":19,"estimatedTokens":196}}137{"id":"stack-64297248","source":"stackoverflow","questionId":64297248,"title":"How can we configure a TypeORM ViewEntity's ViewColumn to be of JSON type?","tags":["typeorm"],"text":"Title: How can we configure a TypeORM ViewEntity's ViewColumn to be of JSON type?\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI am creating a `@ViewEntity()` with TypeORM on MySQL in which I directly select a JSON column. The view is correct and just a normal SQL view.\n\nThe column definition for the view class looks as such:\n\n`@ViewColumn() document: Estimate;`\n\nwhere `Estimate` is an interface specifying the data shape of the JSON, although I have tried `Estimate | Object` as well. The entities retrieved by the Repository are always having the document property as a `string`, evidently the ORM is not parsing the JSON. Therefore I am having to do some annoying `JSON.parse()` and mutating the retrieved record before responding to requests.\n\n`ViewColumnOptions` only takes a property of `name`, so I cannot specify `{ type: 'json' }` as I would on a conventional `@Entity()`'s `@Column()`. Are JSON columns in TypeORM views even implemented? I have been unable to find results in the docs nor on the github issues.\n\n========================================\n\nCode:\n```text\n@ViewEntity()\n```\n\n```text\n@ViewColumn() document: Estimate;\n```\n\n```text\nEstimate\n```\n\n```text\nEstimate | Object\n```\n\n```text\nstring\n```\n\n```text\nJSON.parse()\n```\n\n```text\nViewColumnOptions\n```\n\n```text\nname\n```\n\n```text\n{ type: 'json' }\n```\n\n```text\n@Entity()\n```\n\n```text\n@Column()\n```\n\n```text\n@ManyToOne(() => Customer)\n@JoinColumn({ name: 'customerId' })\ncustomer: Customer;\n@ViewColumn() customerId: string;\n```\n\n```text\n@Column()\n```\n\n```text\n@Column({ type: 'json' }) document: Estimate;\n```\n\n```text\n@ViewColumn() document: Estimate;\n```\n\n```text\n@PrimaryColumn()\n```\n\n```text\n@ViewColumn()\n```\n\n```text\n@ViewEntity()\n```\n\n```text\n@ViewEntity()\n```\n\n```text\nCustomer\n```\n\n```text\ncustomerId\n```\n\n```text\n@JoinColumn()\n```\n\n```text\n@ViewColumn()\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":112,"estimatedTokens":461}}138{"id":"stack-57565810","source":"stackoverflow","questionId":57565810,"title":"How to define varchar and enum in TypeORM?","tags":["postgresql","typescript","nestjs","typeorm"],"text":"Title: How to define varchar and enum in TypeORM?\nTags: postgresql, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have database structure need to declare the variable into `varchar`, `int`, and `enum` using TypeORM in TypeScript. But in TypeScript doesn't have data type varchar and int. How do I declare it?\n\nDatabase structure\n\n```\nimport {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\";\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n account_id: varchar;\n\n @Column()\n email: varchar;\n\n @Column()\n phone_number: varchar;\n\n @Column()\n address: varchar;\n\n @Column()\n status: enum;\n\n @Column()\n current_id: varchar;\n}\n```\n\n========================================\n\nCode:\n```text\nimport {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\";\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n account_id: varchar;\n\n @Column()\n email: varchar;\n\n @Column()\n phone_number: varchar;\n\n @Column()\n address: varchar;\n\n @Column()\n status: enum;\n\n @Column()\n current_id: varchar;\n}\n```\n\n```text\nvarchar\n```\n\n```text\nint\n```\n\n```text\nenum\n```\n\n```text\nimport {Entity, Column, PrimaryGeneratedColumn} from \"typeorm\";\n\n@Entity()\nexport class Photo {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({\n length: 100\n })\n name: string;\n\n @Column(\"text\")\n description: string;\n\n @Column()\n filename: string;\n\n @Column(\"double\")\n views: number;\n\n @Column()\n isPublished: boolean;\n}\n```\n\n========================================\n\nComments:\n- You can use `string` and `number` for varchar and int. Also check the official typescript docs for all available types.\n- Okay, thank you for your respond\n- I understand now. Thank you for your help\n- @firdaus Could you please approve the answer if it resolves your query.","metadata":{"transformedAt":"2026-08-18T18:33:44.694Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":115,"estimatedTokens":471}}139{"id":"stack-69850518","source":"stackoverflow","questionId":69850518,"title":"TypeORM index creation","tags":["typeorm","typeorm-activerecord"],"text":"Title: TypeORM index creation\nTags: typeorm, typeorm-activerecord\nSource: Stack Overflow\n\nQuestion:\nIs it possible to create an unique index with certain ascending/descending fields so that the outcome would be something like this?\n\n```\nCREATE UNIQUE INDEX \"IDX_article_version_latest\" ON \"public\".\"article\" (\"uuid\" ASC, \"version\" DESC, \"updatedAt\" DESC)\n```\n\n========================================\n\nCode:\n```sql\nCREATE UNIQUE INDEX \"IDX_article_version_latest\" ON \"public\".\"article\" (\"uuid\" ASC, \"version\" DESC, \"updatedAt\" DESC)\n```\n\n```js\n@Index(\"IDX_article_version_latest\", { synchronize: false })\n/* ...*/\nclass Article { /*...*/ }\n```\n\n```js\nexport class IndexArticleVersionLatest implements MigrationInterface {\n async up(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(`CREATE UNIQUE INDEX \"IDX_article_version_latest\" ON \"public\".\"article\" (\"uuid\" ASC, \"version\" DESC, \"updatedAt\" DESC)`);\n }\n\n async down(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(`DROP INDEX IF EXISTS \"IDX_article_version_latest\"`);\n }\n}\n```\n\n```text\nsynchronize: false\n```\n\n```text\n@Index\n```\n\n```text\n@Index\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":47,"estimatedTokens":292}}140{"id":"stack-72038893","source":"stackoverflow","questionId":72038893,"title":"NestJS, how and where to build response DTOs","tags":["javascript","node.js","spring","nestjs","typeorm"],"text":"Title: NestJS, how and where to build response DTOs\nTags: javascript, node.js, spring, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have been using the Java Spring framework for developing Microservices. Recently I started exploring NestJS and have a question regarding building response DTOs.\n\nIn Spring,\nThe controllers are lightweight, they hand over the call to Service Layer.\n\nThe service layer implements the business logic, and finally, they call the Mapper classes that are responsible for building the response DTOs. The mapper class might be as simple as cloning the entity to a DTO or might also build complex objects using multiple DB entity objects.\n\nIn NestJS, in most of the examples `class-transformer` is being used. But I am not sure the `class-transformer` is good enough for building complex objects. For me `class-transformer` is basically cloning the object. The equivalent for which in Spring is\n\n```\nBeanUtils.copyProperties(workingWellCompositeMemberContactTrace, workingWellDailyMemberAggEntity);\n```\n\nSo my question is in NestJS, what layer is responsible for building complex response objects? And Is sending Entity object to Controller a good practice?\n\n========================================\n\nTop Answer:\nNestjs provided helper methods like PartialType(), PickType(), OmitType() etc for DTO, you may want to read here: https://docs.nestjs.com/techniques/validation#stripping-properties\n\n========================================\n\nCode:\n```text\nBeanUtils.copyProperties(workingWellCompositeMemberContactTrace, workingWellDailyMemberAggEntity);\n```\n\n```text\nclass-transformer\n```\n\n```text\nclass-transformer\n```\n\n```text\nclass-transformer\n```\n\n```js\nexport class UserDTO {\n id: string;\n\n name: string;\n\n surname: string;\n\n toEntity(dto:UserDTO) {\n const model = new User(); \n model.id = id;\n model.fullname = `${dto.name}, ${dto.surname}`\n return model;\n }\n\n fromEntity(entity:User) {\n const dto = new UserDTO();\n dto.id = entity.id;\n\n const [ name, surname ] = entity.(fullname as string).split(', ').map((name) => {name.tirm()});\n dto.name = name,\n dto.surname = surname;\n }\n}\n```\n\n```text\nwhat layer is responsible for building complex response objects?\n```\n\n```text\nIs sending Entity object to Controller a good practice?\n```\n\n```text\nclass-transformer\n```\n\n```text\ninstanceToPlain\n```\n\n```text\nplainToClass\n```\n\n```text\nExpose\n```\n\n```text\nExclude\n```\n\n========================================\n\nComments:\n- problem with sending entities as response is : When docs like Swagger render documentation on browser, due to some cyclic deps or related entities, the response payload comes out to be be too large and swagger ui goes in non-responsive mode - maybe I am going off topic but I am in favor of sending ResponseDTOs","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":102,"estimatedTokens":712}}141{"id":"stack-64195602","source":"stackoverflow","questionId":64195602,"title":"Typeorm: Execute raw query with parameters","tags":["typeorm"],"text":"Title: Typeorm: Execute raw query with parameters\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to execute raw query in **typeorm** with parameters\nI tried following queries:\n\n```\ninsert into data(id, name, gender) values(?, ?,?)\ninsert into data(id, name, gender) values($1, $2, $3)\ninsert into data(id, name, gender) values(:id, :name, :gender)\n```\n\nThe typeorm code is:\n\n```\nimport { getManager } from 'typeorm';\nawait getManager().query(query, [1, 'test', 'male']);\n```\n\nWhat is wrong? Is there any other way?\n\n========================================\n\nTop Answer:\nas @ashutosh said, it depends on the driver of your database\n\nFor mysql/mysql2 you should use `?` as placehoder. For example\n\n```\nmanager.query('SELECT id FROM foos WHERE createdAt > ? AND id > ?', [new Date(), 3])\n```\n\n========================================\n\nCode:\n```text\ninsert into data(id, name, gender) values(?, ?,?)\ninsert into data(id, name, gender) values($1, $2, $3)\ninsert into data(id, name, gender) values(:id, :name, :gender)\n```\n\n```text\nimport { getManager } from 'typeorm';\nawait getManager().query(query, [1, 'test', 'male']);\n```\n\n```text\nSELECT * FROM TABLE1 WHERE name in (:param)\n```\n\n```text\nmanager.query('SELECT id FROM foos WHERE createdAt > ? AND id > ?', [new Date(), 3])\n```\n\n```text\n?\n```\n\n========================================\n\nComments:\n- for some reason $1 doesn't seem to work on postgres when called with something like: query(`SET search_path to $1`, ['tenant']), but works with something like: query(`call storedProc($1)`, ['param'])\n- Is there a way to name the parameters like in postgres ($1, $2, $3) if you want to reuse the same parameter several times?","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":65,"estimatedTokens":421}}142{"id":"stack-52904724","source":"stackoverflow","questionId":52904724,"title":"Nest can't resolve dependencies of the USERRepository","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: Nest can't resolve dependencies of the USERRepository\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThis is really an unexpected problem.\n\nWhen I type in the terminal \"npm run start\", there's an error.\n\n```\n[Nest] 40671 - 2018-10-20 17:46:37 [ExceptionHandler] Nest can't resolve dependencies of the USERRepository (?). Please make sure that the argument at index [0] is available in the current context. +22ms\nError: Nest can't resolve dependencies of the USERRepository (?). Please make sure that the argument at index [0] is available in the current context.\n at Injector.lookupComponentInExports (/Users/huxiao/OneDrive/Coding/wtapm/node_modules/@nestjs/core/injector/injector.js:139:19)\n at \n at process._tickCallback (internal/process/next_tick.js:160:7)\n at Function.Module.runMain (module.js:703:11)\n at Object. (/Users/huxiao/OneDrive/Coding/wtapm/node_modules/ts-node/src/_bin.ts:177:12)\n at Module._compile (module.js:660:30)\n at Object.Module._extensions..js (module.js:671:10)\n at Module.load (module.js:573:32)\n at tryModuleLoad (module.js:513:12)\n at Function.Module._load (module.js:505:3)\n 1: node::Abort() [/usr/local/bin/node]\n 2: node::Chdir(v8::FunctionCallbackInfo const&) [/usr/local/bin/node]\n 3: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo const&)) [/usr/local/bin/node]\n 4: v8::internal::MaybeHandle v8::internal::(anonymous namespace)::HandleApiCallHelper(v8::internal::Isolate*, v8::internal::Handle, v8::internal::Handle, v8::internal::Handle, v8::internal::Handle, v8::internal::BuiltinArguments) [/usr/local/bin/node]\n 5: v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) [/usr/local/bin/node]\n 6: 0x909046042fd\nAbort trap: 6\n```\n\nI tried everything I can do, but I couldn't solve it. My codes are as below:\n\n**below is [app.module.ts]**\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { UserModule } from './user/user.module';\nimport {TypeOrmModule} from '@nestjs/typeorm';\n\n@Module({\n imports: [TypeOrmModule.forRoot(\n{\n \"type\":\"postgres\",\n \"name\":\"pm_main\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"test\",\n \"database\": \"test\",\n \"synchronize\":true\n }\n ),UserModule],\n controllers: [AppController],\n providers: [AppService]\n})\nexport class AppModule {}\n```\n\n**Below is [user.service.ts]**\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { USER } from './models/user.model';\nimport { Repository } from 'typeorm';\n\n@Injectable()\nexport class UserService {\n\n constructor(\n @InjectRepository(USER)\n private readonly userRepository: Repository\n ){}\n\n async findAllUser(): Promise {\n return await this.userRepository.find();\n }\n}\n```\n\n**Below is [user.module.ts]**\n\n```\nimport { Module } from '@nestjs/common';\nimport { UserController } from './user.controller';\nimport { UserService } from './user.service';\nimport { PROJECT } from 'project/models/project.model';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { USER } from './models/user.model';\n\n@Module({\n imports: [TypeOrmModule.forFeature([USER])],\n providers: [UserService],\n controllers: [UserController],\n exports: [UserService]\n})\nexport class UserModule {}\n```\n\nI 100% followed the sample of the document, but it seems not right.\n\nFor more information, the dependencies in package.json are as below:\n\n```\n\"dependencies\": {\n \"@nestjs/common\": \"^5.3.9\" \n \"@nestjs/core\": \"^5.3.10\", \n \"@nestjs/typeorm\": \"^5.2.0\",\n \"ajv\": \"^6.5.4\",\n \"class-validator\": \"^0.9.1\",\n \"fastify-formbody\": \"^2.0.0\",\n \"jsonwebtoken\": \"^8.3.0\",\n \"passport\": \"^0.4.0\",\n \"passport-jwt\": \"^4.0.0\",\n \"pg\": \"^7.4.3\",\n \"reflect-metadata\": \"^0.1.12\",\n \"rxjs\": \"^6.0.0\",\n \"typeorm\": \"^0.2.7\",\n \"typescript\": \"^2.6.2\"\n```\n\n**Also [user.model.ts] as USER is shown below**\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, ManyToMany, JoinTable } from \"typeorm\";\nimport { IsNotEmpty, IsDate, IsEmail, IsArray, IsEnum, IsJSON } from 'class-validator'\nimport { user_Gender, user_Status } from \"./user.enum\";\nimport { PROJECT } from 'project/models/project.model';\n\n@Entity()\nexport class USER {\n @PrimaryGeneratedColumn('uuid')\n id:string;\n\n @Column({unique:true})\n @IsNotEmpty()\n username:string;\n\n @Column()\n password:string;\n\n @Column()\n @IsEnum({user_Gender})\n gender:string;\n\n @Column(\"jsonb\")\n @IsJSON()\n realname?:{\n firstName:string;\n lastName:string;\n middleName:string;\n };\n\n @Column()\n @IsDate()\n birthday?:Date;\n\n @CreateDateColumn()\n createAt:Date;\n\n @UpdateDateColumn()\n updateAt:Date;\n\n @Column()\n @IsArray()\n industry?:string[];\n\n @Column()\n @IsEmail()\n email?:string;\n\n @Column()\n @IsArray()\n org?:string[];\n\n @Column()\n current_org?:string;\n\n @Column(\"jsonb\")\n @IsJSON()\n user_location?:{\n country:string;\n province_or_state:string;\n city:string;\n district:string;\n address:string;\n };\n\n @Column(\"jsonb\")\n @IsJSON()\n mobilephone?:{code:string,number:string};\n\n @Column(\"text\")\n avater:string;\n\n @Column()\n @IsArray()\n receive_account?:[{\n name:string,\n number:string,\n bank:string,\n swiftCode?:string,\n address?:string}]\n\n @Column()\n @IsDate()\n last_loginAt?:Date;\n\n @Column()\n @IsEnum(user_Status)\n status:string;\n\n @Column()\n projectsId:[];\n\n @ManyToMany(type => PROJECT, project => project.members)\n @JoinTable()\n projects:PROJECT[];\n\n}\n```\n\n========================================\n\nTop Answer:\nKim's solution doesn't completely solve the problem when there are multiple databases in use.\n\nfinally solve it when check out this issue. https://github.com/nestjs/typeorm/issues/105\n\nThat is, also need to specify the connection name when @InjectRepositry(Model, connectionName)\n\n========================================\n\nCode:\n```text\n[Nest] 40671 - 2018-10-20 17:46:37 [ExceptionHandler] Nest can't resolve dependencies of the USERRepository (?). Please make sure that the argument at index [0] is available in the current context. +22ms\nError: Nest can't resolve dependencies of the USERRepository (?). Please make sure that the argument at index [0] is available in the current context.\n at Injector.lookupComponentInExports (/Users/huxiao/OneDrive/Coding/wtapm/node_modules/@nestjs/core/injector/injector.js:139:19)\n at <anonymous>\n at process._tickCallback (internal/process/next_tick.js:160:7)\n at Function.Module.runMain (module.js:703:11)\n at Object.<anonymous> (/Users/huxiao/OneDrive/Coding/wtapm/node_modules/ts-node/src/_bin.ts:177:12)\n at Module._compile (module.js:660:30)\n at Object.Module._extensions..js (module.js:671:10)\n at Module.load (module.js:573:32)\n at tryModuleLoad (module.js:513:12)\n at Function.Module._load (module.js:505:3)\n 1: node::Abort() [/usr/local/bin/node]\n 2: node::Chdir(v8::FunctionCallbackInfo<v8::Value> const&) [/usr/local/bin/node]\n 3: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&)) [/usr/local/bin/node]\n 4: v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) [/usr/local/bin/node]\n 5: v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) [/usr/local/bin/node]\n 6: 0x909046042fd\nAbort trap: 6\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { UserModule } from './user/user.module';\nimport {TypeOrmModule} from '@nestjs/typeorm';\n\n@Module({\n imports: [TypeOrmModule.forRoot(\n{\n \"type\":\"postgres\",\n \"name\":\"pm_main\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"test\",\n \"database\": \"test\",\n \"synchronize\":true\n }\n ),UserModule],\n controllers: [AppController],\n providers: [AppService]\n})\nexport class AppModule {}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { USER } from './models/user.model';\nimport { Repository } from 'typeorm';\n\n@Injectable()\nexport class UserService {\n\n constructor(\n @InjectRepository(USER)\n private readonly userRepository: Repository<USER>\n ){}\n\n async findAllUser(): Promise<USER[]> {\n return await this.userRepository.find();\n }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { UserController } from './user.controller';\nimport { UserService } from './user.service';\nimport { PROJECT } from 'project/models/project.model';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { USER } from './models/user.model';\n\n@Module({\n imports: [TypeOrmModule.forFeature([USER])],\n providers: [UserService],\n controllers: [UserController],\n exports: [UserService]\n})\nexport class UserModule {}\n```\n\n```text\n\"dependencies\": {\n \"@nestjs/common\": \"^5.3.9\" \n \"@nestjs/core\": \"^5.3.10\", \n \"@nestjs/typeorm\": \"^5.2.0\",\n \"ajv\": \"^6.5.4\",\n \"class-validator\": \"^0.9.1\",\n \"fastify-formbody\": \"^2.0.0\",\n \"jsonwebtoken\": \"^8.3.0\",\n \"passport\": \"^0.4.0\",\n \"passport-jwt\": \"^4.0.0\",\n \"pg\": \"^7.4.3\",\n \"reflect-metadata\": \"^0.1.12\",\n \"rxjs\": \"^6.0.0\",\n \"typeorm\": \"^0.2.7\",\n \"typescript\": \"^2.6.2\"\n```\n\n```text\nimport { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, ManyToMany, JoinTable } from \"typeorm\";\nimport { IsNotEmpty, IsDate, IsEmail, IsArray, IsEnum, IsJSON } from 'class-validator'\nimport { user_Gender, user_Status } from \"./user.enum\";\nimport { PROJECT } from 'project/models/project.model';\n\n@Entity()\nexport class USER {\n @PrimaryGeneratedColumn('uuid')\n id:string;\n\n @Column({unique:true})\n @IsNotEmpty()\n username:string;\n\n @Column()\n password:string;\n\n @Column()\n @IsEnum({user_Gender})\n gender:string;\n\n @Column(\"jsonb\")\n @IsJSON()\n realname?:{\n firstName:string;\n lastName:string;\n middleName:string;\n };\n\n @Column()\n @IsDate()\n birthday?:Date;\n\n @CreateDateColumn()\n createAt:Date;\n\n @UpdateDateColumn()\n updateAt:Date;\n\n @Column()\n @IsArray()\n industry?:string[];\n\n @Column()\n @IsEmail()\n email?:string;\n\n @Column()\n @IsArray()\n org?:string[];\n\n @Column()\n current_org?:string;\n\n @Column(\"jsonb\")\n @IsJSON()\n user_location?:{\n country:string;\n province_or_state:string;\n city:string;\n district:string;\n address:string;\n };\n\n @Column(\"jsonb\")\n @IsJSON()\n mobilephone?:{code:string,number:string};\n\n @Column(\"text\")\n avater:string;\n\n @Column()\n @IsArray()\n receive_account?:[{\n name:string,\n number:string,\n bank:string,\n swiftCode?:string,\n address?:string}]\n\n @Column()\n @IsDate()\n last_loginAt?:Date;\n\n @Column()\n @IsEnum(user_Status)\n status:string;\n\n @Column()\n projectsId:[];\n\n @ManyToMany(type => PROJECT, project => project.members)\n @JoinTable()\n projects:PROJECT[];\n\n}\n```\n\n```text\nimports: [TypeOrmModule.forRoot({\n \"type\":\"postgres\",\n \"name\":\"pm_main\",\n ^^^^^^^^^^^^^^^^^\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"test\",\n \"database\": \"test\",\n \"synchronize\":true\n }\n```\n\n```text\nimports: [TypeOrmModule.forFeature([USER])],\n```\n\n```text\nTypeOrmModule.forFeature([USER], 'pm_main')\n```\n\n```text\nforFeature\n```\n\n```text\nforFeature\n```\n\n```text\n\"name\":\"pm_main\",\n```\n\n```text\nforRoot\n```\n\n```text\nimport { UserEntity } from './user.entity';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nconst module = await Test.createTestingModule({\n controllers: [UsersController],\n providers: [UsersService],\n imports: [TypeOrmModule.forRoot(), TypeOrmModule.forFeature([UserEntity])], // <== This line\n}).compile();\n```\n\n========================================\n\nComments:\n- I couldn't spot an error on first glance. Can you include your `USER` model from /models/user.model?\n- @KimKern Thanks for your reply. I have included the USER model.\n- Thanks ! Was stuck for hours because I had the same issue.\n- I am facing this issue.I have two databases, already adding the name in forFeature but still the same.\n- Solved my issue with Sequelize.\n- It would be helpful if you could explain what the code in your answer changes to solve the OP's problem.Code without comments has very little value t oothers\n- Thanks, even though this doesn't answer the original question, but it gave me the clue to my problem, where i'm getting this error in my test script","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":497,"estimatedTokens":3234}}143{"id":"stack-63007454","source":"stackoverflow","questionId":63007454,"title":"TypeORM When updating a specific column, save without affecting UpdateDateColumn","tags":["typeorm"],"text":"Title: TypeORM When updating a specific column, save without affecting UpdateDateColumn\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to save without affecting UpdateDateColumn when updating view column.\n\nThis table is a post table and the view is a hit.\n\nUpdateDateColumn is updated when adding the number of view Column.\n\nI don't want the view column to affect UpdateDateColumn.\n\n```\n@Entity(\"post\")\nexport default class Post extends BaseEntity {\n @PrimaryGeneratedColumn()\n idx: number;\n\n // Skip\n \n @Column({\n nullable: false,\n default: 0\n })\n view: number;\n\n @Column(\"timestampz\")\n @CreateDateColumn()\n created_at: Date;\n\n @Column(\"timestampz\")\n @UpdateDateColumn()\n updated_at: Date;\n}\n```\n\nGive me a solution please.\n\n========================================\n\nTop Answer:\nuse this code:\n\n```\ngetRepository(Post).update(postId, {\n view: newViewValue,\n updated_at: () => 'now()'\n})\n```\n\n========================================\n\nCode:\n```text\n@Entity(\"post\")\nexport default class Post extends BaseEntity {\n @PrimaryGeneratedColumn()\n idx: number;\n\n // Skip\n \n @Column({\n nullable: false,\n default: 0\n })\n view: number;\n\n @Column(\"timestampz\")\n @CreateDateColumn()\n created_at: Date;\n\n @Column(\"timestampz\")\n @UpdateDateColumn()\n updated_at: Date;\n}\n```\n\n```text\ngetRepository(Post).update(postId, {\n view: newViewValue,\n updated_at: () => '\"updated_at\"'\n})\n```\n\n```text\nUPDATE \"post\" SET \"view\" = $2, \"updated_at\" = \"updated_at\" WHERE \"idx\" = $1\n```\n\n```text\ngetRepository(Post).update(postId, {\n view: newViewValue,\n updated_at: () => 'now()'\n})\n```\n\n========================================\n\nComments:\n- use this code: getRepository(Post).update(postId, { view: newViewValue, updated_at: () => 'now()' })","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":100,"estimatedTokens":436}}144{"id":"stack-57540054","source":"stackoverflow","questionId":57540054,"title":"How to fix 'TypeError: relatedEntities.forEach is not a function' from typeorm","tags":["typeorm"],"text":"Title: How to fix 'TypeError: relatedEntities.forEach is not a function' from typeorm\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm setting up a server using TypeORM + PostgreSQL. When saving saving my entity to the entity's repository, I receive the error: `TypeError: relatedEntities.forEach is not a function` and the entity is not saved to the database.\n\nThis seems to only happen when I am using the `@OneToMany` or `@TreeChildren` decorators.\n\nHere is my entity class that is causing the problem:\n\n```\nimport { ServiceData } from './service-data.entity';\nimport { ManufacturerData } from './manufacturer-data.entity';\nimport { Entity, Column, PrimaryGeneratedColumn, TreeChildren } from 'typeorm';\n\n@Entity()\nexport class Advertisement {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ nullable: true })\n name?: string;\n\n @Column()\n gatewayId: string;\n\n @Column()\n rssi: number;\n\n @Column({ nullable: true })\n mac?: string;\n\n @TreeChildren()\n manufacturerData?: ManufacturerData[];\n\n @TreeChildren()\n serviceData?: ServiceData;\n}\n```\n\nThe (abbreviated) error output is: \n\n```\nUnhandledPromiseRejectionWarning: TypeError: relatedEntities.forEach is not a function\n at OneToManySubjectBuilder.buildForSubjectRelation (//src/persistence/subject-builder/OneToManySubjectBuilder.ts:78:25)\n```\n\n========================================\n\nTop Answer:\nThis error can come up when the oneTomany relationships are not properly written in the Entity design and also when you trying to store the relationships in a table.\n\nThe first One is, setting the Entity holding many of the other Entity like this\n\n```\n@OneToMany(() => Address, (address) => address.users)\naddress: Address[];\n```\n\nThe other entity that has manyToOne relationship like this,\n\n```\n@ManyToOne(() => Users, (users) => users.address)\nusers: Users;\n```\n\nIf the relationships are all good, then the problem is storing the entity relations to the database.\n\nwhen creating the user, store the relationships like this\n\n```\naddress = await this.addressRepository.findOneOrFail({\n \n where: {\n\n user_id: Number(userId),\n\n },\n\n });\n\nconst user = new User();\n\nuser.name = name;\nuser.age = age;\n\n### store the address as an array of objects to the relationship column\nusers.address = [address]\n```\n\n========================================\n\nCode:\n```js\nimport { ServiceData } from './service-data.entity';\nimport { ManufacturerData } from './manufacturer-data.entity';\nimport { Entity, Column, PrimaryGeneratedColumn, TreeChildren } from 'typeorm';\n\n@Entity()\nexport class Advertisement {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ nullable: true })\n name?: string;\n\n @Column()\n gatewayId: string;\n\n @Column()\n rssi: number;\n\n @Column({ nullable: true })\n mac?: string;\n\n @TreeChildren()\n manufacturerData?: ManufacturerData[];\n\n @TreeChildren()\n serviceData?: ServiceData;\n}\n```\n\n```text\nUnhandledPromiseRejectionWarning: TypeError: relatedEntities.forEach is not a function\n at OneToManySubjectBuilder.buildForSubjectRelation (/<project-directory>/src/persistence/subject-builder/OneToManySubjectBuilder.ts:78:25)\n```\n\n```text\nTypeError: relatedEntities.forEach is not a function\n```\n\n```text\n@OneToMany\n```\n\n```text\n@TreeChildren\n```\n\n```text\n@TreeChildren\n```\n\n```text\n@OneToMany\n```\n\n```text\nserviceData?: ServiceData;\n```\n\n```text\nserviceData?: ServiceData[];\n```\n\n```text\n@OneToMany(() => Address, (address) => address.users)\naddress: Address[];\n```\n\n```text\n@ManyToOne(() => Users, (users) => users.address)\nusers: Users;\n```\n\n```text\naddress = await this.addressRepository.findOneOrFail({\n \n where: {\n\n user_id: Number(userId),\n\n },\n\n });\n\n\nconst user = new User();\n\nuser.name = name;\nuser.age = age;\n\n### store the address as an array of objects to the relationship column\nusers.address = [address]\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":187,"estimatedTokens":956}}145{"id":"stack-64439306","source":"stackoverflow","questionId":64439306,"title":"Composite primary key in MySQL typeORM","tags":["typeorm"],"text":"Title: Composite primary key in MySQL typeORM\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI need to create a composite primary key. I have two entities are user and task.\n\nUser entity\n\n```\n@Entity('users')\nexport class User extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n public readonly id: string;\n\n @Column({ nullable: false, type: 'varchar', length: 16 })\n public readonly name: string;\n\n @OneToMany(() => Task, (task: Task) => task.user)\n public readonly tasks: Task[];\n}\n```\n\nTask entity\n\n```\n@Entity('tasks')\nexport class Task extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n public readonly id: string;\n\n @Column({ nullable: true, type: 'varchar', length: 16 })\n public readonly name: string;\n\n @Column({ type: 'varchar', nullable: false })\n public readonly userId: string;\n\n @ManyToOne(() => User, (user: User) => user.tasks)\n @JoinColumn({ name: 'userId' })\n public readonly user: User;\n}\n```\n\nIn my table `task` I have to use a composite primary key. For example `4a00a3738e90e-0007`. It's user id '4a00a3738e90e' and it's '0007' count task of user.\n\nHow can I create composite primary key? I didn't find a decision in the documentation.\n\n```\nid name userId\n4a00a3738e90e-0001 task1 4a00a3738e90e\n4a00a3738e90e-0002 task2 4a00a3738e90e\n1er04r35l56en-0001 task1 1er04r35l56en\n```\n\n========================================\n\nCode:\n```js\n@Entity('users')\nexport class User extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n public readonly id: string;\n\n @Column({ nullable: false, type: 'varchar', length: 16 })\n public readonly name: string;\n\n @OneToMany(() => Task, (task: Task) => task.user)\n public readonly tasks: Task[];\n}\n```\n\n```js\n@Entity('tasks')\nexport class Task extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n public readonly id: string;\n\n @Column({ nullable: true, type: 'varchar', length: 16 })\n public readonly name: string;\n\n @Column({ type: 'varchar', nullable: false })\n public readonly userId: string;\n\n @ManyToOne(() => User, (user: User) => user.tasks)\n @JoinColumn({ name: 'userId' })\n public readonly user: User;\n}\n```\n\n```text\nid name userId\n4a00a3738e90e-0001 task1 4a00a3738e90e\n4a00a3738e90e-0002 task2 4a00a3738e90e\n1er04r35l56en-0001 task1 1er04r35l56en\n```\n\n```text\ntask\n```\n\n```text\n4a00a3738e90e-0007\n```\n\n```text\n@ManyToOne(() => User, (user: User) => user.tasks, {primary: true})\n@JoinColumn({ name: 'userId' })\npublic readonly user: User; \n\n@PrimaryColumn({type: \"integer\"})\npublic taskCount: number;\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":112,"estimatedTokens":642}}146{"id":"stack-60758496","source":"stackoverflow","questionId":60758496,"title":"typeorm querybuilder: select relation of relation only","tags":["sql","node.js","nestjs","typeorm"],"text":"Title: typeorm querybuilder: select relation of relation only\nTags: sql, node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nSo I have those entities:\n\n```\nGroup {\n id: number;\n name: string;\n persons: Person[];\n}\n\nPerson {\n name: string;\n items: Item[];\n}\n\nItem {\n name: string;\n active: boolean;\n}\n```\n\n**What I have avaible**: an array of group id's `groupIds`.\n\n**My Goal**: To get an array of `Item` but only the one that are containt in a group that `group.id` is within the group array I have and also that have the property `active` `true`.\n\nI tried to build a querybuilder like this:\n\n```\nthis.groupRepository.createQueryBuilder('group')\n .innerJoin('group.persons', 'persons')\n .innerJoinAndSelect('persons.items', 'items')\n .where({'items.active': true, 'group.id': In(groupIds)})\n .getMany();\n```\n\nBut I only get an array of `group` (without any relations) that have a valid `item` in it.\n\nWhat do I Need to Change, if this is even possible with a single query?\n\n========================================\n\nCode:\n```text\nGroup {\n id: number;\n name: string;\n persons: Person[];\n}\n\nPerson {\n name: string;\n items: Item[];\n}\n\nItem {\n name: string;\n active: boolean;\n}\n```\n\n```text\nthis.groupRepository.createQueryBuilder('group')\n .innerJoin('group.persons', 'persons')\n .innerJoinAndSelect('persons.items', 'items')\n .where({'items.active': true, 'group.id': In(groupIds)})\n .getMany();\n```\n\n```text\ngroupIds\n```\n\n```text\nItem\n```\n\n```text\ngroup.id\n```\n\n```text\nactive\n```\n\n```text\ntrue\n```\n\n```text\ngroup\n```\n\n```text\nitem\n```\n\n```text\nthis.groupRepository.createQueryBuilder('group')\n .leftJoinAndSelect('group.persons', 'persons')\n .leftJoinAndSelect('persons.items', 'items')\n .where('items.active =:active', {active: true})\n .andWhere('group.id IN (:...groupIds)', {groupIds}) \n .getMany();\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":108,"estimatedTokens":484}}147{"id":"stack-52904825","source":"stackoverflow","questionId":52904825,"title":"TypeORM: Updating data (with relations) via Repository API","tags":["node.js","typeorm"],"text":"Title: TypeORM: Updating data (with relations) via Repository API\nTags: node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have two entities (tables): **users** and **roles**. There is a many-to-one relation between both entities (a user can have one role, roles can be related to many users). Now I want to update the user entity (which can also include an update of the user's role) by excuting following commands:\n\n```\nconst user = await this.userRepository.preload(partialUser);\nawait this.userRepository.save(user);\nreturn user;\n```\n\n### Expected behavior\n\n- `partialUser` (user properties to update) is merged with user data from database including `role`\n\n- `user` (merged object) is saved to database\n\n- new user object is returned to caller (including role)\n\n### What happens\n\n- user is merged, but `role` is not loaded (but if I add a child property `role` to `partialUser`, it's okay)\n\n- `user` (merged object) is saved to database (also with `role`, if it was part of `partialUser`)\n\n- new user object is returned, but it's missing role, if role was not updated via partialUser\n\n### Question\n\nWhy is `role` not loaded via `preload` nor `return` after `save`? Are TypeORM repositories not well made for relations or do I use it incorrectly? \n\n### My workaround\n\nAt the moment I have to read the whole `user` entity again after saving it, so that the full object (including `role` relation) can be returned to the caller. I think thats not very efficient. Is it intended that way?\n\n```\nconst user = await this.userRepository.preload(partialUser);\nawait this.userRepository.save(user);\n\nreturn this.userRepository.findOne({\n where: { id: user.id },\n relations: ['role']\n});\n```\n\n========================================\n\nCode:\n```text\nconst user = await this.userRepository.preload(partialUser);\nawait this.userRepository.save(user);\nreturn user;\n```\n\n```text\nconst user = await this.userRepository.preload(partialUser);\nawait this.userRepository.save(user);\n\nreturn this.userRepository.findOne({\n where: { id: user.id },\n relations: ['role']\n});\n```\n\n```text\npartialUser\n```\n\n```text\nrole\n```\n\n```text\nuser\n```\n\n```text\nrole\n```\n\n```text\nrole\n```\n\n```text\npartialUser\n```\n\n```text\nuser\n```\n\n```text\nrole\n```\n\n```text\npartialUser\n```\n\n```text\nrole\n```\n\n```text\npreload\n```\n\n```text\nreturn\n```\n\n```text\nsave\n```\n\n```text\nuser\n```\n\n```text\nrole\n```\n\n```text\n@ManyToMany(type => Role, role => role.User, {\n eager: true\n})\npublic roles: Role[];\n```\n\n```text\neager: true\n```\n\n========================================\n\nComments:\n- You could also resort to use relations in your query. Example adapted from their docs: `const users= await userRepository.find({ relations: [\"roles\"] });`\n- It doesn't work for 'preload'. It works for 'find'","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":142,"estimatedTokens":687}}148{"id":"stack-55095234","source":"stackoverflow","questionId":55095234,"title":"Record won't save to database with Nestjs and TypeOrm (querying works)","tags":["nestjs","typeorm"],"text":"Title: Record won't save to database with Nestjs and TypeOrm (querying works)\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nWhen I post a request, it doesn't save my entity to the database and doesn't report any errors or warnings.\n\nController:\n\n```\n@Controller('recipes')\n\nexport class RecipesController {\n constructor(private readonly recipeService: RecipesService) {}\n @Get()\n async findAll(): Promise {\n return this.recipeService.findAll();\n }\n\n @Post()\n async create(@Body() createRecipeDto: Recipe) {\n this.recipeService.create(createRecipeDto);\n }\n}\n```\n\nService:\n\n```\n@Injectable()\nexport class RecipesService {\n constructor(@InjectRepository(Recipe) private readonly recipeRepository: Repository) {}\n\n async create(recipe: Recipe) {\n const d = await this.recipeRepository.create(recipe);\n console.log(\"d:\", d);\n }\n\n async findAll() {\n return await this.recipeRepository.find();\n }\n}\n```\n\nEntity:\n\n```\n@Entity()\nexport class Recipe {\n @PrimaryGeneratedColumn()\n id: number;\n\n // @IsString()\n @Column()\n name: string;\n\n // @IsString()\n @Column('text')\n description?: string;\n\n // @IsString()\n @Column()\n image: string;\n\n // @IsArray()\n ingredients: string[];\n\n // @IsArray()\n instructions: string[];\n\n // @IsString()\n @Column()\n prepTime?: string;\n\n // @IsString()\n @Column()\n cookTime?: string;\n\n // @IsString()\n @Column()\n yield?: string;\n\n // @IsNumber()\n @Column('int')\n rating?: number;\n\n // @IsArray()\n keywords?: string[];\n\n // @IsArray()\n categories: string[];\n\n // @IsString()\n @Column()\n cuisine?: string;\n\n // @IsBoolean()\n @Column('boolean')\n draft?: boolean;\n}\n```\n\nMy request using Postman:\n\n```\ncurl -X POST \\\n http://localhost:3000/recipes \\\n -H 'Content-Type: application/json' \\\n -H 'Postman-Token: f23b5d42-1c40-4dae-b9b8-b32b733f38b4' \\\n -H 'cache-control: no-cache' \\\n -d '{\n \"name\":\"recipe5\",\n \"description\": \"desc\",\n \"image\": \"http://..\",\n \"ingredients\": [\"-\"],\n \"instructions\": [\"1\"],\n \"prepTime\": \"1:20\",\n \"cookTime\": \"1:00\",\n \"yield\": \"8 servings\",\n \"rating\": 4,\n \"keywords\": [\"1\"],\n \"categories\": [\"cat1\", \"cat2\"],\n \"cuisine\": \"American\",\n \"draft\": false\n}'\n```\n\nIt returns 201.\nMy GET call only returns the entry I created manually.\n\n========================================\n\nCode:\n```text\n@Controller('recipes')\n\nexport class RecipesController {\n constructor(private readonly recipeService: RecipesService) {}\n @Get()\n async findAll(): Promise<Recipe[]> {\n return this.recipeService.findAll();\n }\n\n @Post()\n async create(@Body() createRecipeDto: Recipe) {\n this.recipeService.create(createRecipeDto);\n }\n}\n```\n\n```text\n@Injectable()\nexport class RecipesService {\n constructor(@InjectRepository(Recipe) private readonly recipeRepository: Repository<Recipe>) {}\n\n async create(recipe: Recipe) {\n const d = await this.recipeRepository.create(recipe);\n console.log(\"d:\", d);\n }\n\n async findAll() {\n return await this.recipeRepository.find();\n }\n}\n```\n\n```text\n@Entity()\nexport class Recipe {\n @PrimaryGeneratedColumn()\n id: number;\n\n // @IsString()\n @Column()\n name: string;\n\n // @IsString()\n @Column('text')\n description?: string;\n\n // @IsString()\n @Column()\n image: string;\n\n // @IsArray()\n ingredients: string[];\n\n // @IsArray()\n instructions: string[];\n\n // @IsString()\n @Column()\n prepTime?: string;\n\n // @IsString()\n @Column()\n cookTime?: string;\n\n // @IsString()\n @Column()\n yield?: string;\n\n // @IsNumber()\n @Column('int')\n rating?: number;\n\n // @IsArray()\n keywords?: string[];\n\n // @IsArray()\n categories: string[];\n\n // @IsString()\n @Column()\n cuisine?: string;\n\n // @IsBoolean()\n @Column('boolean')\n draft?: boolean;\n}\n```\n\n```text\ncurl -X POST \\\n http://localhost:3000/recipes \\\n -H 'Content-Type: application/json' \\\n -H 'Postman-Token: f23b5d42-1c40-4dae-b9b8-b32b733f38b4' \\\n -H 'cache-control: no-cache' \\\n -d '{\n \"name\":\"recipe5\",\n \"description\": \"desc\",\n \"image\": \"http://..\",\n \"ingredients\": [\"-\"],\n \"instructions\": [\"1\"],\n \"prepTime\": \"1:20\",\n \"cookTime\": \"1:00\",\n \"yield\": \"8 servings\",\n \"rating\": 4,\n \"keywords\": [\"1\"],\n \"categories\": [\"cat1\", \"cat2\"],\n \"cuisine\": \"American\",\n \"draft\": false\n}'\n```\n\n```text\nconst d = await this.recipeRepository.create(recipe);\n```\n\n```text\nconst d = await this.recipeRepository.save(recipe);\n```\n\n```text\nRepository.save\n```\n\n========================================\n\nComments:\n- I wish the NestJS documentation made this clear..","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":261,"estimatedTokens":1122}}149{"id":"stack-69471840","source":"stackoverflow","questionId":69471840,"title":"Cannot query across one-to-many for property NestJS and TypeORM","tags":["javascript","postgresql","nestjs","typeorm"],"text":"Title: Cannot query across one-to-many for property NestJS and TypeORM\nTags: javascript, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have two entities one is `car` and another one is `carAvailability`\n\n```\nimport { Entity, Column, PrimaryGeneratedColumn, OneToMany } from 'typeorm';\nimport { CarAvailability } from 'src/car-availabilitys/car-availability.entity';\n\n@Entity('cars')\nexport class Car {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToMany(() => CarAvailability, (carAvailability) => carAvailability.car, {\n eager: true,\n cascade: true,\n })\n availabilities: CarAvailability[];\n}\n```\n\nI am trying to add a service that queries and filters cars based on the availabilities. In My Service and tried two ways:\n\nMethod 1 with repo functions:\n\n```\nasync test () {\n const startDateTime = '2012-04-24 02:25:43.511';\n\n return await this.repo.find({\n relations: ['availabilities'],\n where: {\n availabilities: {\n start_date_time: startDateTime\n }\n }\n });\n}\n```\n\nMethod 2 with query builder:\n\n```\nasync test () {\n const startDateTime = '2012-04-24 02:25:43.511';\n\n return this.repo.createQueryBuilder('cars')\n .innerJoin('cars.availabilities', 'car_availabilities')\n .where(\"cars.availabilities.start_date_time = :startDateTime\", { startDateTime })\n .getMany();\n}\n```\n\nMethod 1 error:\n\n```\nError: Cannot query across one-to-many for property availabilities\n```\n\nMethod 2 error:\n\n```\nQueryFailedError: missing FROM-clause entry for table \"availabilities\"\n```\n\nI feel like I am missing something but I am not sure. Have referred both NestJS and TypeORM docs but can't seem to figure out what went wrong.\n\n========================================\n\nTop Answer:\nUsing Method 1 repo functions with nested query builder:\n\n```\nasync test () {\n const startDateTime = '2012-04-24 02:25:43.511';\n\n return await this.repo.find({\n relations: ['availabilities'],\n where: (qb) => {\n qb.where('availabilities.start_date_time = :startDateTime', {\n startDateTime\n });\n }\n });\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Entity, Column, PrimaryGeneratedColumn, OneToMany } from 'typeorm';\nimport { CarAvailability } from 'src/car-availabilitys/car-availability.entity';\n\n@Entity('cars')\nexport class Car {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToMany(() => CarAvailability, (carAvailability) => carAvailability.car, {\n eager: true,\n cascade: true,\n })\n availabilities: CarAvailability[];\n}\n```\n\n```text\nasync test () {\n const startDateTime = '2012-04-24 02:25:43.511';\n\n return await this.repo.find({\n relations: ['availabilities'],\n where: {\n availabilities: {\n start_date_time: startDateTime\n }\n }\n });\n}\n```\n\n```text\nasync test () {\n const startDateTime = '2012-04-24 02:25:43.511';\n\n return this.repo.createQueryBuilder('cars')\n .innerJoin('cars.availabilities', 'car_availabilities')\n .where(\"cars.availabilities.start_date_time = :startDateTime\", { startDateTime })\n .getMany();\n}\n```\n\n```text\nError: Cannot query across one-to-many for property availabilities\n```\n\n```text\nQueryFailedError: missing FROM-clause entry for table \"availabilities\"\n```\n\n```text\ncar\n```\n\n```text\ncarAvailability\n```\n\n```text\ncar_availabilities.start_date_time\n```\n\n```text\ncars.availabilities.start_date_time\n```\n\n```text\ncar.availabilities\n```\n\n```text\ncar_availabilities\n```\n\n```text\nwhere\n```\n\n```text\nasync test () {\n const startDateTime = '2012-04-24 02:25:43.511';\n\n return await this.repo.find({\n relations: ['availabilities'],\n where: (qb) => {\n qb.where('availabilities.start_date_time = :startDateTime', {\n startDateTime\n });\n }\n });\n}\n```\n\n```text\n{\n cascade: true,\n onDelete: 'CASCADE',\n onUpdate:'CASCADE'\n}\n```\n\n```text\ncascade\n```\n\n```text\noneToMany\n```\n\n```text\nmanyToOne\n```\n\n```text\n['availabilities']\n```\n\n```text\neager: true\n```\n\n```text\nreturn await this.repository.find({relations: ['availabilities'])\n.then((cars) => cars.filter((car) => car.start_date_time === startDateTime));\n```\n\n========================================\n\nComments:\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.\n- This is not a preferred method because you are doing the filtering in code instead of in SQL (not very efficient). This method always returns all results and then loops thru them to filter the ones you want.\n- You're right but this is the only solution i could find","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":232,"estimatedTokens":1158}}150{"id":"stack-71585167","source":"stackoverflow","questionId":71585167,"title":"Typeorm typescript repository findone - Argument of type is not assignable to parameter of type 'FindOneOptions'","tags":["mysql","typescript","discord.js","typeorm"],"text":"Title: Typeorm typescript repository findone - Argument of type is not assignable to parameter of type 'FindOneOptions'\nTags: mysql, typescript, discord.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nHere is my configuration file.\n\n```\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity({ name: 'guild_configurations' })\nexport class GuildConfiguration {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ unique: true, name: 'guild_id' })\n guildId: string;\n\n @Column({ default: '?' })\n prefix: string;\n\n @Column({ name: 'welcome_channel_id', nullable: true })\n welcomeChannelId: string;\n}\n```\n\nI was trying to add search guildId with discord guild.id\n\n```\n// https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=e-guildCreate\nimport { Guild } from 'discord.js';\nimport BaseEvent from '../utils/structures/BaseEvent';\nimport DiscordClient from '../client/client';\nimport { getRepository, ObjectID } from 'typeorm';\nimport { GuildConfiguration } from '../typeorm/entities/GuildConfiguration';\n\nexport default class GuildCreateEvent extends BaseEvent {\n constructor(\n private readonly guildConfigRepository = getRepository(GuildConfiguration)\n ) {\n super('guildCreate');\n }\n \n async run(client: DiscordClient, guild: Guild) {\n console.log(\"Hello World\");\n console.log(`Joined ${guild.name}`);\n const config = await this.guildConfigRepository.findOne({guildId:guild.id});\n if(config){\n console.log(\"A configuration was found!\")\n }else{\n console.log(\"Configuration was not found. Creating one...\")\n const newConfig = this.guildConfigRepository.create({guildId:guild.id})\n return this.guildConfigRepository.save(newConfig);\n }\n \n }\n}\n```\n\nthis.guildConfigRepository.findOne({guildId:guild.id});\nit shows\n\nArgument of type '{ guildId: string; }' is not assignable to parameter of type 'FindOneOptions'.\nObject literal may only specify known properties, and 'guildId' does not exist in type 'FindOneOptions'.ts(2345)\n\nmy typeorm version is \"typeorm\": \"^0.3.1\"\nDoes anyone know how to fix this?\nThanks!\n\n========================================\n\nTop Answer:\nAs you're using the 0.3.x typeorm you might use the `findOneBy` instead of `findOne`.\n\n```\nconst config = await this.guildConfigRepository.findOneBy({guildId:guild.id});\n```\n\n========================================\n\nCode:\n```text\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity({ name: 'guild_configurations' })\nexport class GuildConfiguration {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ unique: true, name: 'guild_id' })\n guildId: string;\n\n @Column({ default: '?' })\n prefix: string;\n\n @Column({ name: 'welcome_channel_id', nullable: true })\n welcomeChannelId: string;\n}\n```\n\n```text\n// https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=e-guildCreate\nimport { Guild } from 'discord.js';\nimport BaseEvent from '../utils/structures/BaseEvent';\nimport DiscordClient from '../client/client';\nimport { getRepository, ObjectID } from 'typeorm';\nimport { GuildConfiguration } from '../typeorm/entities/GuildConfiguration';\n\nexport default class GuildCreateEvent extends BaseEvent {\n constructor(\n private readonly guildConfigRepository = getRepository(GuildConfiguration)\n ) {\n super('guildCreate');\n }\n \n async run(client: DiscordClient, guild: Guild) {\n console.log(\"Hello World\");\n console.log(`Joined ${guild.name}`);\n const config = await this.guildConfigRepository.findOne({guildId:guild.id});\n if(config){\n console.log(\"A configuration was found!\")\n }else{\n console.log(\"Configuration was not found. Creating one...\")\n const newConfig = this.guildConfigRepository.create({guildId:guild.id})\n return this.guildConfigRepository.save(newConfig);\n }\n \n }\n}\n```\n\n```text\nthis.guildConfigRepository.findOne({ \n where: { \n guildId: guild.id \n } \n});\n```\n\n```text\nwhere\n```\n\n```text\nconst config = await this.guildConfigRepository.findOneBy({guildId:guild.id});\n```\n\n```text\nfindOneBy\n```\n\n```text\nfindOne\n```\n\n```text\nconst findOptions: FindOneOptions<T> = {\n where: {\n id: entity.id,\n } as FindOptionsWhere<T>,\n };\nreturn this.repo.findOne(findOptions);\n```\n\n```text\nthis.usersRepository.findOne({\n where: {\n email: Equal(authUser.email),\n password: Equal(authUser.password),\n }\n})\n```\n\n```js\nimport { Repository, Equal } from \"typeorm\";\n```\n\n```text\nEqual\n```\n\n```text\nEqual\n```\n\n```text\nthis.guildConfigRepository.findOneBy({ \n guildId: guild.id\n});\n```\n\n```text\nfindOneBy\n```\n\n========================================\n\nComments:\n- What if you do: `this.guildConfigRepository.findOne({ where: { guildId: guild.id } });`?\n- good point! But have downgraded, would try it out next time :)\n- @Almaju it works, thanks a lot! Guess, you can write it like the answer\n- no need to download you can use @almaju's answer (just add where clause)\n- @AshiqDey except that \"just don't use this version\" isn't really a solution.\n- It is also known as `TS2345` at nestjs.\n- this worked for typeorm version 0.3.10\n- `Argument of type '{ id: number; }' is not assignable to parameter of type 'FindOptionsWhere | FindOptionsWhere[]'.`\n- I do have the same Issue as you @KokHowTeh, did you find a solution?\n- Thanks, this is great and also allows to build query methods with generic classes which resulted in compilation errors otherwise.\n- This was the only way i could get typeOrm to work with mongoDb when trying to search properties in nested arrays e.g. array1.array2.myProperty. Dspite the typeOrm documentation saying i could do e.g. where: { \"array1.array2.myProperty\": { $eq: myValue }} as part of the findOne, I kept getting the above error but splitting the options into it's own variable as per this answer allowed it to compile","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":209,"estimatedTokens":1445}}151{"id":"stack-72864723","source":"stackoverflow","questionId":72864723,"title":"which is Better in typeorm Save Or Update","tags":["nestjs","typeorm","node.js-typeorm"],"text":"Title: which is Better in typeorm Save Or Update\nTags: nestjs, typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nI was working on a project and I wanted to update the data but I don't know which is the faster way to update data SAVE() method or Update()\n\n```\nthis.repo.save({\nid:id,\ndata})\n```\n\n========================================\n\nTop Answer:\nActually they are for different purposes\n\n**save()**\nit saves the entity you provided if your entry doesn't have an identifier (id) or the id doesn't exist in the DB, it tries to create a new one. Otherwise, it updates the entity itself.\n\n**update()**\nit executes a simple `UPDATE table SET....` query. It means you can use it for updating an entity 'partially'. It's handy for 'patching' things.\n\nTL;TR\n\n- use `save()` for creating a new record or updating the whole entity at once\n\n- use `update()` for updating an entity partially.\n\n========================================\n\nCode:\n```text\nthis.repo.save({\nid:id,\ndata})\n```\n\n```text\nUPDATE table SET....\n```\n\n```text\nsave()\n```\n\n```text\nupdate()\n```\n\n========================================\n\nComments:\n- Hi thank you for the help and i really appreciate your support ........!!!! but I need to know which method is more faster in querying like taking less time and more optimize way\n- if you want to update a record; `update()` would be faster. Because you don't need to fetch the actual record itself, you can directly call the update with the id and fields you want to update.\n- then what is the difference and use case of upsert?\n- and save will update or create new one , on which condition save willl update? can i pass custom criteria for that?\n- This is a super important detail: `update()` does not contain the entity for subscribers (it will undefined).","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":59,"estimatedTokens":444}}152{"id":"stack-72108412","source":"stackoverflow","questionId":72108412,"title":"Why skip() and take() not works when I use getRawMany() in nestJS with typeorm?","tags":["nestjs","typeorm"],"text":"Title: Why skip() and take() not works when I use getRawMany() in nestJS with typeorm?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHere is the code I currently use.\n\nwith getRawMany() - skip and take not works!\n\n\r\n\r\n\n```\nconst data = await getRepository(Enquiry)\n .createQueryBuilder('enq')\n .select([\n 'enq.id AS id',\n 'enq.location AS location',\n 'enqStatus.name AS status'\n ])\n .leftJoin('enq.status', 'enqStatus')\n .skip(1)\n .take(3)\n .where(payload)\n .getRawMany()\n```\n\n========================================\n\nTop Answer:\nStrangely, `skip()` and `take()` do not work well with joins, you should use `offset()` and `limit()`.\nYou can read more about this in this open issue in TypeORM repository:\nhttps://github.com/typeorm/typeorm/issues/4742\n\n========================================\n\nCode:\n```js\nconst data = await getRepository(Enquiry)\n .createQueryBuilder('enq')\n .select([\n 'enq.id AS id',\n 'enq.location AS location',\n 'enqStatus.name AS status'\n ])\n .leftJoin('enq.status', 'enqStatus')\n .skip(1)\n .take(3)\n .where(payload)\n .getRawMany()\n```\n\n```text\nconst data = await getRepository(Enquiry)\n .createQueryBuilder('enq')\n .select([\n 'enq.id AS id',\n 'enq.location AS location',\n 'enqStatus.name AS status'\n ])\n .leftJoin('enq.status', 'enqStatus')\n .where(payload)\n .offset(meta.page)\n .limit(meta.pageSize)\n .getRawMany()\n```\n\n```text\nskip()\n```\n\n```text\ntake()\n```\n\n```text\noffset()\n```\n\n```text\nlimit()\n```\n\n========================================\n\nComments:\n- you need leftJoinAndSelect, late answer but I think it will work ~\n- I tried this but not worked! :(\n- Did you try with `limit` and `offset`? I think the `leftJoin` would cause this issue.\n- limit and offset works! Thank bro :)\n- in conjunction joins this will not work as expected as it limits to total of all child-records (e.g. joining an article with keywords, then you'll get only one article but 3 keywords when doing \"limit 3\"\n- Great it worked but itd be much better if its explained why this works and skip take doesnt","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":92,"estimatedTokens":514}}153{"id":"stack-62894090","source":"stackoverflow","questionId":62894090,"title":"TypeORM select with case insensitive distinct","tags":["javascript","node.js","postgresql","typeorm"],"text":"Title: TypeORM select with case insensitive distinct\nTags: javascript, node.js, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a TypeORM query builder that connects to a postgresql DB to get all unique names in the DB. My query looks like this\n\n```\nnames = await this._context.manager\n .getRepository(Names)\n .createQueryBuilder('names')\n .select('DISTINCT ON (names.name) names.name')\n .orderBy('names.name', 'ASC')\n .getRawMany();\n```\n\nRight now this query fetches all names in the DB but it's case sensitive so it can't sort out duplicates like 'Jane Doe' from 'jane doe'. So far i've tried to make the distinct upper/lowercase like this:\n`.select('DISTINCT ON LOWER(names.name) names.name')` but that doesn't work. I also found a .distinctOn() function but i couldn't make that case insensitive either.\n\nI'm new to typeORM so i'm at a bit of a loss on where to go from here, any ideas?\n\nI'm working in Node.JS towards a postgresql DB if that makes a difference.\n\n========================================\n\nTop Answer:\nWith Repository, I did the case insensitive search with postgres as database using `ILIKE` operator in this way\n\n```\nconst planning_groups: any[] =\n await this.planningGroupRepository.find({\n where: `\"tenant_id\" ILIKE '${tenantId}'` \n });\n```\n\nwhere **tenant_id** is a column name and `tenantId` is a keyword to search for.\n\n========================================\n\nCode:\n```text\nnames = await this._context.manager\n .getRepository(Names)\n .createQueryBuilder('names')\n .select('DISTINCT ON (names.name) names.name')\n .orderBy('names.name', 'ASC')\n .getRawMany();\n```\n\n```text\n.select('DISTINCT ON LOWER(names.name) names.name')\n```\n\n```text\nnames = await this._context.manager\n .getRepository(Names)\n .createQueryBuilder('names')\n .select('DISTINCT ON (LOWER(names.name)) names.name')\n .orderBy('LOWER(names.name)', 'ASC')\n .getRawMany();\n```\n\n```text\nconst planning_groups: any[] =\n await this.planningGroupRepository.find({\n where: `\"tenant_id\" ILIKE '${tenantId}'` \n });\n```\n\n```text\nILIKE\n```\n\n```text\ntenantId\n```\n\n========================================\n\nComments:\n- Yeah this works like a charm :) I tried the LOWER before but i missed adding it to the orderBy as well so i didn't get any results. Thanks a lot!\n- How do you write this to search on a column of a relation?\n- This doesn't work for me (\"typeorm\": \"^0.3.17\",) `Type 'string' is not assignable to type 'FindOptionsWhere | FindOptionsWhere[] | undefined'.ts(2322)`","metadata":{"transformedAt":"2026-08-18T18:33:44.695Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":83,"estimatedTokens":642}}154{"id":"stack-51697680","source":"stackoverflow","questionId":51697680,"title":"How do you detect if an attribute like password has changed in typeorm","tags":["javascript","node.js","nestjs","typeorm"],"text":"Title: How do you detect if an attribute like password has changed in typeorm\nTags: javascript, node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn typeorm, I am trying to use a subscriber decorator to hash users password before persisting to the database. Unfortunately, I can't find a reference in the docs.\n\nIn sequelizejs, I use the following code,\n\n```\nUser.hashPassword = (user, options) => {\n if (!user.changed('password')) {\n return null;\n }\n // hash password\n return Bcrypt.hash(user.get('password'), SALT_ROUNDS)\n .then(hash => user.set('password', hash));\n };\n```\n\nRight now, I am trying to migrate the code to `typeorm` and my translation is roughly\n\n```\n@BeforeInsert()\n@BeforeUpdate()\nhashPassword() {\n // conditional to detect if password has changed goes here\n this.password = bcrypt.hashSync(this.password, SALT_ROUNDS);\n}\n```\n\nThe issue is, I stuck at `!user.changed('password')`. Is there an equivalent function in `typeorm` to do this without rolling out my own solution?\n\n========================================\n\nTop Answer:\nYou can try this: \n\n```\n@BeforeInsert()\n@BeforeUpdate()\nhashPassword() {\n if (this.password) {\n this.password = createHmac('sha256', this.password).digest('hex');\n }\n}\n```\n\nI just check if a password is present in the DTO (before update and insert). If it is present, I should hash it.\n\n========================================\n\nCode:\n```text\nUser.hashPassword = (user, options) => {\n if (!user.changed('password')) {\n return null;\n }\n // hash password\n return Bcrypt.hash(user.get('password'), SALT_ROUNDS)\n .then(hash => user.set('password', hash));\n };\n```\n\n```text\n@BeforeInsert()\n@BeforeUpdate()\nhashPassword() {\n // conditional to detect if password has changed goes here\n this.password = bcrypt.hashSync(this.password, SALT_ROUNDS);\n}\n```\n\n```text\ntypeorm\n```\n\n```text\n!user.changed('password')\n```\n\n```text\ntypeorm\n```\n\n```text\n@Entity()\nexport class User extends BaseEntity {\n @PrimaryColumn()\n public username: string;\n\n @Column()\n public password: string;\n\n @Column({ nullable: true })\n public jwtToken: string;\n\n private tempPassword: string;\n\n\n @AfterLoad()\n private loadTempPassword(): void {\n this.tempPassword = this.password;\n }\n\n @BeforeUpdate()\n private encryptPassword(): void {\n if (this.tempPassword !== this.password) {\n //\n }\n }\n```\n\n```text\n@AfterLoad\n```\n\n```text\n@BeforeInsert()\n@BeforeUpdate()\nhashPassword() {\n if (this.password) {\n this.password = createHmac('sha256', this.password).digest('hex');\n }\n}\n```\n\n```text\n----------\n\n private tempPassword: string\n\n /// commit to handle the password if i not change it it will be not encription\n\n\n @AfterLoad()\n private loadTempPassword(): void {\n this.tempPassword = this.password;\n }\n\n\n\n\n @BeforeInsert()\n @BeforeUpdate()\n async hashPassword(): Promise<void> {\n // cheack if that password changing or not\n if (this.tempPassword !== this.password) {\n\n try {\n this.password = await bcrypt.hash(this.password, 10)\n\n } catch (e) {\n throw new InternalServerErrorException('there are some issiue in the hash')\n\n }\n }\n\n\n }\n```\n\n```text\n@Column('string', { select: false })\n password:string\n```\n\n```text\nwe check if the password is found or not \n if (this.password) {\n//make hash \n}\n```\n\n```text\n@AfterLoad()\n private loadTempPassword(): void {\n this.tempPassword = this.password;\n }\n```\n\n```text\n@BeforeInsert()\n @BeforeUpdate()\n async hashPassword(): Promise<void> {\n // cheack if that password changing or not\n if (this.password) {\n if (this.tempPassword !== this.password) {\n\n try {\n this.password = await bcrypt.hash(this.password, 10)\n\n } catch (e) {\n throw new InternalServerErrorException('there are some issiue in the hash')\n\n }\n }\n }\n```\n\n========================================\n\nComments:\n- Did you find some solution for this?\n- @Hammerbot No, I did not. What I did was to check if the `user.password` property is present in the update request. If it is present, confirm that it is a plain string to prevent a double hash. Then manually run the `bcrypt.hash()` on the plain string before persisting.\n- Have you tried using a subscriber? github.com/typeorm/typeorm/blob/master/docs/…\n- It's important to note here that Entity Listeners are not fired when using repository methods like `.update()` and `.delete()` since the entity is not loaded. If you want to make sure these methods fire, you need to load the entity (with `.findOne()`), update it and then use the `.save()` method. See this github thread for more details\n- But how do you validate password length etc with `class-validator` in encryptPassword? Would you do it manually instead?","metadata":{"transformedAt":"2026-08-18T18:33:44.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":208,"estimatedTokens":1204}}155{"id":"stack-57762374","source":"stackoverflow","questionId":57762374,"title":"How configure TypeORM ormconfig.json file to parse Entities from js dist folder or ts src folder?","tags":["node.js","typeorm"],"text":"Title: How configure TypeORM ormconfig.json file to parse Entities from js dist folder or ts src folder?\nTags: node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nI set my TypeORM config entities path like:\n\n```\n\"entities\": [\"src/entities/**/*.ts\"]\n```\n\nThis works good when I use ts-node. `ts-node src/main.ts`\n\nAfter compile typescripts using `tsc`, I got a `dist` folder with the compiled application:\n\nHowever, typeORM still tries to get entities from the `src` folder instead of `dist`. throwing a lot of unexpectec syntax errors for parsing a TS file instead of a JS. So I change the fallowing string to the entities condiguration:\n\n```\n\"entities\": [\"dist/entities/**/*.js\"]\n```\n\nIt works with node `node dist/main.js` but it does not works with `ts-node src/main.ts`\n\nHow can I configure `ormconfig.json` to be able to work with both (`node` at `dist` folder and `ts-node` at `src` folder)?\n\n========================================\n\nTop Answer:\nIn **addition** to the existing answer:\n\nI didn't like the idea to much to always work on the dist folder. Why? Because when I run commands from the command line I don't want to check whether dist is up-to-date, meaning was recently compiled.\n\nSo, I like my my `typeorm` commands like `typeorm schema:sync` work on the `src`! You can do that by running them via `ts-node`.\n\nSo, instead of\n\n```\ntypeorm schema:sync\n```\n\nuse\n\n```\n// Linux\nts-node ./node_modules/.bin/typeorm schema:sync\n\n// Windows\nts-node ./node_modules/typeorm/cli.js schema:sync\n```\n\n### Background\n\ntypeorm cli uses node, which relies on the files being compiled to javascript. So, that would only work on the /dist folder, which is the compiled version. However, that requires a watcher or similar running to capture changes of your ORM files. The described way here compiles typescript on-the-fly making a compilation not required. Source: https://github.com/typeorm/typeorm/blob/master/docs/faq.md#how-to-use-typeorm-with-ts-node\n\n========================================\n\nCode:\n```text\n\"entities\": [\"src/entities/**/*.ts\"]\n```\n\n```text\n\"entities\": [\"dist/entities/**/*.js\"]\n```\n\n```text\nts-node src/main.ts\n```\n\n```text\ntsc\n```\n\n```text\ndist\n```\n\n```text\nsrc\n```\n\n```text\ndist\n```\n\n```text\nnode dist/main.js\n```\n\n```text\nts-node src/main.ts\n```\n\n```text\normconfig.json\n```\n\n```text\nnode\n```\n\n```text\ndist\n```\n\n```text\nts-node\n```\n\n```text\nsrc\n```\n\n```text\nconst srcConfig = {\n \"entities\": [\n \"src/entities/**/*.ts\"\n ],\n}\n\nconst distConfig = {\n \"entities\": [\n \"dist/entities/**/*.js\"\n ],\n}\n\nmodule.exports = process.env.TS_NODE ? srcConfig : distConfig;\n```\n\n```text\normconfig.js\n```\n\n```text\nTS_NODE\n```\n\n```text\ntypeorm schema:sync\n```\n\n```text\n// Linux\nts-node ./node_modules/.bin/typeorm schema:sync\n\n// Windows\nts-node ./node_modules/typeorm/cli.js schema:sync\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeorm schema:sync\n```\n\n```text\nsrc\n```\n\n```text\nts-node\n```\n\n```text\n//npm install --save \"detect-ts-node\"\nconst detectTSNode = require('detect-ts-node');\n\nconst commonConfig = {\n \"type\": \"mssql\",\n \"host\": \"127.0.0.1\",\n \"port\": 1433,\n \"username\": \"sa\",\n \"password\": \"$$$$$$\",\n \"database\": \"$$$$$$\",\n \"synchronize\": true,\n \"logging\": false,\n \"options\": {\n \"encrypt\": false,\n \"enableArithAbort\": false\n }\n};\n\n\nconst srcConfig = {\n \"entities\": [\n \"src/entity/**/*.ts\"\n ],\n \"migrations\": [\n \"src/migration/**/*.ts\"\n ],\n \"subscribers\": [\n \"src/subscriber/**/*.ts\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n};\n\nconst distConfig = {\n \"entities\": [\n __dirname + \"/dist/entity/**/*.js\"\n ],\n \"migrations\": [\n __dirname + \"/dist/migration/**/*.js\"\n ],\n \"subscribers\": [\n __dirname + \"/dist/subscriber/**/*.js\"\n ],\n \"cli\": {\n \"entitiesDir\": __dirname + \"/dist/entity\",\n \"migrationsDir\": __dirname + \"/dist/migration\",\n \"subscribersDir\": __dirname + \"/dist/subscriber\"\n }\n};\n\n\nconst result = {};\nlet key;\n\n// Append common configs to final object\nfor (key in commonConfig) {\n if (commonConfig.hasOwnProperty(key)) {\n result[key] = commonConfig[key];\n }\n}\n\nif (detectTSNode) {\n // if ts-node append src configuration\n for (key in srcConfig) {\n if (srcConfig.hasOwnProperty(key)) {\n result[key] = srcConfig[key];\n }\n }\n} else {\n // else append dist configuration\n for (key in distConfig) {\n if (distConfig.hasOwnProperty(key)) {\n result[key] = distConfig[key];\n }\n }\n\n}\n\n\nmodule.exports = result;\n```\n\n```text\nimport { createConnection } from \"typeorm\";\nconst conf = require('../ormconfig.js');\n\n// Print the result for debuggin purposes\nconsole.log(conf);\n\ncreateConnection(conf).then(async connection => {\n console.log(\"do your job here\")\n}).catch(error => {\n console.log(error)\n});\n```\n\n========================================\n\nComments:\n- For the people looking for the linked PR. It has been merged, by including a symbol on the process variable. To branch your code in case you are running with *ts_node*, you can check if `process[Symbol.for(\"ts-node.register.instance\")]` is *truthy*.","metadata":{"transformedAt":"2026-08-18T18:33:44.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":269,"estimatedTokens":1314}}156{"id":"stack-66693362","source":"stackoverflow","questionId":66693362,"title":"How to excute Raw SQL Query on NestJS framework using typeorm","tags":["postgresql","nestjs","typeorm"],"text":"Title: How to excute Raw SQL Query on NestJS framework using typeorm\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am going to execute such a long query on the NestJS framework using Typeform.\nPlease let me know how to execute this query.\n\n```\nselect user.id, user.fullName, (select count(*) sendCnt from chat where senderId = user.id), (select count(*) recvCnt from chat where receiverId = user.id) from users user where user.role = 'Admin'\n```\n\n========================================\n\nTop Answer:\nyou can use typeorm - DataSource module for execute raw SQL queries\n\nplease refer below example\n\n```\nimport { DataSource } from 'typeorm';\n\nexport class {\n constructor(\n @InjectDataSource() private dataSource: DataSource,\n) {}\n\n async function_name () {\n this.dataSource.query()\n }\n}\n```\n\n========================================\n\nCode:\n```text\nselect user.id, user.fullName, (select count(*) sendCnt from chat where senderId = user.id), (select count(*) recvCnt from chat where receiverId = user.id) from users user where user.role = 'Admin'\n```\n\n```js\nconst rawData = await connection.query(`SELECT * FROM USERS`);\n```\n\n```js\n@Injectable()\nexport class FooService {\n constructor(@InjectConnection() private readonly connection: Connection) {}\n\n async doSomeQuery() {\n return this.connection.query('SELECT * FROM USERS;');\n }\n}\n```\n\n```text\nTypeORM\n```\n\n```text\n@InjectConnection()\n```\n\n```text\nquery\n```\n\n```text\n@nestjs/typeorm\n```\n\n```text\nthis.connection\n```\n\n```text\n@InjectConnection()\n```\n\n```text\n@InjectConnection()\n```\n\n```text\n@InjectDataSource()\n```\n\n```text\nreturn await getRepository(users)\n.createQueryBuilder(\"user\")\n.where(\"user.role = 'Admin'\")\n.select(\"user.id as userId\")\n.addSelect(\"user.fullName as fullName\")\n.addSelect(\"(select count(*) sendCnt from chat where senderId = user.id) as sendCnt\")\n.addSelect(\"(select count(*) recvCnt from chat where receiverId = user.id) as recvCnt\")\n.printSql()\n.getRawMany();\n```\n\n```text\nimport { getManager } from 'typeorm';\n\nconst entityManager = getManager();\nreturn entityManager.query(`SELECT * FROM users`)\n```\n\n```text\nreturn entityManager.query(`select user.id, user.fullName, (select count(*) sendCnt from chat where senderId = user.id), (select count(*) recvCnt from chat where receiverId = user.id) from users user where user.role = 'Admin'`)\n```\n\n```text\nimport { DataSource } from 'typeorm';\n\nexport class <class name> {\n constructor(\n @InjectDataSource() private dataSource: DataSource,\n) {}\n\n async function_name () {\n this.dataSource.query(<QUERY>)\n }\n}\n```\n\n========================================\n\nComments:\n- Currently, I am using PostgreSQL. Could you please let me know the detailed base code for this functionality?\n- I'm not sure I the question.\n- Please, provide a bit more information if you can, i.e: how you import connection and inject it in constructor or? Thanks.\n- @textoro just added a small example\n- @JayMcDoniel et al. `@InjectConnection()` decorator is now deprecated. Use `@InjectDataSource()` now.\n- After InjectConnection() is deprecated. This solution work for me.","metadata":{"transformedAt":"2026-08-18T18:33:44.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":133,"estimatedTokens":776}}157{"id":"stack-74542474","source":"stackoverflow","questionId":74542474,"title":"How to create custom (separate file) repository in NestJS 9 with TypeORM 0.3.x","tags":["nestjs","typeorm","repository-pattern"],"text":"Title: How to create custom (separate file) repository in NestJS 9 with TypeORM 0.3.x\nTags: nestjs, typeorm, repository-pattern\nSource: Stack Overflow\n\nQuestion:\n*This is not a duplicate Q. Please don't mark this as that.*\n\nFollowing is not I want\n\n```\nimport { EntityRepository, Repository } from \"typeorm\";\nimport { Test } from \"./test.model\";\nimport { Injectable } from \"@nestjs/common\";\n\n@EntityRepository(Test)\nexport class TestRepository extends Repository {}\n```\n\nthe `@EntityRepository` decorator is now deprecated.\n\nI also don't want to make a fake repository like in here:\nhttps://stackoverflow.com/a/73352265/5420070\n\nDon't want this either as I've to extract `manager` from `dataSource`, I don't want this because I think this is not the best way.\n\n```\nexport const UserRepository = dataSource.getRepository(User).extend({\n // ^^^^^^^^^^ from where this came from\n findByName(firstName: string, lastName: string) {\n return this.createQueryBuilder(\"user\")\n .where(\"user.firstName = :firstName\", { firstName })\n .andWhere(\"user.lastName = :lastName\", { lastName })\n .getMany()\n },\n })\n```\n\nFound above in: https://orkhan.gitbook.io/typeorm/docs/custom-repository#how-to-create-custom-repository\n\nI don't think this is in NestJS context.\n\nWhat I want\nWant to know right way to make custom repository in latest version of NestJS (v9) & TypeORM (v0.3). In `@EntityRepository` deprecation note, they said that need to extend the repo to create custom repo like `someRepo.extend({})`. I want to know how to do it in NestJS way\n\n========================================\n\nTop Answer:\n```\nimport { Column, Entity, JoinColumn, ManyToOne, OneToMany } from \"typeorm\";\nimport { CustomBaseEntity } from \"../core/custom-base.entity\";//custom-made\n@Entity({name: 'rcon_log', schema: 'dbo'})\nexport class LogEntity extends CustomBaseEntity{\n------------your code-----------\n}\n```\n\n========================================\n\nCode:\n```js\nimport { EntityRepository, Repository } from \"typeorm\";\nimport { Test } from \"./test.model\";\nimport { Injectable } from \"@nestjs/common\";\n\n@EntityRepository(Test)\nexport class TestRepository extends Repository<Test> {}\n```\n\n```js\nexport const UserRepository = dataSource.getRepository(User).extend({\n // ^^^^^^^^^^ from where this came from\n findByName(firstName: string, lastName: string) {\n return this.createQueryBuilder(\"user\")\n .where(\"user.firstName = :firstName\", { firstName })\n .andWhere(\"user.lastName = :lastName\", { lastName })\n .getMany()\n },\n })\n```\n\n```text\n@EntityRepository\n```\n\n```text\nmanager\n```\n\n```text\ndataSource\n```\n\n```text\n@EntityRepository\n```\n\n```text\nsomeRepo.extend({})\n```\n\n```js\nimport { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class UserEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n firstName: string;\n\n @Column()\n lastName: string;\n\n @Column({ default: true })\n isActive: boolean;\n}\n```\n\n```js\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\nimport { UserEntity } from './user.entity';\n\nexport class UserRepository extends Repository<UserEntity> {\n constructor(\n @InjectRepository(UserEntity)\n private userRepository: Repository<UserEntity>\n ) {\n super(userRepository.target, userRepository.manager, userRepository.queryRunner);\n }\n\n // sample method for demo purposes\n async findByEmail(email: string): Promise<UserEntity> {\n return await this.userRepository.findOneBy({ email }); // could also be this.findOneBy({ email });, but depending on your IDE/TS settings, could warn that userRepository is not used though. Up to you to use either of the 2 methods\n }\n \n // your other custom methods in your repo...\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { UserRepository } from './user.repository';\nimport { UserEntity } from './user.entity';\n\n@Injectable()\nexport class UserService {\n constructor(\n private readonly userRepository: UserRepository, // import as usual\n ) {}\n\n findAll(): Promise<UserEntity[]> {\n return this.userRepository.find();\n }\n \n // call your repo method\n findOneByEmail(email: string): Promise<UserEntity> {\n return this.userRepository.findByEmail({ email });\n }\n\n findOne(id: number): Promise<UserEntity> {\n return this.userRepository.findOneBy({ id });\n }\n\n async remove(id: string): Promise<void> {\n await this.userRepository.delete(id);\n }\n \n // your other custom methods in your service...\n}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UserService } from './user.service';\nimport { UserController } from './user.controller';\nimport { UserEntity } from './user.entity';\n\n@Module({\n imports: [TypeOrmModule.forFeature([UserEntity])], // here we provide the TypeOrm support as usual, specifically for our UserEntity in this case\n providers: [UserService, UserRepository], // here we provide our custom repo\n controllers: [UserController],\n exports: [UserService, UserRepository] // add this only if you use service and/or custom repo within another module/service\n})\nexport class UserModule {}\n```\n\n```text\nUserEntity\n```\n\n```text\nUserRepository\n```\n\n```text\nUserService\n```\n\n```text\nUserRepository\n```\n\n```text\nUserService\n```\n\n```text\nUserModule\n```\n\n```text\nUserRepository\n```\n\n```text\nUserEntity\n```\n\n```text\nUserModule\n```\n\n```text\nUserModule\n```\n\n```text\nAppModule\n```\n\n```text\nUserRepository\n```\n\n```text\nUserService\n```\n\n```text\nmanager\n```\n\n```text\nqueryRunnner\n```\n\n```text\nUserRepository\n```\n\n```text\nUserModule\n```\n\n```text\nUserRepository\n```\n\n```text\nimport { Column, Entity, JoinColumn, ManyToOne, OneToMany } from \"typeorm\";\nimport { CustomBaseEntity } from \"../core/custom-base.entity\";//custom-made\n@Entity({name: 'rcon_log', schema: 'dbo'})\nexport class LogEntity extends CustomBaseEntity{\n------------your code-----------\n}\n```\n\n========================================\n\nComments:\n- I tried this solution and I get the error Error: Nest can't resolve dependencies of the CustomerRepository (?). Please make sure that the argument CustomerEntityRepository at index [0] is available in the CustomerModule context. Potential solutions: - Is CustomerModule a valid NestJS module? - If CustomerEntityRepository is a provider, is it part of the current CustomerModule? - If CustomerEntityRepository is exported from a separate @Module, is that module imported within CustomerModule? @Module({ imports: [ /* the Module containing CustomerEntityRepository */ ] })\n- Please provide more context to the comments, maybe a link to some repo in order to better understand your code :) Otherwise your error tells it all, you're missing something, somewhere =)\n- Pretty good solution for global repositories, but you cannot use this custom repository in a transaction. It would be nice to have an alternative for the old `entityManager.getCustomRepository(Foo)`.\n- Make sure *not* to use `@InjectRepository(UserEntity)` when you are creating the Repository class yourself.","metadata":{"transformedAt":"2026-08-18T18:33:44.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":278,"estimatedTokens":1798}}158{"id":"stack-60777204","source":"stackoverflow","questionId":60777204,"title":"TypeError: Repository method is not a function (NestJS / TypeORM)","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: TypeError: Repository method is not a function (NestJS / TypeORM)\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm working with NestJS and TypeORM. When trying to call the createMailLogEntry method of the repository, I'm getting the following error: `TypeError: this.mailLogEntryRepository.createMailLogEntry is not a function`\n\nI can't figure out what's going wrong.\n\n**mailing.service.ts**\n\n```\n@Injectable()\nexport class MailingService {\n\n constructor(@InjectRepository(MailLogEntryRepository) private mailLogEntryRepository: MailLogEntryRepository) { }\n\n // ...\n\n if(transferResult) {\n await this.mailLogEntryRepository.createMailLogEntry({\n creationDate: new Date(Date.now()),\n from: mailContent.from,\n to: mailContent.to,\n subject: mailContent.subject,\n text: mailContent.text,\n html: mailContent.html,\n cc: mailContent.cc,\n bcc: mailContent.bcc,\n });\n }\n }\n}\n```\n\n**mail-log-entry.repository.ts**\n\n```\n@EntityRepository(MailLogEntry)\nexport class MailLogEntryRepository extends Repository {\n\n async createMailLogEntry(mailLogEntryDto: MailLogEntryDto): Promise {\n const mailLogEntry = MailLogEntryRepository.createMailLogEntryFromDto(mailLogEntryDto);\n return await mailLogEntry.save();\n }\n\n private static createMailLogEntryFromDto(mailLogEntryDto: MailLogEntryDto): MailLogEntry {\n const mailLogEntry = new MailLogEntry();\n mailLogEntry.from = mailLogEntryDto.from;\n mailLogEntry.to = mailLogEntryDto.to;\n mailLogEntry.subject = mailLogEntryDto.subject;\n mailLogEntry.text = mailLogEntryDto.text;\n mailLogEntry.html = mailLogEntryDto.html;\n mailLogEntry.cc = mailLogEntryDto.cc;\n mailLogEntry.bcc = mailLogEntryDto.bcc;\n\n return mailLogEntry;\n }\n}\n```\n\n========================================\n\nTop Answer:\nI had the same problem, I'll tell you what got me out of it if it helps someone else!\n\nIf your repository is handmade (not generated by an ORM) then you can't use the Repository injection :\n\nhttps://i.sstatic.net/klir6.png\n\nInstead just use the repository as you would for a service (just remove the @InjectRepository(People)):\n\nhttps://i.sstatic.net/duDXN.png\n\nI hope this will help!Happy coding !\n\nPS : Personnes is my entity and the helper has nothing to do with the issue\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class MailingService {\n\n constructor(@InjectRepository(MailLogEntryRepository) private mailLogEntryRepository: MailLogEntryRepository) { }\n\n // ...\n\n if(transferResult) {\n await this.mailLogEntryRepository.createMailLogEntry({\n creationDate: new Date(Date.now()),\n from: mailContent.from,\n to: mailContent.to,\n subject: mailContent.subject,\n text: mailContent.text,\n html: mailContent.html,\n cc: mailContent.cc,\n bcc: mailContent.bcc,\n });\n }\n }\n}\n```\n\n```text\n@EntityRepository(MailLogEntry)\nexport class MailLogEntryRepository extends Repository<MailLogEntry> {\n\n async createMailLogEntry(mailLogEntryDto: MailLogEntryDto): Promise<MailLogEntry> {\n const mailLogEntry = MailLogEntryRepository.createMailLogEntryFromDto(mailLogEntryDto);\n return await mailLogEntry.save();\n }\n\n private static createMailLogEntryFromDto(mailLogEntryDto: MailLogEntryDto): MailLogEntry {\n const mailLogEntry = new MailLogEntry();\n mailLogEntry.from = mailLogEntryDto.from;\n mailLogEntry.to = mailLogEntryDto.to;\n mailLogEntry.subject = mailLogEntryDto.subject;\n mailLogEntry.text = mailLogEntryDto.text;\n mailLogEntry.html = mailLogEntryDto.html;\n mailLogEntry.cc = mailLogEntryDto.cc;\n mailLogEntry.bcc = mailLogEntryDto.bcc;\n\n return mailLogEntry;\n }\n}\n```\n\n```text\nTypeError: this.mailLogEntryRepository.createMailLogEntry is not a function\n```\n\n```text\n@Module({\n imports: [TypeOrmModule.forFeature([TeamRepository])],\n providers: [TeamService],\n controllers: [TeamController]\n})\nexport class TeamModule {}\n```\n\n```text\n@Entity\nexport class Person { ... }\n\n@Injectable()\nexport class OtherPersonService { ... } // Person !== OtherPerson\n\n@EntityRepository(Person)\nexport class OtherPersonRepository extends Repository<Person> { ... } // Same problem\n```\n\n```text\n@Module({\n imports: [TypeOrmModule.forFeature([\n TeamRepository,\n Team // either the entity or the custom repository should be imported.\n ])],\n providers: [TeamService],\n controllers: [TeamController]\n})\nexport class TeamModule {}\n```\n\n```text\n@Injectable()\nexport class ProductService {\n private logger = new Logger('ProductService');\n constructor(\n @InjectRepository(Product)\n private productRepository: Repository<Product>\n ) { }\n\n async getAllAsync(): Promise<Product[]> {\n return await this.productRepository.find();\n }\n\n async getCountAsync(): Promise<number> {\n return await this.productRepository.count();\n }\n}\n```\n\n```text\nconst mockUserRepository = {\n register: jest.fn().mockResolvedValue('sampleResolvedValue')\n};\n```\n\n```js\nexampleQueryBuilder() {\n return this.createQueryBuilder() ...\n}\n```\n\n```js\nexampleQueryBuilder() {\n return this.dataSource\n .getRepository(Person)\n .createQueryBuilder() ...\n}\n```\n\n```js\n// account.repository.ts\n@Injectable()\nexport class AccountsRepository extends Repository<AccountsEntity> {\n constructor(private dataSource: DataSource) {\n super(AccountsEntity, dataSource.createEntityManager());\n }\n\n async getByUsername(username: string) {\n return this.findOne({ where: { username } });\n }\n // ...\n}\n```\n\n```js\n// account.service.ts\nexport class AccountService {\n constructor(private readonly accountRepository: AccountRepository) {}\n\n async getByUsername(username: string): Promise<Account> {\n return this.accountRepository.getByUsername(username);\n }\n // ...\n}\n```\n\n```js\n// account.module.ts\n@Module({\n imports: [\n TypeOrmModule.forFeature([AccountEntity])],\n // ...\n ],\n providers: [AccountService, AccountRepository],\n // ...\n})\nexport class AccountModule { }\n```\n\n```text\n@Module({\n imports: [\n TypeOrmModule.forFeature([\n YourEntity\n ])\n ],\n controllers: [],\n providers: [YourRepository],\n exports: [],\n})\n```\n\n```text\nTypeOrmModule.forFeature\n```\n\n```text\n@Injectable()\nexport class TaskRepository extends Repository<Task> {\n constructor(private readonly dataSource: DataSource) {\n super(Task, dataSource.manager);\n }\n getTasks(filterDto: GetTasksFilterDto): Promise<Task[]> {}\n```\n\n```text\n@Injectable()\nexport class TasksService {\n\n constructor (\n @InjectRepository(Task)\n private taskRepository: TaskRepository\n ) {}\n```\n\n```text\n@Module({\n controllers: [TasksController],\n providers: [TasksService, TaskRepository],\n imports: [TypeOrmModule.forFeature([Task ])]\n})\nexport class TasksModule {}\n```\n\n========================================\n\nComments:\n- Probably you have some problem how you provide this custom repository and your mailing service gets undefined in place of mailLogEntryRepository\n- @Noniq, I'm currently having this same issue and none of these answers are fixing it for me. I don't know if you ever got yours fixed or if anyone has a fix for this. It's exactly the same issue saying **TypeError: this.userRepository.register is not a function**\n- @MSadiq Have you solved it?\n- Yes, I just added what fixed it for me to the answers, hopefully it helps someone someday\n- This should be an accepted answer. The custom extended repository you make has to be imported via Typeorm like in the answer.\n- Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?","metadata":{"transformedAt":"2026-08-18T18:33:44.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":298,"estimatedTokens":2021}}159{"id":"stack-51113506","source":"stackoverflow","questionId":51113506,"title":"NodeJS map Dtos to TypeORM Entities","tags":["node.js","dto","nestjs","typeorm","class-transformer"],"text":"Title: NodeJS map Dtos to TypeORM Entities\nTags: node.js, dto, nestjs, typeorm, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI have a `nodejs` REST API backend running the `nestjs` framework, using **typeORM** as **ORM** for my entities.\n\nComing from a `C#/Entity Framework` background, I am very used to have my Dtos mapped to the database entities.\n\nIs there a similar approach with typeORM? \n\nI have seen the automapper-ts library, but those magic strings in the map declarations look kind of scary...\nBasically it would be amazing if I could :\n\n```\nlet user: TypeORMUserEntity = mapper.map(userDto);\n```\n\nWhat is the way to do this (or any alternative with same result) in nodejs/typeorm backend environment?\n\n========================================\n\nTop Answer:\nI am using `create` method from `getRepository`\n\n```\nexport async function save(booking: CreateBookingDto) {\n const bookingRepository = getRepository(Booking);\n\n const bookingEntity = bookingRepository.create({ ...booking });\n return bookingRepository.save(bookingEntity);\n}\n```\n\n========================================\n\nCode:\n```text\nlet user: TypeORMUserEntity = mapper.map<TypeORMUserEntity>(userDto);\n```\n\n```text\nnodejs\n```\n\n```text\nnestjs\n```\n\n```text\nC#/Entity Framework\n```\n\n```text\n@Exclude()\nclass SkillNewDto {\n @Expose()\n @ApiModelProperty({ required: true })\n @IsString()\n @MaxLength(60)\n name: string;\n\n @Expose()\n @ApiModelProperty({\n required: true,\n type: Number,\n isArray: true,\n })\n @IsArray()\n @IsInt({ each: true })\n @IsOptional()\n categories: number[];\n}\n```\n\n```text\nconst skillDto = plainToClass(SkillNewDto, body);\nconst errors = await validate(skillDto);\nif (errors.length) {\n throw new BadRequestException('Invalid skill', this.modelHelper.modelErrorsToReadable(errors));\n}\n```\n\n```text\nExclude\n```\n\n```text\nExpose\n```\n\n```text\nclass-transform\n```\n\n```text\nIsString\n```\n\n```text\nIsArray\n```\n\n```text\nIsOptional\n```\n\n```text\nIsInt\n```\n\n```text\nMaxLength\n```\n\n```text\nclass-validator\n```\n\n```text\nApiModelProperty\n```\n\n```text\nexport async function save(booking: CreateBookingDto) {\n const bookingRepository = getRepository(Booking);\n\n const bookingEntity = bookingRepository.create({ ...booking });\n return bookingRepository.save(bookingEntity);\n}\n```\n\n```text\ncreate\n```\n\n```text\ngetRepository\n```\n\n```text\nclass LoginResDto {\n token?: string;\n\n addCustomProperty = (propertyName: AllowedKeys, propertyValue: any): this => {\n this[propertyName] = propertyValue;\n return this;\n };\n\n @Expose()\n type: UserType;\n\n @Expose()\n name: string;\n\n @Expose()\n surname: string;\n\n @Expose()\n publicId: number;\n\n @Expose({\n name: 'I',\n })\n @Type(() => HumanResDto)\n detail: HumanResDto;\n}\n\nexport default LoginResDto;\n```\n\n```text\nconst convertData = TransformService.convert<LoginResDto, UserEntity>(\n userExist,\n LoginResDto,\n 'excludeAll'\n ).addCustomProperty('token', tokenInstance.clientToken);\n```\n\n```text\nclass TransformService {\n static convert<T, K>(\n source: K,\n destinationClass: ClassConstructor<T>,\n strategy: 'excludeAll' | 'exposeAll'\n ): T {\n return plainToClass(destinationClass, source, { strategy });\n }\n\n static convertArray<T, K>(\n source: K[],\n destinationClass: ClassConstructor<T>,\n strategy: 'excludeAll' | 'exposeAll'\n ): T[] {\n return plainToInstance(destinationClass, source, { strategy });\n }\n}\n\nexport default TransformService;\n```\n\n========================================\n\nComments:\n- Isn't this a DTO -> DTO instead of a DTO -> Enity mapping ? `typescript const skillDto = plainToClass(SkillNewDto, body);`","metadata":{"transformedAt":"2026-08-18T18:33:44.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":205,"estimatedTokens":907}}160{"id":"stack-59812344","source":"stackoverflow","questionId":59812344,"title":"Expect orWhere() to works with andWhere() instead where()","tags":["query-builder","typeorm"],"text":"Title: Expect orWhere() to works with andWhere() instead where()\nTags: query-builder, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a query:\n\n```\ntopics = await topicRepository.createQueryBuilder('topic')\n .leftJoinAndSelect('topic.user', 'user', 'topic.userId = user.id')\n .where('topic.categoryId = :id', {\n id: categoryId,\n })\n .andWhere('topic.title like :search', { search: `%${searchKey}%`})\n // It should take the first where\n .orWhere('user.pseudo like :search', { search: `%${searchKey}%` })\n .addOrderBy(filter === 'latest' ? 'topic.created_at' : 'topic.repliesCount', 'DESC')\n .take(limit)\n .skip(skip)\n .getMany();\n```\n\nGenerated SQL query is:\n\n SELECT DISTINCT `distinctAlias`.`topic_id` as \\\"ids_topic_id\\\", `distinctAlias`.`topic_created_at` FROM (SELECT `topic`.`id` AS `topic_id`, `topic`.`title` AS `topic_title`, `topic`.`content` AS `topic_content`, `topic`.`created_at` AS `topic_created_at`, `topic`.`views` AS `topic_views`, `topic`.`repliesCount` AS `topic_repliesCount`, `topic`.`categoryId` AS `topic_categoryId`, `topic`.`userId` AS `topic_userId`, `topic`.`surveyId` AS `topic_surveyId`, `user`.`id` AS `user_id`, `user`.`email` AS `user_email`, `user`.`pseudo` AS `user_pseudo`, `user`.`password` AS `user_password`, `user`.`rank` AS `user_rank`, `user`.`avatar` AS `user_avatar`, `user`.`createdAt` AS `user_createdAt`, `user`.`lastActivity` AS `user_lastActivity`, `user`.`signature` AS `user_signature`, `user`.`post_count` AS `user_post_count`, `user`.`updatedAt` AS `user_updatedAt` FROM `topic` `topic` LEFT JOIN `user` `user` ON `user`.`id`=`topic`.`userId` AND (topic.userId = `user`.`id`) WHERE topic.categoryId = '5' AND `topic`.`title` like '%admin%' OR topic.user.pseudo like '%admin%') `distinctAlias` ORDER BY `distinctAlias`.`topic_created_at` DESC, `topic_id` ASC LIMIT 20\n\nThe problem is here:\n\n WHERE topic.categoryId = '5' AND topic.title like '%admin%' OR topic.user.pseudo like '%admin%')\n\nI expected :\n\n WHERE (topic.categoryId = '5' AND topic.title like '%admin%') OR (topic.categoryId = '5' AND topic.user.pseudo like '%admin%')\n\nI want the **.orWhere** being OR from **.andWhere** instead **.where**\n\nI don't find any documentation / issue about this use case.\n\n========================================\n\nCode:\n```text\ntopics = await topicRepository.createQueryBuilder('topic')\n .leftJoinAndSelect('topic.user', 'user', 'topic.userId = user.id')\n .where('topic.categoryId = :id', {\n id: categoryId,\n })\n .andWhere('topic.title like :search', { search: `%${searchKey}%`})\n // It should take the first where\n .orWhere('user.pseudo like :search', { search: `%${searchKey}%` })\n .addOrderBy(filter === 'latest' ? 'topic.created_at' : 'topic.repliesCount', 'DESC')\n .take(limit)\n .skip(skip)\n .getMany();\n```\n\n```text\ndistinctAlias\n```\n\n```text\ntopic_id\n```\n\n```text\ndistinctAlias\n```\n\n```text\ntopic_created_at\n```\n\n```text\ntopic\n```\n\n```text\nid\n```\n\n```text\ntopic_id\n```\n\n```text\ntopic\n```\n\n```text\ntitle\n```\n\n```text\ntopic_title\n```\n\n```text\ntopic\n```\n\n```text\ncontent\n```\n\n```text\ntopic_content\n```\n\n```text\ntopic\n```\n\n```text\ncreated_at\n```\n\n```text\ntopic_created_at\n```\n\n```text\ntopic\n```\n\n```text\nviews\n```\n\n```text\ntopic_views\n```\n\n```text\ntopic\n```\n\n```text\nrepliesCount\n```\n\n```text\ntopic_repliesCount\n```\n\n```text\ntopic\n```\n\n```text\ncategoryId\n```\n\n```text\ntopic_categoryId\n```\n\n```text\ntopic\n```\n\n```text\nuserId\n```\n\n```text\ntopic_userId\n```\n\n```text\ntopic\n```\n\n```text\nsurveyId\n```\n\n```text\ntopic_surveyId\n```\n\n```text\nuser\n```\n\n```text\nid\n```\n\n```text\nuser_id\n```\n\n```text\nuser\n```\n\n```text\nemail\n```\n\n```text\nuser_email\n```\n\n```text\nuser\n```\n\n```text\npseudo\n```\n\n```text\nuser_pseudo\n```\n\n```text\nuser\n```\n\n```text\npassword\n```\n\n```text\nuser_password\n```\n\n```text\nuser\n```\n\n```text\nrank\n```\n\n```text\nuser_rank\n```\n\n```text\nuser\n```\n\n```text\navatar\n```\n\n```text\nuser_avatar\n```\n\n```text\nuser\n```\n\n```text\ncreatedAt\n```\n\n```text\nuser_createdAt\n```\n\n```text\nuser\n```\n\n```text\nlastActivity\n```\n\n```text\nuser_lastActivity\n```\n\n```text\nuser\n```\n\n```text\nsignature\n```\n\n```text\nuser_signature\n```\n\n```text\nuser\n```\n\n```text\npost_count\n```\n\n```text\nuser_post_count\n```\n\n```text\nuser\n```\n\n```text\nupdatedAt\n```\n\n```text\nuser_updatedAt\n```\n\n```text\ntopic\n```\n\n```text\ntopic\n```\n\n```text\nuser\n```\n\n```text\nuser\n```\n\n```text\nuser\n```\n\n```text\nid\n```\n\n```text\ntopic\n```\n\n```text\nuserId\n```\n\n```text\nuser\n```\n\n```text\nid\n```\n\n```text\ntopic\n```\n\n```text\ntitle\n```\n\n```text\ndistinctAlias\n```\n\n```text\ndistinctAlias\n```\n\n```text\ntopic_created_at\n```\n\n```text\ntopic_id\n```\n\n```ts\ntopics = await topicRepository.createQueryBuilder('topic')\n .leftJoinAndSelect('topic.user', 'user', 'topic.userId = user.id')\n .where('topic.categoryId = :id', {\n id: categoryId,\n })\n .andWhere(new Brackets(qb => {\n qb.where('topic.title like :search', { search: `%${searchKey}%`})\n .orWhere('user.pseudo like :search', { search: `%${searchKey}%` }); \n }))\n .addOrderBy(filter === 'latest' ? 'topic.created_at' : 'topic.repliesCount', 'DESC')\n .take(limit)\n .skip(skip)\n .getMany();\n```\n\n========================================\n\nComments:\n- Logical expression `(A and B) or (A and C)` can be simplified down to `A and (B or C)`, similar to how `xy + xz` is the same as `x(y + z)`\n- Edit: I found the fix, I edited ur post please accept the edit ;) Ty Brackets was the solution, weird I never found something about it :(\n- The brackets are only mentioned in passing. Glad I could help.","metadata":{"transformedAt":"2026-08-18T18:33:44.696Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":82,"totalLines":398,"estimatedTokens":1458}}161{"id":"stack-52814795","source":"stackoverflow","questionId":52814795,"title":"How to query with 'OR' Operation in where object using find-options API in TypeORM","tags":["typeorm"],"text":"Title: How to query with 'OR' Operation in where object using find-options API in TypeORM\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI want find results in my repo where firstname is like 'john' **OR** lastname is like 'doe'\nbut findOptions where clause treat it as AND.\n\nWhat I tried :\n\n```\nlet results = await userRepo.find({\n where : {\n firstname : Like('%John%'),\n lastname : Like('%Doe%'),\n }\n});\n```\n\nWhat I expect of this :\n\n```\nlet results = await userRepo.find({\n where : {\n firstname : Like('%John%'),\n lastname : Or(Like('%Doe%')),\n }\n});\n```\n\nAny help on how can I use **OR** within where object?\n\n========================================\n\nTop Answer:\n```\nconst userRepository = getRepository(User);\n/* return userRepository.find({\n email: ILike(\"%\" + body.search + \"%\")\n}); */\n\nreturn userRepository.find({\n where : [{\n email : ILike(\"%\"+body.search+\"%\"),\n }, {\n fullName : ILike(\"%\"+body.search+\"%\"),\n }]\n});\n```\n\nIn my case working fine.\n\n========================================\n\nCode:\n```text\nlet results = await userRepo.find({\n where : {\n firstname : Like('%John%'),\n lastname : Like('%Doe%'),\n }\n});\n```\n\n```text\nlet results = await userRepo.find({\n where : {\n firstname : Like('%John%'),\n lastname : Or(Like('%Doe%')),\n }\n});\n```\n\n```text\nlet results = await userRepo.find({\n where: [\n { firstname: Like('%John%') },\n { lastname: Like('%Doe%') }\n ]\n });\n```\n\n```text\nlet results = await userRepo\n .createQueryBuilder()\n .select()\n .where(\"firstname LIKE %:first%\", { first: John })\n .orWhere(\"lastname LIKE %:last%\", { last: Doe });\n```\n\n```text\n.find()\n```\n\n```text\nlet results = await userRepo.find({\n where : `firstname LIKE '%john%' OR lastname LIKE '%doe%'`\n})\n```\n\n```text\nconst query.where = await getRepository(abc)\n .createQueryBuilder(\"abc\")\n .select(); \n await query.where(\"abc.Name ILIKE :Name\", {\n Name: `%${searchTerm}%`,\n }).orWhere(\"abc.description ILIKE :description\", {\n description: `%${searchTerm}%`,\n });`\n```\n\n```text\nconst userRepository = getRepository(User);\n/* return userRepository.find({\n email: ILike(\"%\" + body.search + \"%\")\n}); */\n\nreturn userRepository.find({\n where : [{\n email : ILike(\"%\"+body.search+\"%\"),\n }, {\n fullName : ILike(\"%\"+body.search+\"%\"),\n }]\n});\n```\n\n========================================\n\nComments:\n- Did you mean \"findOptions where clause treat it as AND\"?\n- yes thanks, I edited it accordingly.\n- Thanks, I found that we can put where query in find-options as a string. I'm sticking to that. Thanks a lot though! :)\n- This won't use the column aliases of your entity, so you'll have to transform them manually. Also it's prone to SQL Injection.\n- @EricJeker It was the only option at that point in the API. The new updates were rolled out later.\n- Yeah. I get it. It was published way after time my question was published. Thanks anyways. Here's the reference commit : github.com/typeorm/typeorm/commit/…\n- there are other conditions as well that should work with and operatoe","metadata":{"transformedAt":"2026-08-18T18:33:44.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":136,"estimatedTokens":766}}162{"id":"stack-51313852","source":"stackoverflow","questionId":51313852,"title":"Docker Compose cannot connect to database","tags":["docker","docker-compose","typeorm","nestjs"],"text":"Title: Docker Compose cannot connect to database\nTags: docker, docker-compose, typeorm, nestjs\nSource: Stack Overflow\n\nQuestion:\nI'm using nestjs for my backend and using typeorm as ORM.\nI tried to define my database and my application in an docker-compose file. \n\nIf I'm running my database as a container and my application from my local machine it works well. My program connects and creates the tables etc.\n\nBut if I try to connect the database from within my container or to start the container with docker-compose up it fails.\n\nAlways get an ECONNREFUSED Error.\n\nWhere is my mistake ?\n\ndocker-compose.yml\n\n```\nversion: '3.1'\nvolumes:\n dbdata:\n\nservices:\n db:\n image: postgres:10\n volumes:\n - ./dbData/:/var/lib/postgresql/data\n restart: always\n environment:\n - POSTGRES_PASSWORD=${TYPEORM_PASSWORD}\n - POSTGRES_USER=${TYPEORM_USERNAME}\n - POSTGRES_DB=${TYPEORM_DATABASE}\n ports:\n - ${TYPEORM_PORT}:5432\n\n backend:\n build: .\n ports:\n - \"3001:3000\"\n command: npm run start\n volumes:\n - .:/src\n```\n\nDockerfile\n\n```\nFROM node:10.5\n\nWORKDIR /home\n\n# Bundle app source\nCOPY . /home\n\n# Install app dependencies\n#RUN npm install -g nodemon\n# If you are building your code for production\n# RUN npm install --only=production\nRUN npm i -g @nestjs/cli\nRUN npm install\n\nEXPOSE 3000\n```\n\n.env\n\n```\n# .env\nHOST=localhost\nPORT=3000\nNODE_ENV=development\nLOG_LEVEL=debug\n\nTYPEORM_CONNECTION=postgres\nTYPEORM_HOST=localhost\nTYPEORM_USERNAME=postgres\nTYPEORM_PASSWORD=postgres\nTYPEORM_DATABASE=mariokart\nTYPEORM_PORT=5432\nTYPEORM_SYNCHRONIZE=true\nTYPEORM_DROP_SCHEMA=true\nTYPEORM_LOGGING=all\nTYPEORM_ENTITIES=src/database/entity/*.ts\nTYPEORM_MIGRATIONS=src/database/migrations/**/*.ts\nTYPEORM_SUBSCRIBERS=src/database/subscribers/**/*.ts\n```\n\nI tried to use links but it don't work in the container.\n\n========================================\n\nTop Answer:\nYou can create a network and among two services.\n\nCreate network for db and backend services:\n\n```\nnetworks:\n common-net: {}\n```\n\nand add the network to these two services. So your .yml file would like below after edit:\n\n```\nversion: '3.1'\nvolumes:\n dbdata:\n\nservices:\n db:\n image: postgres:10\n volumes:\n - ./dbData/:/var/lib/postgresql/data\n restart: always\n environment:\n - POSTGRES_PASSWORD=${TYPEORM_PASSWORD}\n - POSTGRES_USER=${TYPEORM_USERNAME}\n - POSTGRES_DB=${TYPEORM_DATABASE}\n ports:\n - ${TYPEORM_PORT}:5432\n networks:\n - common-net\n\n backend:\n build: .\n ports:\n - \"3001:3000\"\n command: npm run start\n volumes:\n - .:/src\n networks:\n - common-net\n\nnetworks:\n common-net: {}\n```\n\n### Note1: After this change, there is no need to expose the Postgres port externally unless you have a reason for it. You can remove that section.\n\n### Note2: TYPEORM_HOST should be renamed to db. Docker would resolve the IP address of db service by itself.\n\n========================================\n\nCode:\n```text\nversion: '3.1'\nvolumes:\n dbdata:\n\nservices:\n db:\n image: postgres:10\n volumes:\n - ./dbData/:/var/lib/postgresql/data\n restart: always\n environment:\n - POSTGRES_PASSWORD=${TYPEORM_PASSWORD}\n - POSTGRES_USER=${TYPEORM_USERNAME}\n - POSTGRES_DB=${TYPEORM_DATABASE}\n ports:\n - ${TYPEORM_PORT}:5432\n\n backend:\n build: .\n ports:\n - \"3001:3000\"\n command: npm run start\n volumes:\n - .:/src\n```\n\n```text\nFROM node:10.5\n\nWORKDIR /home\n\n# Bundle app source\nCOPY . /home\n\n# Install app dependencies\n#RUN npm install -g nodemon\n# If you are building your code for production\n# RUN npm install --only=production\nRUN npm i -g @nestjs/cli\nRUN npm install\n\nEXPOSE 3000\n```\n\n```text\n# .env\nHOST=localhost\nPORT=3000\nNODE_ENV=development\nLOG_LEVEL=debug\n\nTYPEORM_CONNECTION=postgres\nTYPEORM_HOST=localhost\nTYPEORM_USERNAME=postgres\nTYPEORM_PASSWORD=postgres\nTYPEORM_DATABASE=mariokart\nTYPEORM_PORT=5432\nTYPEORM_SYNCHRONIZE=true\nTYPEORM_DROP_SCHEMA=true\nTYPEORM_LOGGING=all\nTYPEORM_ENTITIES=src/database/entity/*.ts\nTYPEORM_MIGRATIONS=src/database/migrations/**/*.ts\nTYPEORM_SUBSCRIBERS=src/database/subscribers/**/*.ts\n```\n\n```text\n192.0.18.1 dir_db_1\n```\n\n```text\nservices:\n db:\n container_name: project_db\n ...\n backend:\n container_name: project_backend\n```\n\n```text\n/etc/hosts\n```\n\n```text\nbackend\n```\n\n```text\ndir\n```\n\n```text\nTYPEORM_HOST=localhost\n```\n\n```text\nTYPEORM_HOST=dir_db_1\n```\n\n```text\nTYPEORM_HOST=project_db\n```\n\n```text\nnetworks:\n common-net: {}\n```\n\n```text\nversion: '3.1'\nvolumes:\n dbdata:\n\nservices:\n db:\n image: postgres:10\n volumes:\n - ./dbData/:/var/lib/postgresql/data\n restart: always\n environment:\n - POSTGRES_PASSWORD=${TYPEORM_PASSWORD}\n - POSTGRES_USER=${TYPEORM_USERNAME}\n - POSTGRES_DB=${TYPEORM_DATABASE}\n ports:\n - ${TYPEORM_PORT}:5432\n networks:\n - common-net\n\n backend:\n build: .\n ports:\n - \"3001:3000\"\n command: npm run start\n volumes:\n - .:/src\n networks:\n - common-net\n\n\nnetworks:\n common-net: {}\n```\n\n```text\nversion: '0.0.1'\nservices:\n postgresdb:\n container_name: postgresdb\n image: postgres:14\n restart: always\n environment:\n - POSTGRES_PASSWORD=mysecretpassword\n - POSTGRES_DB=dummy_db\n - POSTGRES_USER=postgres\n web:\n image: server01:tag01\n ports:\n - 3000:3000\n environment:\n - POSTGRES_HOST=postgresdb\n```\n\n========================================\n\nComments:\n- doesn't docker compose create a common network for the containers by default ?\n- Yes! You're right. Changing the typeorm_hostname will solve the issue.","metadata":{"transformedAt":"2026-08-18T18:33:44.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":312,"estimatedTokens":1373}}163{"id":"stack-54668910","source":"stackoverflow","questionId":54668910,"title":"alias was not found. Maybe you forget to join it","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: alias was not found. Maybe you forget to join it\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn my nectjs project I'm using TypeORM and I have 2 entities user and post,\nand I'm tying to make a relation between them\n\n### user.entity.ts\n\n```\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ length: 50, unique: true })\n name: string;\n\n @OneToMany(type => Post, post => post.user)\n posts: Post[];\n}\n```\n\n### post.entity.ts\n\n```\n@Entity()\nexport class Post {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ length: 30 })\n title: string;\n\n @ManyToOne(type => User, user => user.posts)\n user: User;\n}\n```\n\nSo I want to join these tables and get post by it's title for specific user\n\n```\nconst PostObject = await createQueryBuilder(\"post\")\n .leftJoinAndSelect(\n \"post.user\",\n \"user\",\n \"post.title = :title\",\n { title: \"title1\" }\n )\n .where(\"user.id = :id\", { id: id })\n .getOne();\n```\n\nbut when I run the project and execute this function I get this error:\n\n```\nError: \"post\" alias was not found. Maybe you forget to join it?\n```\n\n========================================\n\nTop Answer:\nCan also use getRepository like below.\n\n```\nconst PostObject = await getRepository(\"post\").createQueryBuilder(\"post\")\n .leftJoinAndSelect(\n \"post.user\",\n \"user\",\n \"post.title = :title\",\n { title: \"title1\" }\n )\n .where(\"user.id = :id\", { id: id })\n .getOne();\n```\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ length: 50, unique: true })\n name: string;\n\n @OneToMany(type => Post, post => post.user)\n posts: Post[];\n}\n```\n\n```text\n@Entity()\nexport class Post {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ length: 30 })\n title: string;\n\n @ManyToOne(type => User, user => user.posts)\n user: User;\n}\n```\n\n```text\nconst PostObject = await createQueryBuilder(\"post\")\n .leftJoinAndSelect(\n \"post.user\",\n \"user\",\n \"post.title = :title\",\n { title: \"title1\" }\n )\n .where(\"user.id = :id\", { id: id })\n .getOne();\n```\n\n```text\nError: \"post\" alias was not found. Maybe you forget to join it?\n```\n\n```text\nconstructor(\n @InjectRepository(Post) private readonly postRepository: Repository<Post>\n) {\n}\n```\n\n```text\nthis.postRepository.createQueryBuilder('post')\n// ^^^^^^^^^^^^^^^^\n .leftJoinAndSelect(\n 'post.user',\n 'user',\n 'post.title = :title',\n { title: 'title1' },\n )\n .where('user.id = :id', { id })\n .getOne();\n```\n\n```text\nRepository\n```\n\n```text\nQueryBuilder\n```\n\n```text\nPost\n```\n\n```text\nconst PostObject = await getRepository(\"post\").createQueryBuilder(\"post\")\n .leftJoinAndSelect(\n \"post.user\",\n \"user\",\n \"post.title = :title\",\n { title: \"title1\" }\n )\n .where(\"user.id = :id\", { id: id })\n .getOne();\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":167,"estimatedTokens":726}}164{"id":"stack-63016585","source":"stackoverflow","questionId":63016585,"title":"It's possible, create a table without primary key in TypeOrm?","tags":["node.js","typescript","typeorm"],"text":"Title: It's possible, create a table without primary key in TypeOrm?\nTags: node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nAnd still managing to do @OneToMany in another entity.\n\n```\nexport class ProductsOfOrder { \n @ManyToOne(() => Order, order => order.products)\n order: Order\n\n @ManyToOne(() => Product)\n product: Product\n\n @Column({type: 'integer'})\n amount: number\n}\n```\n\nIn the case using the foreign key of order\n\n```\n@Entity()\nexport class Order {\n @PrimaryGeneratedColumn('uuid')\n id: string\n\n @ManyToOne(() => User)\n user: User\n\n @OneToMany(() => ProductsOfOrder, productsOfOrder => productsOfOrder.order, {cascade: true})\n products: ProductsOfOrder[]\n}\n```\n\n========================================\n\nTop Answer:\nAhem, of course, you can create a table without a primary key in TypeORM.\n\nHere's a nice dirty little hack:\n\n- Add a fake primary column to your model and set the insert, select, and update options to false.\n\n```\n@Entity()\nexport class EntityWithoutPK {\n /**\n * ! This is a fake attribute\n * This is a workaround for TypeORM's `MissingPrimaryColumnError`\n **/\n @PrimaryColumn({ type: 'uuid', insert: false, select: false, update: false })\n id: never;\n\n // Other column definitions\n}\n```\n\nGenerate a migration file and then delete the primary column part from the generated SQL\n\nSet synchronize option to false\n\n```\n@Entity({ synchronize: false })\nexport class Order\n```\n\n- Run the migration\n\n**Notes**\n\nBefore applying a hack, see the following checklist. If you have a \"no\" for any one of them, create a primary key.\n\n- You'll only query in groups, i.e. often with where condition with another indexed/FK column\n\n- Individual entity doesn't make sense, you will never call a method (e.g. save) of individual entity\n\n- The primary key takes a considerable amount of space for an individual record (e.g., UUID primary key for simple metrics).\n\n- The entity schema doesn't change often; otherwise, the `synchronize: false` option might cause lots of panic.\n\nFor your case, it makes total sense to create a primary key in the order table.\n\n========================================\n\nCode:\n```text\nexport class ProductsOfOrder { \n @ManyToOne(() => Order, order => order.products)\n order: Order\n\n @ManyToOne(() => Product)\n product: Product\n\n @Column({type: 'integer'})\n amount: number\n}\n```\n\n```text\n@Entity()\nexport class Order {\n @PrimaryGeneratedColumn('uuid')\n id: string\n\n @ManyToOne(() => User)\n user: User\n\n @OneToMany(() => ProductsOfOrder, productsOfOrder => productsOfOrder.order, {cascade: true})\n products: ProductsOfOrder[]\n}\n```\n\n```js\n@Entity()\nexport class EntityWithoutPK {\n /**\n * ! This is a fake attribute\n * This is a workaround for TypeORM's `MissingPrimaryColumnError`\n **/\n @PrimaryColumn({ type: 'uuid', insert: false, select: false, update: false })\n id: never;\n\n // Other column definitions\n}\n```\n\n```js\n@Entity({ synchronize: false })\nexport class Order\n```\n\n```text\nsynchronize: false\n```\n\n========================================\n\nComments:\n- I dont know why, but is still trying to select the column even \"select: false\" I have. typeorm 0.3.17.\n- Same here, did you found solution?","metadata":{"transformedAt":"2026-08-18T18:33:44.696Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":142,"estimatedTokens":797}}165{"id":"stack-60591696","source":"stackoverflow","questionId":60591696,"title":"With TypeORM, `SQLITE_CONSTRAINT: FOREIGN KEY constraint failed` when adding a column to an entity","tags":["javascript","typescript","sqlite","orm","typeorm"],"text":"Title: With TypeORM, `SQLITE_CONSTRAINT: FOREIGN KEY constraint failed` when adding a column to an entity\nTags: javascript, typescript, sqlite, orm, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using TypeORM as a TypeScript ORM library, with a SQLite database.\n\nI've got a TypeORM entity, called `Photo` with a `@OneToOne` relationship with another entity, called `PhotoMetadata`.\n\n`Photo.ts`:\n\n```\nimport {\n Entity,\n Column,\n PrimaryGeneratedColumn,\n OneToOne,\n BaseEntity,\n} from 'typeorm';\n\nimport PhotoMetadata from './PhotoMetadata';\n\n@Entity()\nexport default class Photo extends BaseEntity {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ length: 100 })\n public name: string;\n\n @OneToOne(\n () => PhotoMetadata,\n (photoMetadata) => photoMetadata.photo,\n { cascade: true },\n )\n metadata: PhotoMetadata;\n}\n```\n\nAnd here is `PhotoMetadata.ts`:\n\n```\nimport {\n Entity,\n Column,\n PrimaryGeneratedColumn,\n OneToOne,\n JoinColumn,\n} from 'typeorm';\n\nimport Photo from './Photo';\n\n@Entity()\nexport default class PhotoMetadata {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n comment: string;\n\n @OneToOne(\n () => Photo,\n (photo) => photo.metadata,\n )\n @JoinColumn()\n photo: Photo;\n}\n```\n\nWhen I add a column to `Photo`, like:\n\n```\n@Column({ nullable: true })\n test: string;\n```\n\nThen run the app, with logging enabled, I get:\n\n```\nquery: BEGIN TRANSACTION\nquery: SELECT * FROM \"sqlite_master\" WHERE \"type\" = 'table' AND \"name\" IN ('photo_metadata', 'photo', 'user')\nquery: SELECT * FROM \"sqlite_master\" WHERE \"type\" = 'index' AND \"tbl_name\" IN ('photo_metadata', 'photo', 'user')\nquery: PRAGMA table_info(\"user\")\nquery: PRAGMA index_list(\"user\")\nquery: PRAGMA foreign_key_list(\"user\")\nquery: PRAGMA table_info(\"photo\")\nquery: PRAGMA index_list(\"photo\")\nquery: PRAGMA foreign_key_list(\"photo\")\nquery: PRAGMA table_info(\"photo_metadata\")\nquery: PRAGMA index_list(\"photo_metadata\")\nquery: PRAGMA foreign_key_list(\"photo_metadata\")\nquery: PRAGMA index_info(\"sqlite_autoindex_photo_metadata_1\")\nquery: SELECT * FROM \"sqlite_master\" WHERE \"type\" = 'table' AND \"name\" = 'typeorm_metadata'\nquery: CREATE TABLE \"temporary_photo_metadata\" (\"id\" integer PRIMARY KEY AUTOINCREMENT NOT NULL, \"comment\" varchar NOT NULL, \"photoId\" integer, CONSTRAINT \"UQ_99f01ed52303cc16139d69f7464\" UNIQUE (\"photoId\"), CONSTRAINT \"FK_99f01ed52303cc16139d69f7464\" FOREIGN KEY (\"photoId\") REFERENCES \"photo\" (\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION)\nquery: INSERT INTO \"temporary_photo_metadata\"(\"id\", \"comment\", \"photoId\") SELECT \"id\", \"comment\", \"photoId\" FROM \"photo_metadata\"\nquery: DROP TABLE \"photo_metadata\"\nquery: ALTER TABLE \"temporary_photo_metadata\" RENAME TO \"photo_metadata\"\nquery: CREATE TABLE \"temporary_photo\" (\"id\" integer PRIMARY KEY AUTOINCREMENT NOT NULL, \"name\" varchar(100) NOT NULL)\nquery: INSERT INTO \"temporary_photo\"(\"id\", \"name\") SELECT \"id\", \"name\" FROM \"photo\"\nquery: DROP TABLE \"photo\"\nquery failed: DROP TABLE \"photo\"\nerror: [Error: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed] {\n errno: 19,\n code: 'SQLITE_CONSTRAINT'\n}\nquery: ROLLBACK\n```\n\nHow can I fix this issue? It seems to fail dropping the Photo table that I modified, because of the foreign key.\n\n========================================\n\nTop Answer:\nThe problem may occurs when you already have some data in your database and you add new Entities. I've tried the two solution here but didn't work. But one thing worked for me: just drop the Table before open a new connection (Open an connection, drop table, close connection, open another and do what u and to do).\nExample:\n\n```\ncreateConnection({\ntype: \"sqlite\",\ndatabase: \"datateste.sqlite\",\nentities: [\n User,\n Auditory,\n Goal,\n Supervised,\n Supervisor\n],\nsynchronize: true,\nlogging: false}).then(async (e) => {\nawait e.dropDatabase()\nawait e.close()}).then(() => {\ncreateConnection({\n type: \"sqlite\",\n database: \"datateste.sqlite\",\n entities: [\n User,\n Auditory,\n Goal,\n Supervised,\n Supervisor\n ],\n synchronize: true,\n logging: false\n}).then(async connection => {\n // here you do what you want\n}).catch(error => console.log(error));\n```\n\n})\n\n========================================\n\nCode:\n```text\nimport {\n Entity,\n Column,\n PrimaryGeneratedColumn,\n OneToOne,\n BaseEntity,\n} from 'typeorm';\n\nimport PhotoMetadata from './PhotoMetadata';\n\n@Entity()\nexport default class Photo extends BaseEntity {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ length: 100 })\n public name: string;\n\n @OneToOne(\n () => PhotoMetadata,\n (photoMetadata) => photoMetadata.photo,\n { cascade: true },\n )\n metadata: PhotoMetadata;\n}\n```\n\n```text\nimport {\n Entity,\n Column,\n PrimaryGeneratedColumn,\n OneToOne,\n JoinColumn,\n} from 'typeorm';\n\nimport Photo from './Photo';\n\n@Entity()\nexport default class PhotoMetadata {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n comment: string;\n\n @OneToOne(\n () => Photo,\n (photo) => photo.metadata,\n )\n @JoinColumn()\n photo: Photo;\n}\n```\n\n```text\n@Column({ nullable: true })\n test: string;\n```\n\n```text\nquery: BEGIN TRANSACTION\nquery: SELECT * FROM \"sqlite_master\" WHERE \"type\" = 'table' AND \"name\" IN ('photo_metadata', 'photo', 'user')\nquery: SELECT * FROM \"sqlite_master\" WHERE \"type\" = 'index' AND \"tbl_name\" IN ('photo_metadata', 'photo', 'user')\nquery: PRAGMA table_info(\"user\")\nquery: PRAGMA index_list(\"user\")\nquery: PRAGMA foreign_key_list(\"user\")\nquery: PRAGMA table_info(\"photo\")\nquery: PRAGMA index_list(\"photo\")\nquery: PRAGMA foreign_key_list(\"photo\")\nquery: PRAGMA table_info(\"photo_metadata\")\nquery: PRAGMA index_list(\"photo_metadata\")\nquery: PRAGMA foreign_key_list(\"photo_metadata\")\nquery: PRAGMA index_info(\"sqlite_autoindex_photo_metadata_1\")\nquery: SELECT * FROM \"sqlite_master\" WHERE \"type\" = 'table' AND \"name\" = 'typeorm_metadata'\nquery: CREATE TABLE \"temporary_photo_metadata\" (\"id\" integer PRIMARY KEY AUTOINCREMENT NOT NULL, \"comment\" varchar NOT NULL, \"photoId\" integer, CONSTRAINT \"UQ_99f01ed52303cc16139d69f7464\" UNIQUE (\"photoId\"), CONSTRAINT \"FK_99f01ed52303cc16139d69f7464\" FOREIGN KEY (\"photoId\") REFERENCES \"photo\" (\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION)\nquery: INSERT INTO \"temporary_photo_metadata\"(\"id\", \"comment\", \"photoId\") SELECT \"id\", \"comment\", \"photoId\" FROM \"photo_metadata\"\nquery: DROP TABLE \"photo_metadata\"\nquery: ALTER TABLE \"temporary_photo_metadata\" RENAME TO \"photo_metadata\"\nquery: CREATE TABLE \"temporary_photo\" (\"id\" integer PRIMARY KEY AUTOINCREMENT NOT NULL, \"name\" varchar(100) NOT NULL)\nquery: INSERT INTO \"temporary_photo\"(\"id\", \"name\") SELECT \"id\", \"name\" FROM \"photo\"\nquery: DROP TABLE \"photo\"\nquery failed: DROP TABLE \"photo\"\nerror: [Error: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed] {\n errno: 19,\n code: 'SQLITE_CONSTRAINT'\n}\nquery: ROLLBACK\n```\n\n```text\nPhoto\n```\n\n```text\n@OneToOne\n```\n\n```text\nPhotoMetadata\n```\n\n```text\nPhoto.ts\n```\n\n```text\nPhotoMetadata.ts\n```\n\n```text\nPhoto\n```\n\n```text\nconst connection = await createConnection();\n\nawait connection.query('PRAGMA foreign_keys=OFF');\nawait connection.synchronize();\nawait connection.query('PRAGMA foreign_keys=ON');\n```\n\n```text\nawait connection.query(\"PRAGMA foreign_keys=OFF;\");\nawait connection.runMigrations();\nawait connection.query(\"PRAGMA foreign_keys=ON;\");\n```\n\n```text\nsynchronize: false\n```\n\n```text\normconfig.json\n```\n\n```text\ncreateConnection({\ntype: \"sqlite\",\ndatabase: \"datateste.sqlite\",\nentities: [\n User,\n Auditory,\n Goal,\n Supervised,\n Supervisor\n],\nsynchronize: true,\nlogging: false}).then(async (e) => {\nawait e.dropDatabase()\nawait e.close()}).then(() => {\ncreateConnection({\n type: \"sqlite\",\n database: \"datateste.sqlite\",\n entities: [\n User,\n Auditory,\n Goal,\n Supervised,\n Supervisor\n ],\n synchronize: true,\n logging: false\n}).then(async connection => {\n // here you do what you want\n}).catch(error => console.log(error));\n```\n\n========================================\n\nComments:\n- Where should I put this code if the connection is being auto-generated by nest via `TypeOrmModule.forRootAsync()`","metadata":{"transformedAt":"2026-08-18T18:33:44.697Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":326,"estimatedTokens":2011}}166{"id":"stack-52931663","source":"stackoverflow","questionId":52931663,"title":"How can I specify column name casing in TypeORM migrations","tags":["sql","postgresql","typescript","migration","typeorm"],"text":"Title: How can I specify column name casing in TypeORM migrations\nTags: sql, postgresql, typescript, migration, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using typeORM and I want to use migrations instead of syncing because I'm working in a team and it's actually a lot of tedious work to get the db to a state in which the app actually functions.\n\nThe problem is that every column name I specify in the migration gets converted to lowercase which I've worked around by making all entity props snake_case. But foreign keys get converted to camelCase by (I think) postgres by default so I can't relate anything to each other by foreign key in my migration. (because it needs to be camelCase but the query gets converted to lowercase)\n\nHave i made clear what my problem is?\n\nIs there a way to solve this, or is there a workaround?\n\n========================================\n\nTop Answer:\nIn postgresql, column and table names are automatically converted to lowercase unless you include them in double quotes:\n\n```\ncolumnName becomes columnname\n\"columnName\" remains as columnName\n```\n\nSee https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html -- \"Quoting an identifier also makes it case-sensitive, whereas unquoted names are always folded to lower case.\"\n\nSo you should write migrations as, for example,\n\n```\nALTER TABLE \"tableName\" ADD COLUMN \"columnName\" character varying ...\n```\n\nand queries similarly.\n\n========================================\n\nCode:\n```text\nnpm i --save typeorm-naming-strategies\n```\n\n```text\nconst SnakeNamingStrategy = require('typeorm-naming-strategies')\n .SnakeNamingStrategy;\n\nmodule.exports = {\n name: 'development',\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n ...\n namingStrategy: new SnakeNamingStrategy(),\n}\n```\n\n```text\ncolumnName becomes columnname\n\"columnName\" remains as columnName\n```\n\n```text\nALTER TABLE \"tableName\" ADD COLUMN \"columnName\" character varying ...\n```\n\n========================================\n\nComments:\n- This should be an accepted answer, great!","metadata":{"transformedAt":"2026-08-18T18:33:44.697Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":67,"estimatedTokens":511}}167{"id":"stack-61637468","source":"stackoverflow","questionId":61637468,"title":"How to stub EntityManager and Connection in TypeORM with Jest","tags":["typescript","unit-testing","jestjs","nestjs","typeorm"],"text":"Title: How to stub EntityManager and Connection in TypeORM with Jest\nTags: typescript, unit-testing, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI got an app on NestJS in Typescript using TypeORM and unit-tests written with Jest. I have a function that uses transactions like this:\n\n```\nasync createMany(users: User[]) {\n await this.connection.transaction(async manager => {\n await manager.save(users[0]);\n await manager.save(users[1]);\n });\n}\n```\n\nThat's an example from NestJS docs. I do it roughly in the same way via `this.connection.transaction` but the business-logic is different.\n\nThe thing is I want to make a unit-test to test this service function. So I need to somehow mock both `this.connection` and its `manager`. Or at least the manager. I'm not sure how to do it using Jest. I can't create a manager without a connection. I can't create a mock connection with no manager to return inside it.\n\nUsing both TypeORM and Jest is standard in NestJS. There have to be a way to write unit-tests with transactions. But I am not sure how to do it.\n\nNote that I am asking about unit-test mocking ORM. Not integration tests that would directly use a testing db instance.\n\n========================================\n\nTop Answer:\nI believe you can also:\n\n```\nimport { getConnectionToken } from '@nestjs/typeorm';\n\n{\n provide: getConnectionToken(),\n useClass: Connection,\n},\n```\n\n========================================\n\nCode:\n```js\nasync createMany(users: User[]) {\n await this.connection.transaction(async manager => {\n await manager.save(users[0]);\n await manager.save(users[1]);\n });\n}\n```\n\n```text\nthis.connection.transaction\n```\n\n```text\nthis.connection\n```\n\n```text\nmanager\n```\n\n```text\nimport { Test } from \"@nestjs/testing\";\n\ndescribe(\"UsersService\", () => {\n let usersService;\n let connection;\n const mockConnection = () => ({\n transaction: jest.fn()\n });\n\n beforeEach(async () => {\n const module = await Test.createTestingModule({\n providers: [\n UsersService,\n {\n provide: Connection,\n useFactory: mockConnection\n }\n ],\n }).compile();\n\n usersService = await module.get<UsersService>(UsersService); \n connection = await modle.get<Connection>(Connection);\n });\n\n describe(\"some tests\", () => {\n it(\"should test something\", async () => {\n const someMockedUsers = [/* some users */];\n const mockedManager = {\n save: jest.fn()\n }\n connection.transaction.mockImplementation((cb) => {\n cb(mockedManager);\n });\n\n await userService.createMany(someMockedUsers);\n\n expect(connection.transaction).toHaveBeenCalled();\n expect(mockedManager.save).toHaveBeenCalledTimes(2);\n // ...\n\n });\n });\n\n\n});\n```\n\n```text\nTestingModule\n```\n\n```text\nConnection\n```\n\n```text\nimport { getConnectionToken } from '@nestjs/typeorm';\n\n{\n provide: getConnectionToken(),\n useClass: Connection,\n},\n```\n\n========================================\n\nComments:\n- This should work. However using `Test.createTestingModule` caused me a lot of problems hogging loads of RAM. I ended not using it and going for `sinon.js` instead.\n- @kkkkkkk your solution works very well thank you ! There is jus something that i'm not getting, when I expect the connection to be called I get an error. Even though the mock is correctly called. Do you know why jest wouldn't record the calls etc... ?\n- I get Received: [Function mockConstructor], instead of the expected value. Looks like Jest ignores the mock.\n- facing this error after your code , TypeError: Cannot read properties of undefined (reading 'name') at new Connection (connection/Connection.ts:119:29)\n- I'm also facing the same error when utilizing `getConnectionToken()`. Any ideas?","metadata":{"transformedAt":"2026-08-18T18:33:44.697Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":135,"estimatedTokens":983}}168{"id":"stack-62832291","source":"stackoverflow","questionId":62832291,"title":"How to apply where-criteria to the same field more than once in TypeORM?","tags":["typeorm"],"text":"Title: How to apply where-criteria to the same field more than once in TypeORM?\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to express this query in TypeORM:\n\n```\nselect * from user where x > 5 and x or other variations, like:\n\n```\nselect * from user where x > '2020-01-01' and x = 5.5 and x <> 10\n```\n\nHow do I do it?\n\n```\nuserRepo.find({where: {x: MoreThan(5), x: LessThan(10)}})\n```\n\nis obviously not legal.\n\n========================================\n\nCode:\n```text\nselect * from user where x > 5 and x < 10\n```\n\n```text\nselect * from user where x > '2020-01-01' and x < '2020-10-10'\nselect * from user where x >= 5.5 and x <> 10\n```\n\n```text\nuserRepo.find({where: {x: MoreThan(5), x: LessThan(10)}})\n```\n\n```text\nimport {Between} from \"typeorm\";\n\nconst loadedPosts = await connection.getRepository(Post).find({\n likes: Between(1, 10)\n});\n```\n\n```text\nuserRepo.find({where: {x: Between(5,10)}})\n```\n\n```text\nimport {Raw} from \"typeorm\";\n\nconst loadedPosts = await connection.getRepository(Post).find({\n currentDate: Raw(alias =>`${alias} > NOW()`)\n});\n```\n\n```text\nSELECT * FROM \"post\" WHERE \"currentDate\" > NOW()\n```\n\n```text\nuserRepo.find({\n where: {\n x: Raw(alias => `${alias} >= 5.5 and ${alias} <> 10`) \n }\n})\n```\n\n```text\nraw\n```\n\n========================================\n\nComments:\n- That matches less than or equal and greater than or equal, not less than and greater than though. It's not exactly the same. On my original query, I'm working with dates, so, it's not as simple of adding or subtracting 1.\n- I corrected the question to avoid matching one and only one single narrow case, since what I'm after is learning and understanding how to use TypeORM.","metadata":{"transformedAt":"2026-08-18T18:33:44.697Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":79,"estimatedTokens":425}}169{"id":"stack-72272265","source":"stackoverflow","questionId":72272265,"title":"How can my class-validator validate union string | number?","tags":["typescript","nestjs","typeorm","class-validator"],"text":"Title: How can my class-validator validate union string | number?\nTags: typescript, nestjs, typeorm, class-validator\nSource: Stack Overflow\n\nQuestion:\nI have an simple DTO class for validation\n\n```\nclass SearchIssuerDto {\n search: string | number;\n}\n```\n\nWhat is the correct way to validate the search param that it can accept an string or a number ?\n\n========================================\n\nCode:\n```js\nclass SearchIssuerDto {\n search: string | number;\n}\n```\n\n```text\n@ValidatorConstraint({ name: 'string-or-number', async: false })\nexport class IsNumberOrString implements ValidatorConstraintInterface {\n validate(text: any, args: ValidationArguments) {\n return typeof text === 'number' || typeof text === 'string';\n }\n\n defaultMessage(args: ValidationArguments) {\n return '($value) must be number or string';\n }\n}\n```\n\n```text\nclass SearchIssuerDto {\n @IsDefined()\n @Validate(IsNumberOrString)\n search: number | string;\n}\n```\n\n========================================\n\nComments:\n- I was wondering if it's possible to do it without custom validator, but if it's impossible thanks mate\n- I looked around for other solution, but sadly did not find anything else","metadata":{"transformedAt":"2026-08-18T18:33:44.697Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":50,"estimatedTokens":295}}170{"id":"stack-60311071","source":"stackoverflow","questionId":60311071,"title":"Nest can't resolve dependencies of repository","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: Nest can't resolve dependencies of repository\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI got error on my nestjs app. I cant figure out whats wring with my code. I \nThe codes is something like this\n\n**AppModule**\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AdminModule } from './components/admin.modules';\n\n@Module({\n imports: [\n AdminModule,\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: process.env.DATABASE_HOST,\n username: process.env.DATABASE_USERNAME,\n password: process.env.DATABASE_PASSWORD,\n database: process.env.DATABASE_NAME,\n port: parseInt(process.env.DATABASE_PORT),\n }),\n ],\n})\nexport class AppModule {}\n```\n\n**AdminModule**\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\nimport { Admin } from './admin.entity';\nimport { AdminRepository } from './admin.repository';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Admin])],\n providers: [AdminRepository],\n})\nexport class AdminModule {}\n```\n\n**AdminRepository**\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\nimport { RepositoryBase } from '../../common/base/repository.base';\nimport { Admin } from './admin.entity';\n\n@Injectable()\nexport class AdminRepository extends RepositoryBase {\n constructor(@InjectRepository(Admin) private readonly repo: Repository) {\n super(repo);\n}\n```\n\nAnd what i get is error like this\n\n Error: Nest can't resolve dependencies of the AdminRepository (?). Please make sure that the argument AdminRepository at index [0] is available in the AdminModule context.\n\n \n Potential solutions:\n - If AdminRepository is a provider, is it part of the current AdminModule?\n - If AdminRepository is exported from a separate @Module, is that module imported within AdminModule?\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AdminModule } from './components/admin.modules';\n\n@Module({\n imports: [\n AdminModule,\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: process.env.DATABASE_HOST,\n username: process.env.DATABASE_USERNAME,\n password: process.env.DATABASE_PASSWORD,\n database: process.env.DATABASE_NAME,\n port: parseInt(process.env.DATABASE_PORT),\n }),\n ],\n})\nexport class AppModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\nimport { Admin } from './admin.entity';\nimport { AdminRepository } from './admin.repository';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Admin])],\n providers: [AdminRepository],\n})\nexport class AdminModule {}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\nimport { RepositoryBase } from '../../common/base/repository.base';\nimport { Admin } from './admin.entity';\n\n@Injectable()\nexport class AdminRepository extends RepositoryBase<Admin> {\n constructor(@InjectRepository(Admin) private readonly repo: Repository<Admin>) {\n super(repo);\n}\n```\n\n```text\nAdminRepository\n```\n\n```text\nTypeOrm\n```\n\n```text\nAdmin\n```\n\n```text\nAdminRepo\n```\n\n```text\nAdminService\n```\n\n```text\nAdmin\n```\n\n```text\n${EntityClassName}Repository\n```\n\n========================================\n\nComments:\n- Hi! Can you provide a repository.base file?\n- Damn... reserved names should throw an error or something.","metadata":{"transformedAt":"2026-08-18T18:33:44.697Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":159,"estimatedTokens":909}}171{"id":"stack-67547621","source":"stackoverflow","questionId":67547621,"title":"CannotDetermineEntityError when saving entities with TypeORM","tags":["nestjs","typeorm"],"text":"Title: CannotDetermineEntityError when saving entities with TypeORM\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI created a NestJS and used TypeORM for the RDBMS(I used postgres in my project).\n\n`Post` is an `@Entity` class, `PostRepository` is a `Repository` class for `Post`.\n\nI was trying to create `OnModuleInit` service to initialize some data.\n\n```\n@Injectable()\nexport class PostsDataInitializer implements OnModuleInit {\n private data: Post[] = [\n {\n title: 'Generate a NestJS project',\n content: 'content',\n },\n {\n title: 'Create GrapQL APIs',\n content: 'content',\n },\n {\n title: 'Connect to Postgres via TypeORM',\n content: 'content',\n },\n ];\n\n constructor(private readonly postRepository: PostRepository) {}\n async onModuleInit(): Promise {\n await this.postRepository.manager.transaction(async (manager) => {\n // NOTE: you must perform all database operations using the given manager instance\n // it's a special instance of EntityManager working with this transaction\n // and don't forget to await things here\n await manager.delete(Post, {});\n console.log('deleted: {} ');\n this.data.forEach(async (d) => await manager.save(d as Post));\n const savedPosts = await manager.find(Post);\n savedPosts.forEach((p) => {\n console.log('saved: {}', p);\n });\n });\n }\n}\n```\n\nWhen starting up the application, I got the following error.\n\n```\nCannotDetermineEntityError: Cannot save, given value must be instance of entity class, instead object literal is given. Or you must specify an entity target to method call.\n```\n\n*But the above `save` was accepting an instance of `Post`*.\n\n========================================\n\nTop Answer:\nYou can alternatively specify the target type as per the error message like so:\n\n```\nawait manager.save(Post, d)\n```\n\nFrom the documentation of save() I see there is such a method as:\n\n```\nsave>(targetOrEntity: EntityTarget, entity: T, options?: SaveOptions): Promise;\n```\n\nnest version 9.1.8\n\n========================================\n\nCode:\n```java\n@Injectable()\nexport class PostsDataInitializer implements OnModuleInit {\n private data: Post[] = [\n {\n title: 'Generate a NestJS project',\n content: 'content',\n },\n {\n title: 'Create GrapQL APIs',\n content: 'content',\n },\n {\n title: 'Connect to Postgres via TypeORM',\n content: 'content',\n },\n ];\n\n constructor(private readonly postRepository: PostRepository) {}\n async onModuleInit(): Promise<void> {\n await this.postRepository.manager.transaction(async (manager) => {\n // NOTE: you must perform all database operations using the given manager instance\n // it's a special instance of EntityManager working with this transaction\n // and don't forget to await things here\n await manager.delete(Post, {});\n console.log('deleted: {} ');\n this.data.forEach(async (d) => await manager.save(d as Post));\n const savedPosts = await manager.find<Post>(Post);\n savedPosts.forEach((p) => {\n console.log('saved: {}', p);\n });\n });\n }\n}\n```\n\n```sh\nCannotDetermineEntityError: Cannot save, given value must be instance of entity class, instead object literal is given. Or you must specify an entity target to method call.\n```\n\n```text\nPost\n```\n\n```text\n@Entity\n```\n\n```text\nPostRepository\n```\n\n```text\nRepository\n```\n\n```text\nPost\n```\n\n```text\nOnModuleInit\n```\n\n```text\nsave\n```\n\n```text\nPost\n```\n\n```js\nprivate data = [\n {\n title: 'Generate a NestJS project',\n content: 'content',\n },\n {\n title: 'Create GrapQL APIs',\n content: 'content',\n },\n {\n title: 'Connect to Postgres via TypeORM',\n content: 'content',\n },\n ].map(data => {\n const post = new Post();\n Object.assign(post, data);\n return post;\n })\n```\n\n```text\n.save\n```\n\n```js\nawait manager.save(Post, d)\n```\n\n```js\nsave<Entity, T extends DeepPartial<Entity>>(targetOrEntity: EntityTarget<Entity>, entity: T, options?: SaveOptions): Promise<T & Entity>;\n```\n\n========================================\n\nComments:\n- I used `d as Post` to cast it to `Post`, why this does not work. What is the difference between object literal and instance in typescript?\n- the difference isn't up to ts but to js. `new Foo()` objects will be `instance of Foo`, while a literal object that just has the shape of `Foo` won't. And TypeORM expect to work with instances of `Foo`\n- btw typecasting in strongly typed languages allow us to convert types. Since javascript is not strongly typed, the *type assertion* that you used will no longer exist at runtime. See this example\n- Works better for me than the accepted answer\n- This answer worked well for me.","metadata":{"transformedAt":"2026-08-18T18:33:44.697Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":188,"estimatedTokens":1161}}172{"id":"stack-60361397","source":"stackoverflow","questionId":60361397,"title":"setting up a one to many relationship for a self referencing table","tags":["sql","postgresql","orm","nestjs","typeorm"],"text":"Title: setting up a one to many relationship for a self referencing table\nTags: sql, postgresql, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a `Project` entity with a non-autogenerated id field and a successor field. This successor is the project that follows next. But maybe there is no following project so this might be null.\n\n```\n@Entity()\nexport class Project extends BaseEntity {\n @PrimaryColumn({ unique: true })\n public id: string;\n\n @OneToMany(() => Project, project => project.id, { nullable: true })\n public successorId?: string;\n}\n```\n\nWhen creating a new project via\n\n```\npublic createProject(id: string, successorId?: string): Promise {\n const project: Project = new Project();\n project.id = id;\n project.successorId = successorId;\n return project.save();\n}\n```\n\nthere are multiple cases I have to take care for.\n\nPassing in an id that already exists:\n\nThis will not throw an error. It just overrides the existing entity.\n\nPassing in `undefined` for the `successorId`:\n\nThe code works fine then but it does not create a `successorId` column with `null` then. The column simply does not exist in the database.\n\nPassing in the same id for `id` and `successorId` (this should be possible):\n\nTypeORM throws the error \n\n TypeError: Cannot read property 'joinColumns' of undefined\n\nPassing in a `successorId` of another existing project:\n\nI'm getting the same error as above\n\nPassing in a `successorId` of a project that doesn't exist:\n\nI'm getting the same error as above\n\nSo how can I fix that? I think my entity design seems to be wrong. Basically it should be\n\n- One project might have one successor\n\n- A project can be the successor of many projects\n\nWould be awesome if someone could help!\n\n**Update**\n\nI also tried this\n\n```\n@OneToMany(() => Project, project => project.successorId, { nullable: true })\n@Column()\npublic successorId?: string;\n```\n\nbut whenever I want to call the `createProject` method I'm getting this error\n\n QueryFailedError: null value in column \"successorId\" violates not-null\n constraint\n\nand this\n\n```\n@OneToMany(() => Project, project => project.successorId, { nullable: true })\npublic successorId?: string;\n```\n\nbut then I'm getting this error\n\n TypeError: relatedEntities.forEach is not a function\n\n========================================\n\nTop Answer:\nYou can try this\n\n```\nexport class RolesPermission {\n @PrimaryGeneratedColumn('uuid')\n @PrimaryColumn({ type: 'varchar', length: 36, default: 'UUID()' })\n entityId?: string;\n\n @Column({ unique: true })\n name: string;\n\n @OneToMany(() => RolesPermission, (rolePermission) => rolePermission.parent)\n rolePermissions?: RolesPermission[];\n\n @ManyToOne(() => RolesPermission, (rolePermission) => rolePermission.rolePermissions, { nullable: true, createForeignKeyConstraints: false })\n parent?: RolesPermission;\n\n @Column({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' })\n createdAt?: Date;\n\n @Column({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP' })\n updatedAt?: Date;}\n```\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class Project extends BaseEntity {\n @PrimaryColumn({ unique: true })\n public id: string;\n\n @OneToMany(() => Project, project => project.id, { nullable: true })\n public successorId?: string;\n}\n```\n\n```text\npublic createProject(id: string, successorId?: string): Promise<Project> {\n const project: Project = new Project();\n project.id = id;\n project.successorId = successorId;\n return project.save();\n}\n```\n\n```text\n@OneToMany(() => Project, project => project.successorId, { nullable: true })\n@Column()\npublic successorId?: string;\n```\n\n```text\n@OneToMany(() => Project, project => project.successorId, { nullable: true })\npublic successorId?: string;\n```\n\n```text\nProject\n```\n\n```text\nundefined\n```\n\n```text\nsuccessorId\n```\n\n```text\nsuccessorId\n```\n\n```text\nnull\n```\n\n```text\nid\n```\n\n```text\nsuccessorId\n```\n\n```text\nsuccessorId\n```\n\n```text\nsuccessorId\n```\n\n```text\ncreateProject\n```\n\n```text\n@Entity()\nexport class Project extends BaseEntity {\n @PrimaryColumn({ unique: true })\n public id: string;\n\n @Column({ nullable: true })\n public successorId?: string;\n\n @ManyToOne(() => Project, project => project.id)\n @JoinColumn({ name: \"successorId\" })\n public successor?: Project;\n}\n```\n\n```text\npublic successor?: Project;\n```\n\n```text\npublic successorId?: string;\n```\n\n```text\nManyToOne\n```\n\n```text\npropertyName\n```\n\n```text\nreferencedColumnName\n```\n\n```text\nsuccessorId\n```\n\n```text\n@Column\n```\n\n```text\nexport class RolesPermission {\n @PrimaryGeneratedColumn('uuid')\n @PrimaryColumn({ type: 'varchar', length: 36, default: 'UUID()' })\n entityId?: string;\n\n @Column({ unique: true })\n name: string;\n\n @OneToMany(() => RolesPermission, (rolePermission) => rolePermission.parent)\n rolePermissions?: RolesPermission[];\n\n @ManyToOne(() => RolesPermission, (rolePermission) => rolePermission.rolePermissions, { nullable: true, createForeignKeyConstraints: false })\n parent?: RolesPermission;\n\n @Column({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP' })\n createdAt?: Date;\n\n @Column({ type: 'datetime', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP' })\n updatedAt?: Date;}\n```\n\n========================================\n\nComments:\n- I tested your solution and I think this seems to work. Would you mind explaining why two fields are required? And it knows how to map that field to a variable via string?\n- The only case still failing was the first part. Creating an entity with the same id just overrides the existing one ..\n- yes, I was able to reproduce it with this sample repo :) github.com/mhcomp/…\n- ok, one last question: The code seems to work fine but are you sure a `ManyToOne` relation should be used instead of a `OneToMany` relation?\n- yep, in TypeORM `@OneToMany` is an inverse side of `@ManyToOne` and cannot exist without `@ManyToOne`. Also `@OneToMany` is not required and can be ommited in this case. For example if you need \"projects which before successor\" or in other words \"projects in which this project is specified as successor\" then you need to use `OneToMany` as inverse side. It will look like `@OneToMany(() => Project, project => project.successor) public projects: Project[]`\n- btw, I don't know your requirements about successor. If a one successor can be specified in many projects, then `@ManyToOne` is right approach. Otherwise if one succesor can only one project, then you should use `@OneToOne` relation instead.","metadata":{"transformedAt":"2026-08-18T18:33:44.697Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":262,"estimatedTokens":1627}}173{"id":"stack-63681836","source":"stackoverflow","questionId":63681836,"title":"Cannot determine GraphQL input type for argument named","tags":["typescript","graphql","typeorm","typegraphql"],"text":"Title: Cannot determine GraphQL input type for argument named\nTags: typescript, graphql, typeorm, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI have two relationed models:\n\n1.- RoleEntity\n\n```\nimport { Column, Entity, BaseEntity, OneToMany, PrimaryColumn } from \"typeorm\";\nimport { Field, ObjectType } from \"type-graphql\";\n\nimport { UserEntity } from \"./user.entity\";\n\n@ObjectType()\n@Entity({\n name: \"tb_roles\"\n})\nexport class RoleEntity extends BaseEntity {\n\n @Field()\n @PrimaryColumn({\n name: \"id\",\n type: \"character varying\",\n length: 5\n })\n id!: string;\n\n @Field()\n @Column({\n name: \"description\",\n type: \"character varying\",\n nullable: true\n })\n description!: string\n\n @Field(() => [UserEntity])\n @OneToMany(() => UserEntity, user => user.role)\n users!: UserEntity[];\n}\n```\n\n2.- UserEntity\n\n```\nimport {Field, ObjectType} from \"type-graphql\";\nimport { BaseEntity, Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn } from \"typeorm\";\n\nimport { RoleEntity } from \"./role.entity\";\n\n@ObjectType()\n@Entity({\n name: \"tb_users\"\n})\nexport class UserEntity extends BaseEntity {\n @Field()\n @PrimaryGeneratedColumn(\"uuid\", {\n name: \"id\"\n })\n id!: string;\n\n @Field()\n @Column({\n name: \"username\",\n type: \"character varying\",\n unique: true,\n nullable: false\n })\n username!: string;\n\n @Field()\n @Column({\n name: \"last_name\",\n type: \"character varying\",\n nullable: false\n })\n lastName!: string;\n\n @Field()\n @Column({\n name: \"mother_last_name\",\n type: \"character varying\",\n nullable: true\n })\n motherLastName!: string;\n\n @Field()\n @Column({\n name: \"first_name\",\n type: \"character varying\",\n nullable: false\n })\n firstName!: string;\n\n @Field()\n @Column({\n name: \"middle_name\",\n type: \"character varying\",\n nullable: true\n })\n middleName!: string;\n\n @Field()\n @Column({\n name: \"email\",\n type: \"character varying\",\n unique: true,\n nullable: false\n })\n email!: string;\n\n @Field()\n @Column({\n name: \"password\",\n type: \"character varying\",\n nullable: false\n })\n password!: string;\n\n @Field(() => RoleEntity)\n @ManyToOne(() => RoleEntity)\n @JoinColumn({name: \"role_id\"})\n role!: RoleEntity;\n\n @Field()\n @Column({\n name: \"is_active\",\n type: \"character varying\",\n nullable: true\n })\n isActive!: boolean;\n\n @Field()\n @CreateDateColumn({\n name: \"created_at\"\n })\n createdAt!: string;\n\n @Field()\n @UpdateDateColumn({\n name: \"updated_at\"\n })\n updatedAt!: string;\n}\n```\n\nAnd this is the resolver for user:\n\n```\nimport {Arg, Mutation, Query, Resolver} from \"type-graphql\";\nimport bcrypt from \"bcryptjs\";\n\nimport {UserEntity} from \"../../entity/user.entity\";\nimport {RoleEntity} from \"../../entity/role.entity\";\n\n@Resolver()\nexport class UserResolver {\n @Query(() => [UserEntity])\n async users() {\n return await UserEntity.find();\n }\n\n @Mutation(() => UserEntity)\n async createUser(\n @Arg('username') username: string,\n @Arg('lastName') lastName: string,\n @Arg('motherLastName') motherLastName: string,\n @Arg('firstName') firstName: string,\n @Arg('middleName') middleName: string,\n @Arg('email') email: string,\n @Arg('password') password: string,\n @Arg('role') role: RoleEntity,\n @Arg('isActive') isActive: boolean\n ): Promise {\n\n const hashedPassword = await bcrypt.hashSync(password, bcrypt.genSaltSync(10));\n\n const user = UserEntity.create({\n username,\n lastName,\n motherLastName,\n firstName,\n middleName,\n email,\n password: hashedPassword,\n role,\n isActive\n }).save();\n\n return user;\n }\n}\n```\n\nbut, i get this error:\n\n(node:14788) UnhandledPromiseRejectionWarning: Error: Cannot determine GraphQL input type for argument named 'role' of 'createUser' of 'UserResolver' class. Does the\nvalue used as its TS type or explicit type is decorated with a proper decorator or is it a proper input value?\n\nI need your help please.\n\n========================================\n\nTop Answer:\nThe error is because you can't use `ObjectType` arguments in mutations¹, just plain scalar types or `InputType`:\n\nhttps://typegraphql.com/docs/resolvers.html#input-types\n\n¹: the `RoleEntity` ObjectType in your case.\n\n========================================\n\nCode:\n```js\nimport { Column, Entity, BaseEntity, OneToMany, PrimaryColumn } from \"typeorm\";\nimport { Field, ObjectType } from \"type-graphql\";\n\nimport { UserEntity } from \"./user.entity\";\n\n\n@ObjectType()\n@Entity({\n name: \"tb_roles\"\n})\nexport class RoleEntity extends BaseEntity {\n\n @Field()\n @PrimaryColumn({\n name: \"id\",\n type: \"character varying\",\n length: 5\n })\n id!: string;\n\n @Field()\n @Column({\n name: \"description\",\n type: \"character varying\",\n nullable: true\n })\n description!: string\n\n @Field(() => [UserEntity])\n @OneToMany(() => UserEntity, user => user.role)\n users!: UserEntity[];\n}\n```\n\n```js\nimport {Field, ObjectType} from \"type-graphql\";\nimport { BaseEntity, Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn } from \"typeorm\";\n\nimport { RoleEntity } from \"./role.entity\";\n\n\n@ObjectType()\n@Entity({\n name: \"tb_users\"\n})\nexport class UserEntity extends BaseEntity {\n @Field()\n @PrimaryGeneratedColumn(\"uuid\", {\n name: \"id\"\n })\n id!: string;\n\n @Field()\n @Column({\n name: \"username\",\n type: \"character varying\",\n unique: true,\n nullable: false\n })\n username!: string;\n\n @Field()\n @Column({\n name: \"last_name\",\n type: \"character varying\",\n nullable: false\n })\n lastName!: string;\n\n @Field()\n @Column({\n name: \"mother_last_name\",\n type: \"character varying\",\n nullable: true\n })\n motherLastName!: string;\n\n @Field()\n @Column({\n name: \"first_name\",\n type: \"character varying\",\n nullable: false\n })\n firstName!: string;\n\n @Field()\n @Column({\n name: \"middle_name\",\n type: \"character varying\",\n nullable: true\n })\n middleName!: string;\n\n @Field()\n @Column({\n name: \"email\",\n type: \"character varying\",\n unique: true,\n nullable: false\n })\n email!: string;\n\n @Field()\n @Column({\n name: \"password\",\n type: \"character varying\",\n nullable: false\n })\n password!: string;\n\n @Field(() => RoleEntity)\n @ManyToOne(() => RoleEntity)\n @JoinColumn({name: \"role_id\"})\n role!: RoleEntity;\n\n @Field()\n @Column({\n name: \"is_active\",\n type: \"character varying\",\n nullable: true\n })\n isActive!: boolean;\n\n @Field()\n @CreateDateColumn({\n name: \"created_at\"\n })\n createdAt!: string;\n\n @Field()\n @UpdateDateColumn({\n name: \"updated_at\"\n })\n updatedAt!: string;\n}\n```\n\n```js\nimport {Arg, Mutation, Query, Resolver} from \"type-graphql\";\nimport bcrypt from \"bcryptjs\";\n\nimport {UserEntity} from \"../../entity/user.entity\";\nimport {RoleEntity} from \"../../entity/role.entity\";\n\n\n@Resolver()\nexport class UserResolver {\n @Query(() => [UserEntity])\n async users() {\n return await UserEntity.find();\n }\n\n @Mutation(() => UserEntity)\n async createUser(\n @Arg('username') username: string,\n @Arg('lastName') lastName: string,\n @Arg('motherLastName') motherLastName: string,\n @Arg('firstName') firstName: string,\n @Arg('middleName') middleName: string,\n @Arg('email') email: string,\n @Arg('password') password: string,\n @Arg('role') role: RoleEntity,\n @Arg('isActive') isActive: boolean\n ): Promise<UserEntity> {\n\n const hashedPassword = await bcrypt.hashSync(password, bcrypt.genSaltSync(10));\n\n const user = UserEntity.create({\n username,\n lastName,\n motherLastName,\n firstName,\n middleName,\n email,\n password: hashedPassword,\n role,\n isActive\n }).save();\n\n return user;\n }\n}\n```\n\n```text\n@Field(() => RoleEntity)\n @ManyToOne(() => RoleEntity)\n @JoinColumn({name: \"role_id\"})\n role!: RoleEntity;\n```\n\n```text\n@Field()\n@Column({name: 'role_id'})\nroleId!: string;\n\n@Field(() => RoleEntity)\nrole!: RoleEntity;\n@ManyToOne(() => RoleEntity, role => role.userConnection)\n@JoinColumn({name: 'role_id'})\nroleConnection!: Promise<RoleEntity>\n```\n\n```text\n@OneToMany(() => UserEntity, user => user.roleConnection)\nuserConnection!: Promise<UserEntity[]>\n```\n\n```text\nquery users {\n users {\n firstName\n username\n roleId\n role {\n description\n }\n }\n}\n```\n\n```text\n@FieldResolver()\n async role(@Root() user: UserEntity): Promise<RoleEntity | undefined> {\n //const role: RoleEntity | undefined = await RoleEntity.findOne(user.roleId);\n //return role;\n return await RoleEntity.findOne(user.roleId);\n }\n```\n\n```text\nObjectType\n```\n\n```text\nInputType\n```\n\n```text\nRoleEntity\n```\n\n```text\nregisterEnumType\n```\n\n```text\n@nestjs/graphql\n```\n\n```text\nimport {registerEnumType} from '@nestjs/graphql'\n```\n\n```text\nregisterEnumType(OrderStatus, { name: 'OrderStatus' });\n```\n\n========================================\n\nComments:\n- Maybe related: github.com/MichalLytek/type-graphql/issues/371\n- Looking at the dates of the other answers, it looks like they've changed something and this is the way to do it now - though we're importing `registerEnumType` from the `'type-graphql'` lib.","metadata":{"transformedAt":"2026-08-18T18:33:44.697Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":478,"estimatedTokens":2337}}174{"id":"stack-67554794","source":"stackoverflow","questionId":67554794,"title":"QueryRunnerAlreadyReleasedError when executing a series of queries in a single transaction","tags":["nestjs","typeorm"],"text":"Title: QueryRunnerAlreadyReleasedError when executing a series of queries in a single transaction\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI add an `OnMoudleInit`service to initialize some sample data in my NestJS application.\n\nTypeORM provides several approaches to wrap the queries into a single transcation.\n\nI tried to use `EntityManager.transaction` to wrap the operations.\n\n```\nawait this.manager.transaction(async (manager) => {\n // NOTE: you must perform all database operations using the given manager instance\n // it's a special instance of EntityManager working with this transaction\n // and don't forget to await things here\n const del = await manager.delete(PostEntity, {});\n console.log('posts deleted: ', del.affected);\n\n const userDel = await manager.delete(UserEntity, {});\n console.log('users deleted: ', userDel.affected);\n\n const user = new UserEntity();\n Object.assign(user, {\n firstName: 'hantsy',\n lastName: 'bai',\n email: 'hantsy@gmail.com',\n });\n const savedUser = await manager.save(user);\n console.log('saved user: ', JSON.stringify(savedUser));\n this.data.forEach(async (d) => {\n const p = new PostEntity();\n p.author = savedUser;\n \n // comment out these relation settings it will work well.\n // \n // const comment = new CommentEntity();\n // comment.content = 'test comment at:' + new Date();\n // p.comments = Promise.resolve([comment]);\n Object.assign(p, d);\n await manager.save(p);\n });\n });\n\n const savedPosts = await this.postRepository.find({});\n console.log('saved:', JSON.stringify(savedPosts));\n }\n```\n\nWhen the application is starting up, the following error occurred.\n\n```\nposts deleted: 2\nusers deleted: 1\nsaved user: {\"firstName\":\"hantsy\",\"lastName\":\"bai\",\"email\":\"hantsy@gmail.com\",\"id\":\"04d5cc63-d36a-4d80-a37f-97424ef168a8\"}\nD:\\hantsylabs\\nestjs-graphql-sample\\node_modules\\typeorm\\error\\QueryRunnerAlreadyReleasedError.js:10\n var _this = _super.call(this) || this;\n ^\n\nQueryRunnerAlreadyReleasedError: Query runner already released. Cannot run queries anymore.\n at new QueryRunnerAlreadyReleasedError (D:\\hantsylabs\\nestjs-graphql-sample\\node_modules\\typeorm\\error\\QueryRunnerAlreadyReleasedError.js:10:28)\n```\n\n**Update**: I found this is caused by the post/comment `cascade` settings, I was trying to use one command to save post/comments.\n\n```\n@OneToMany((type) => CommentEntity, (comment) => comment.post, {\n cascade: true,\n })\n comments?: Promise;\n```\n\n**Update 2**: If I use the `Repository` class to execute the `save` task, it seems it works.\n\n```\nconst post = new PostEntity();\n post.title = 'test title';\n post.content = 'test content';\n const comment = new CommentEntity();\n comment.content = 'test comment';\n post.comments = Promise.resolve([comment]);\n await this.postRepository.save(post);\n //console.log('saved from repository: ', JSON.stringify(savedPost));\n```\n\nWhen I added the above codes before the manager transaction block, and I found the `manager.delete(Post, {})` did not apply the `cascade` settings?\n\n========================================\n\nTop Answer:\nIt's silly, but for me, the issue was that I simply was trying to reuse a QueryRunner that's already \"released\". If you check TypeORM documentation https://orkhan.gitbook.io/typeorm/docs/query-runner you will see each QueryRunner has a function to release() it manually, and there is also a boolean **property called \"isReleased\"** on the QueryRunner instance so if it is released you just have to **create a new QueryRunner** before running your queries.\n\nHope this helps someone.\n\n========================================\n\nCode:\n```js\nawait this.manager.transaction(async (manager) => {\n // NOTE: you must perform all database operations using the given manager instance\n // it's a special instance of EntityManager working with this transaction\n // and don't forget to await things here\n const del = await manager.delete(PostEntity, {});\n console.log('posts deleted: ', del.affected);\n\n const userDel = await manager.delete(UserEntity, {});\n console.log('users deleted: ', userDel.affected);\n\n const user = new UserEntity();\n Object.assign(user, {\n firstName: 'hantsy',\n lastName: 'bai',\n email: 'hantsy@gmail.com',\n });\n const savedUser = await manager.save(user);\n console.log('saved user: ', JSON.stringify(savedUser));\n this.data.forEach(async (d) => {\n const p = new PostEntity();\n p.author = savedUser;\n \n // comment out these relation settings it will work well.\n // \n // const comment = new CommentEntity();\n // comment.content = 'test comment at:' + new Date();\n // p.comments = Promise.resolve([comment]);\n Object.assign(p, d);\n await manager.save(p);\n });\n });\n\n const savedPosts = await this.postRepository.find({});\n console.log('saved:', JSON.stringify(savedPosts));\n }\n```\n\n```sh\nposts deleted: 2\nusers deleted: 1\nsaved user: {\"firstName\":\"hantsy\",\"lastName\":\"bai\",\"email\":\"hantsy@gmail.com\",\"id\":\"04d5cc63-d36a-4d80-a37f-97424ef168a8\"}\nD:\\hantsylabs\\nestjs-graphql-sample\\node_modules\\typeorm\\error\\QueryRunnerAlreadyReleasedError.js:10\n var _this = _super.call(this) || this;\n ^\n\nQueryRunnerAlreadyReleasedError: Query runner already released. Cannot run queries anymore.\n at new QueryRunnerAlreadyReleasedError (D:\\hantsylabs\\nestjs-graphql-sample\\node_modules\\typeorm\\error\\QueryRunnerAlreadyReleasedError.js:10:28)\n```\n\n```js\n@OneToMany((type) => CommentEntity, (comment) => comment.post, {\n cascade: true,\n })\n comments?: Promise<CommentEntity[]>;\n```\n\n```js\nconst post = new PostEntity();\n post.title = 'test title';\n post.content = 'test content';\n const comment = new CommentEntity();\n comment.content = 'test comment';\n post.comments = Promise.resolve([comment]);\n await this.postRepository.save(post);\n //console.log('saved from repository: ', JSON.stringify(savedPost));\n```\n\n```text\nOnMoudleInit\n```\n\n```text\nEntityManager.transaction\n```\n\n```text\ncascade\n```\n\n```text\nRepository\n```\n\n```text\nsave\n```\n\n```text\nmanager.delete(Post, {})\n```\n\n```text\ncascade\n```\n\n```js\nthis.data.forEach(async (d) => {\n const p = new PostEntity();\n p.author = savedUser;\n \n // comment out these relation settings it will work well.\n // \n // const comment = new CommentEntity();\n // comment.content = 'test comment at:' + new Date();\n // p.comments = Promise.resolve([comment]);\n Object.assign(p, d);\n await manager.save(p);\n });\n```\n\n```js\nawait Promise.all(\n this.data.map(async (d) => {\n const p = new PostEntity();\n Object.assign(p, d);\n p.author = user;\n\n const c = CommentEntity.of('test comment at:' + new Date());\n p.comments = Promise.resolve([c]);\n await mgr.save(p);\n }),\n );\n });\n```\n\n```text\nPromise.all\n```\n\n```text\nawait Promise.all(\n grn_items.map(async item => {\nconst itemdata = { grn: { ...grnData }, ...item };\nconst grnItemData = await queryRunner.manager.save(GrnItem, itemdata);\n}),\n );\n```\n\n```text\n@Injectable()\nexport class UserRepository extends Repository<UserEntity> {\n constructor(private dataSource: DataSource) {\n - super(dataSource.getRepository(UserEntity).target, dataSource.manager, dataSource.createQueryRunner());\n + super(UserEntity, dataSource.manager);\n }\n}\n```\n\n========================================\n\nComments:\n- OMG, I love you. I have been looking for a solution for two hours now. This is exactly what I was looking for. Thanks.\n- @AfsharMohebi here's how: In the first example `forEach` fires all async functions and the code continues with execution, eventually exiting the function, and the transaction. The manager.save(p) method probably has some promise chain inside which executes long after the transaction is gone. `await Promise.all`, on the other hand, does not let the execution resume until all of the promises passed to Promise.all are resolved. You can also achieve a similar (but sequential) result like this: `for (const d of this.data) {await manager.save(new PostEntity())}`\n- Promise and data.map instead of forEach works perfectly!\n- superb, but would like to know more on why data.map works and foreach does not works\n- I may be late to the party but, @msonowal, that's because map() would return the values of iterable which Promise.all() requires while forEach() doesn't.\n- Thank you Hantsy. Love you. You saved my life.","metadata":{"transformedAt":"2026-08-18T18:33:44.697Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":255,"estimatedTokens":2142}}175{"id":"stack-54098443","source":"stackoverflow","questionId":54098443,"title":"Specify existing foreign key for O2O relation in TypeORM","tags":["node.js","typeorm"],"text":"Title: Specify existing foreign key for O2O relation in TypeORM\nTags: node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nTake the two entities defined at http://typeorm.io/#/one-to-one-relations\n\nA one-to-one relation is defined in User and as a result a foreign key column \"profileId\" is generated in the User table. So far, so good.\n\nBut my \"User\" entity already has an \"idProfile\" column and I would like this to be the foreign key on which the relation is built. How can I tell TypeORM to use this column instead of generating a new one?\n\n========================================\n\nCode:\n```text\n@Entity()\nclass User {\n @OneToOne(type => Profile)\n @JoinColumn({ name: 'idProfile' })\n profile: Profile\n}\n\n@Entity()\nclass Profile {\n @PrimaryGeneratedColumn()\n id: number\n}\n```\n\n```text\n@JoinColumn()\n```\n\n========================================\n\nComments:\n- Works like a charm. Thank you!\n- But how can you add this value to the db? When I try to add an entry with the FK (for example your idProfile) I get the error Type 'number' has no properties in common with type 'DeepPartial>'","metadata":{"transformedAt":"2026-08-18T18:33:44.697Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":38,"estimatedTokens":273}}176{"id":"stack-62784171","source":"stackoverflow","questionId":62784171,"title":"How to auto-remove orphaned rows in TypeORM?","tags":["typescript","typeorm"],"text":"Title: How to auto-remove orphaned rows in TypeORM?\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a one-to-many relation in TypeORM and I would like to delete rows from the many side of the relationship rather than unlinking them by setting their foreign key to null (the default behavior), leaving them orphaned. How can this be done? I saw a PR for this feature but it was rejected. Is there a workaround or some other way to do this? Here's a simplified version of my code to give some context.\n\n```\n@Entity()\n@TableInheritance({ column: { name: 'type', type: 'text' } })\nexport default class Geolocation {\n @PrimaryGeneratedColumn()\n id!: number;\n\n @IsGeoJSONPoint\n @Column('geography')\n point!: Point;\n}\n\n@ChildEntity('offer')\nexport default class OfferGeolocation extends Geolocation {\n @ManyToOne(type => Offer, offer => offer.geolocations, { onDelete: 'CASCADE' })\n offer!: Offer;\n}\n\n@ChildEntity('business')\nexport default class BusinessGeolocation extends Geolocation {\n @ManyToOne(type => Business, business => business.geolocations, { onDelete: 'CASCADE' })\n business!: Business;\n}\n\n@Entity()\nexport default class Business {\n @PrimaryGeneratedColumn()\n id!: number;\n\n // I would like to remove orphaned business geolocations\n @OneToMany(type => BusinessGeolocation, businessGeolocation => businessGeolocation.business, { cascade: true })\n geolocations!: BusinessGeolocation[];\n}\n\n@Entity()\nexport default class Offer {\n @PrimaryGeneratedColumn()\n id!: number;\n\n // I would like to remove orphaned offer geolocations as well\n @OneToMany(type => OfferGeolocation, offerGeolocation => offerGeolocation.offer, { cascade: true })\n geolocations!: OfferGeolocation[];\n}\n```\n\n========================================\n\nCode:\n```js\n@Entity()\n@TableInheritance({ column: { name: 'type', type: 'text' } })\nexport default class Geolocation {\n @PrimaryGeneratedColumn()\n id!: number;\n\n @IsGeoJSONPoint\n @Column('geography')\n point!: Point;\n}\n\n\n@ChildEntity('offer')\nexport default class OfferGeolocation extends Geolocation {\n @ManyToOne(type => Offer, offer => offer.geolocations, { onDelete: 'CASCADE' })\n offer!: Offer;\n}\n\n\n@ChildEntity('business')\nexport default class BusinessGeolocation extends Geolocation {\n @ManyToOne(type => Business, business => business.geolocations, { onDelete: 'CASCADE' })\n business!: Business;\n}\n\n\n@Entity()\nexport default class Business {\n @PrimaryGeneratedColumn()\n id!: number;\n\n // I would like to remove orphaned business geolocations\n @OneToMany(type => BusinessGeolocation, businessGeolocation => businessGeolocation.business, { cascade: true })\n geolocations!: BusinessGeolocation[];\n}\n\n\n@Entity()\nexport default class Offer {\n @PrimaryGeneratedColumn()\n id!: number;\n\n // I would like to remove orphaned offer geolocations as well\n @OneToMany(type => OfferGeolocation, offerGeolocation => offerGeolocation.offer, { cascade: true })\n geolocations!: OfferGeolocation[];\n}\n```\n\n```text\n@ChildEntity('business')\nexport default class BusinessGeolocation extends Geolocation {\n @ManyToOne(\n type => Business, business => business.geolocations, {\n onDelete: 'CASCADE',\n orphanedRowAction: \"delete\" // NEW\n })\n business!: Business;\n}\n```\n\n========================================\n\nComments:\n- Did you find a solution? Thinking i might just 'delete where col = null'?\n- @dale Nope, not yet :(\n- Hi, in this example, does it mean that if you remove a row in 'business' table (represented here by the entity BusinessGeolocation), THEN a row in the related entity of kind \"Business\" will be removed, ONLY WHEN this row in related entity of kind \"Business\" does not have any other row from 'business' table pointing to it? So basically for now my undestanding is that it would work if i do something like: await BusinessGeolocation.remove(varOfTypeBusinessGeolocation); I have the same setup, minus the @childEntity() overhead, and it doesnt work for me, the related business entity remains...\n- I’m using TypeORM and noticed that while orphanedRowAction: 'delete' can automatically remove orphaned child entities, there is no equivalent feature for soft removal. Is there a reason why TypeORM doesn’t provide orphanedRowAction: 'soft-remove', and what’s the best practice to implement this behavior safely?","metadata":{"transformedAt":"2026-08-18T18:33:44.697Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":123,"estimatedTokens":1073}}177{"id":"stack-68948248","source":"stackoverflow","questionId":68948248,"title":"Find rows using foreign key in TypeORM","tags":["postgresql","nestjs","typeorm"],"text":"Title: Find rows using foreign key in TypeORM\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have an OneToMany relation from `User` to `Message`.\n\nWhen I insert register a user with a message, it adds the user to the `User` table, and the message to the `Message` table with a `userId` pointing to the user's id.\n\nThis is done automatically using the following setup.\n\n`User` entity:\n\n```\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn() \n id: number;\n\n @Column()\n name: string;\n\n @Column()\n email: string;\n\n @JoinTable()\n @OneToMany((type) => Message, (message) => message.user, {\n cascade: true,\n })\n messages: Message[];\n}\n```\n\n`Message` entity:\n\n```\n@Entity()\nexport class Message {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n text: string;\n @ManyToOne((type) => User, (user) => user.messages, { eager: true })\n user: User[];\n}\n```\n\nIf I want to find all messages from a user via `userId` with:\n\n```\nconst existing_msgs = await this.messageRepository.find({\n where: { userId: user.id },\n});\n```\n\nIt tells me that it cannot find the `userId` column, which is understandable as I did not specifically include `userId` to the `Message` entity.\n\nBut how would we query it in this case?\n\n========================================\n\nTop Answer:\nI was able to do it with the following querybuilder.\n\n```\nconst msg_arr = await this.userRepository\n .createQueryBuilder('user')\n .leftJoinAndSelect('user.messages', 'messages')\n .where('user.id = :userId', { userId: user.id })\n .andWhere('messages.text LIKE :text', { text: message })\n .select('messages.text')\n .execute();\n```\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn() \n id: number;\n\n @Column()\n name: string;\n\n @Column()\n email: string;\n\n @JoinTable()\n @OneToMany((type) => Message, (message) => message.user, {\n cascade: true,\n })\n messages: Message[];\n}\n```\n\n```text\n@Entity()\nexport class Message {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n text: string;\n @ManyToOne((type) => User, (user) => user.messages, { eager: true })\n user: User[];\n}\n```\n\n```text\nconst existing_msgs = await this.messageRepository.find({\n where: { userId: user.id },\n});\n```\n\n```text\nUser\n```\n\n```text\nMessage\n```\n\n```text\nUser\n```\n\n```text\nMessage\n```\n\n```text\nuserId\n```\n\n```text\nUser\n```\n\n```text\nMessage\n```\n\n```text\nuserId\n```\n\n```text\nuserId\n```\n\n```text\nuserId\n```\n\n```text\nMessage\n```\n\n```text\nconst existing_msgs = await this.messageRepository.find({\n where: { user: { id: user.id }},\n});\n```\n\n```text\n@Entity()\nexport class Message {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n text: string;\n\n @ManyToOne((type) => User, (user) => user.messages, { eager: true })\n @JoinColumn() // <-- Add this\n user: User[];\n}\n```\n\n```text\nconst msg_arr = await this.userRepository\n .createQueryBuilder('user')\n .leftJoinAndSelect('user.messages', 'messages')\n .where('user.id = :userId', { userId: user.id })\n .andWhere('messages.text LIKE :text', { text: message })\n .select('messages.text')\n .execute();\n```\n\n========================================\n\nComments:\n- good but you missed ':' at --> where: { user : { id: user.id} }\n- you're right, just fixed it\n- Shouldn't it be `user: User;` - i.e. Message entity has column `user` pointing to single User entity?","metadata":{"transformedAt":"2026-08-18T18:33:44.697Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":198,"estimatedTokens":850}}178{"id":"stack-60339223","source":"stackoverflow","questionId":60339223,"title":"Node.js, transaction coflicts in PostgreSQL, optimistic concurrency control and transaction retries","tags":["node.js","postgresql","typeorm","node-postgres"],"text":"Title: Node.js, transaction coflicts in PostgreSQL, optimistic concurrency control and transaction retries\nTags: node.js, postgresql, typeorm, node-postgres\nSource: Stack Overflow\n\nQuestion:\nI want to use PostgreSQL transaction isolation to ensure data correctness with optimistic concurrency control pattern where conflicting transactions are automatically retried, instead of my application doing upfront locking of database rows and tables. \n\nOne usual way to implement this is that the web application retries the transaction a specific number of times within a code block or replays the HTTP request by a middleware layer, also known as HTTP request replay. Here is an example of such a middleware for Pyramid and Python web applications web. \n\nI did not find any good information on how Node.js and its PostgreSQL driver handle situations where there are two concurrent transactions in progress and one cannot go through because of reading and write conflicts. PostgreSQL will rollback one of the transactions, but how this is signalled to the application? In Python, PSQL driver would raise `psycopg2.extensions.TransactionRollbackError` under this condition. For other SQL database drivers here are some exceptions they will raise.\n\nThis behaviour is more usual when you have set your SQL transaction isolation level to SERIALIZABLE, as you tend to get more conflicts under load, so I would like to handle it gracefully instead of giving HTTP 500 to users.\n\nMy question is:\n\nHow to detect dirty read rollbacks with PostgreSQL and some of the common ORM frameworks like TypeORM - if special handling is needed and the retry library cannot be independent?\n\nIs there a middleware (NestJS/Express.js/others) to handle this and automatically try to replay the HTTP request N number of times whenever there is a transaction rollback from the database driver?\n\n========================================\n\nCode:\n```text\npsycopg2.extensions.TransactionRollbackError\n```\n\n```text\n/**\n * Check error code to determine if we should retry a transaction.\n * \n * See https://www.postgresql.org/docs/10/errcodes-appendix.html and\n * https://stackoverflow.com/a/16409293/749644\n */\nfunction shouldRetryTransaction(err: unknown) {\n const code = typeof err === 'object' ? String((err as any).code) : null\n return code === '40001' || code === '40P01';\n}\n\n/**\n * Using a repeatable read transaction throws an error with the code 40001 \n * \"serialization failure due to concurrent update\" if the user was \n * updated by another concurrent transaction.\n */\nasync function updateUser(data: unknown) {\n try {\n return await this.userRepo.manager.transaction(\n 'REPEATABLE READ',\n async manager => {\n const user = manager.findOne(User, id);\n \n // Modify user\n // ...\n \n // Save the user\n await manager.save(user);\n }\n );\n } catch (err) {\n if (shouldRetryTransaction(err)) {\n // retry logic \n } else {\n throw err;\n }\n }\n}\n```\n\n```text\n/**\n * Request replay middleware\n */\n\nimport retry from 'async-retry';\n\nfunction replayOnTransactionError(fn: (req, res, next) => unknown) {\n return (req, res, next) => {\n retry(bail => {\n try {\n // Call the actual handler\n await fn(req, res, next);\n } catch (err) {\n if (!shouldRetryTransaction(err)) {\n // Bail out if we're not supposed to retry anymore\n return bail(err);\n }\n\n // Rethrow error to continue retrying\n throw err;\n }\n }, {\n factor: 2,\n retries: 3,\n minTimeout: 30,\n });\n }\n}\n\napp.put('/users/:id', replayOnTransactionError(async (req, res, next) => {\n // ...\n}))\n```\n\n```text\npg\n```\n\n```text\nasync-retry\n```\n\n```text\nmanager\n```\n\n```text\ntypeorm-transactional-cls-hooked\n```\n\n========================================\n\nComments:\n- \"*How to detect dirty read*\" - that's easy: Postgres does not support dirty reads, so there is nothing to \"detect\"\n- Removed the dirty read bit, so hope the question makes more sense now. I just wanted to demostrate what is a transaction conflict with an image.\n- I still don't understand what you mean with a \"*dirty read rollback*\" if there are no dirty reads in Postgres\n- In the links there is more information which describes problem and solutions in other programming languages.\n- Thank you Mihail. This is a good start. Usually other frameworks that have been around for longer time (Django, Rails) do this in a middleware peer HTTP request, so that one does not need to write manual update logic for every function. This is so called HTTP request replay.\n- @MikkoOhtamaa I added a middleware that replays requests for express apps.","metadata":{"transformedAt":"2026-08-18T18:33:44.697Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":127,"estimatedTokens":1173}}179{"id":"stack-60927609","source":"stackoverflow","questionId":60927609,"title":"Nest can't resolve dependencies of the [ServiceName]","tags":["typescript","nestjs","typeorm"],"text":"Title: Nest can't resolve dependencies of the [ServiceName]\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThe error that says that the dependency can't be resolved is not clear enough. Currently, the error output says: \n\n```\n[ExceptionHandler] Nest can't resolve dependencies of the LeadService (LeadRepository, ?). Please make sure that the argument dependency at index [1] is available in the LeadModule context.\n```\n\nFrom this output, I can conclude that the dependency `ConsentService` of my `LeadService`. See `LeadService` constructor below.\n\nAdditionally, the output also puts the following suggestion:\n\n*Potential solutions:*\n\n \n \n- If dependency is a provider, is it part of the current LeadModule?\n \n\n**My answer:** It is a provider, but it's not part of the current module. It's a provider from the ConsentModule. See ConsentModule definition. \n\n \n \n- If dependency is exported from a separate @Module, is that module imported within LeadModule?\n \n\n```\n@Module({\n imports: [ /* the Module containing dependency */ ]\n })\n```\n\n**My answer:** Yes, it is exported from the ConsentModule and it is imported in the LeadModule thus I don't understand why is this failing.\n\n### Input Code\n\n**ConsentService** \n\n```\n@Injectable()\nexport class ConsentService {\n constructor(@InjectRepository(Consent) private repository: Repository) {}\n}\n```\n\n**LeadService**\n\n```\n@Injectable()\nexport class LeadService {\n constructor(\n @InjectRepository(Lead)\n private leadRepository: Repository,\n @Inject()\n private consentService: ConsentService\n ) {}\n}\n```\n\n**ConsentModule**\n\n```\nimport { Module } from '@nestjs/common';\nimport { ConsentService } from './consent.service';\nimport { Consent } from '../db/models';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Consent])],\n providers: [ConsentService],\n exports: [ConsentService]\n})\nexport class ConsentModule {}\n```\n\n**LeadModule**\n\n```\nimport { Module } from '@nestjs/common';\nimport { LeadService } from './lead.service';\nimport { Lead } from '../db/models';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { ConsentModule } from './consent.module';\n\n@Module({\n imports: [ConsentModule, TypeOrmModule.forFeature([Lead])],\n providers: [LeadService],\n exports: [LeadService]\n})\nexport class LeadModule {}\n```\n\n**AppModule**\n\n```\n@Global()\n@Module({\n imports: [\n ConsentModule,\n LeadModule,\n TypeOrmModule.forRoot({\n ...getDbConnectionProperties(),\n entities: [Consent, Lead]\n })\n ],\n controllers: [\n DevController,\n HealthController\n ],\n providers: []\n})\nexport class AppModule {}\n```\n\nI would like to know why exactly is the error happening because I think I have declared everything correctly\n\n========================================\n\nCode:\n```text\n[ExceptionHandler] Nest can't resolve dependencies of the LeadService (LeadRepository, ?). Please make sure that the argument dependency at index [1] is available in the LeadModule context.\n```\n\n```text\n@Module({\n imports: [ /* the Module containing dependency */ ]\n })\n```\n\n```text\n@Injectable()\nexport class ConsentService {\n constructor(@InjectRepository(Consent) private repository: Repository<Consent>) {}\n}\n```\n\n```text\n@Injectable()\nexport class LeadService<T extends LeadPayload> {\n constructor(\n @InjectRepository(Lead)\n private leadRepository: Repository<Lead>,\n @Inject()\n private consentService: ConsentService\n ) {}\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { ConsentService } from './consent.service';\nimport { Consent } from '../db/models';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Consent])],\n providers: [ConsentService],\n exports: [ConsentService]\n})\nexport class ConsentModule {}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { LeadService } from './lead.service';\nimport { Lead } from '../db/models';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { ConsentModule } from './consent.module';\n\n@Module({\n imports: [ConsentModule, TypeOrmModule.forFeature([Lead])],\n providers: [LeadService],\n exports: [LeadService]\n})\nexport class LeadModule {}\n```\n\n```text\n@Global()\n@Module({\n imports: [\n ConsentModule,\n LeadModule,\n TypeOrmModule.forRoot({\n ...getDbConnectionProperties(),\n entities: [Consent, Lead]\n })\n ],\n controllers: [\n DevController,\n HealthController\n ],\n providers: []\n})\nexport class AppModule {}\n```\n\n```text\nConsentService\n```\n\n```text\nLeadService\n```\n\n```text\nLeadService\n```\n\n```text\n@Inject\n```\n\n```text\ntoken\n```\n\n```text\n@Inject(\"name\")\n```\n\n```text\nLeadService\n```\n\n```text\nconsentService\n```\n\n```text\n@Inject(ConsentService)\n```\n\n```text\nConsentService\n```\n\n```text\nLeadService\n```\n\n```text\n@Inject(ConsentService)\n```\n\n```text\n@Inject()\n```\n\n```text\nconsentService\n```\n\n```text\n@Inject()\n```\n\n```text\nLeadService\n```\n\n```text\nConsentService\n```\n\n```text\nLeadService\n```\n\n```text\nLeadService\n```\n\n```text\n@Inject()\n```\n\n```text\nLeadService\n```\n\n```text\nConsentService\n```\n\n========================================\n\nComments:\n- Thanks @kierans. I completely agree with your argument that `@Inject` shouldn't be used at all. In fact removing this solved my problem.","metadata":{"transformedAt":"2026-08-18T18:33:44.698Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":29,"totalLines":292,"estimatedTokens":1309}}180{"id":"stack-55009830","source":"stackoverflow","questionId":55009830,"title":"NestJS TypeORM InjectRepository Cannot read property 'prototype' of undefined","tags":["typescript","jestjs","nestjs","typeorm"],"text":"Title: NestJS TypeORM InjectRepository Cannot read property 'prototype' of undefined\nTags: typescript, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nTrying to unit test.\nGot following error:\n\n TypeError: Cannot read property 'prototype' of undefined\n\n \n export class UserService {\n\n \n constructor(@InjectRepository(User) private readonly userRepository:\n Repository ) { } \n\n**spec.ts:**\n\n```\ndescribe('AuthController', () => {\nlet authController: AuthController;\nlet authService: AuthService;\nlet mockRepository = {\n\n};\nbeforeEach(async () => {\n const module = await Test.createTestingModule({\n imports: [\n TypeOrmModule.forFeature([User]),\n ],\n controllers: [AuthController],\n providers: [AuthService, {\n provide: getRepositoryToken(User),\n useValue: mockRepository\n }]\n }).compile()\n authService = module.get(AuthService);\n authController = module.get(AuthController)\n});\n```\n\nCan someone a solution please?\n\n**MORE INFO**:\n\nSo seems like its something wrong with `typeorm`\n\n```\nbeforeEach(async () => {\n const module = await Test.createTestingModule({\n\n }).compile()\n authService = module.get(AuthService);\n authController = module.get(AuthController)\n});\n```\n\nWith this code I'm getting exact the same error. So only problem is adding `typeorm` to this test Module.\n\nSo it fails because of dependency: **AuthController->AuthService->UserService->TypeORM**\n\nBtw just checked `UserService` using API with Postman and it works fine.\n\n**Still no result:**\n\n```\nmodule = await Test.createTestingModule({\n controllers: [AuthController],\n components: [\n {\n provide: AuthService,\n useValue: {}\n },\n {\n provide: UserService,\n useValue: {}\n },\n {\n provide: getRepositoryToken(User),\n useValue: {}\n }\n ],\n providers: [\n {\n provide: AuthService,\n useValue: {}\n },\n {\n provide: UserService,\n useValue: {}\n },\n {\n provide: getRepositoryToken(User),\n useValue: {}\n }\n ]\n }).compile()\n this.authController = module.get(AuthController)\n```\n\nAlso \n\n```\nclass AuthServiceMock {\n logIn(userName) {\n return { id:100, isDeleted:false, login:\"login\", password:\"password\"};\n }\n\n signUp() {\n return { expireIn: 3600, token:\"token\" };\n }\n}\n\ndescribe('AuthController', () => {\nlet module: TestingModule;\nlet authController: AuthController;\nlet authService: AuthService;\n\nbeforeEach(async () => {\n module = await Test.createTestingModule({\n controllers: [AuthController],\n components: [\n\n ],\n providers: [\n {\n provide: AuthService,\n useClass: AuthServiceMock\n },\n ]\n }).compile()\n this.authController = module.get(AuthController)\n});\n```\n\n========================================\n\nTop Answer:\nI just passed the User entity to Repository and it works.\n\n```\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(User)\n private readonly userRepository: Repository\n ) { }\n\n}\n```\n\nCheckout docs from here: https://docs.nestjs.com/techniques/database. They have pretty good docs.\n\n========================================\n\nCode:\n```text\ndescribe('AuthController', () => {\nlet authController: AuthController;\nlet authService: AuthService;\nlet mockRepository = {\n\n};\nbeforeEach(async () => {\n const module = await Test.createTestingModule({\n imports: [\n TypeOrmModule.forFeature([User]),\n ],\n controllers: [AuthController],\n providers: [AuthService, {\n provide: getRepositoryToken(User),\n useValue: mockRepository\n }]\n }).compile()\n authService = module.get<AuthService>(AuthService);\n authController = module.get<AuthController>(AuthController)\n});\n```\n\n```text\nbeforeEach(async () => {\n const module = await Test.createTestingModule({\n\n }).compile()\n authService = module.get<AuthService>(AuthService);\n authController = module.get<AuthController>(AuthController)\n});\n```\n\n```text\nmodule = await Test.createTestingModule({\n controllers: [AuthController],\n components: [\n {\n provide: AuthService,\n useValue: {}\n },\n {\n provide: UserService,\n useValue: {}\n },\n {\n provide: getRepositoryToken(User),\n useValue: {}\n }\n ],\n providers: [\n {\n provide: AuthService,\n useValue: {}\n },\n {\n provide: UserService,\n useValue: {}\n },\n {\n provide: getRepositoryToken(User),\n useValue: {}\n }\n ]\n }).compile()\n this.authController = module.get<AuthController>(AuthController)\n```\n\n```text\nclass AuthServiceMock {\n logIn(userName) {\n return { id:100, isDeleted:false, login:\"login\", password:\"password\"};\n }\n\n signUp() {\n return { expireIn: 3600, token:\"token\" };\n }\n}\n\ndescribe('AuthController', () => {\nlet module: TestingModule;\nlet authController: AuthController;\nlet authService: AuthService;\n\nbeforeEach(async () => {\n module = await Test.createTestingModule({\n controllers: [AuthController],\n components: [\n\n ],\n providers: [\n {\n provide: AuthService,\n useClass: AuthServiceMock\n },\n ]\n }).compile()\n this.authController = module.get<AuthController>(AuthController)\n});\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeorm\n```\n\n```text\nUserService\n```\n\n```js\nexport * from './user.module';\n```\n\n```text\nsrc/user/index.ts\n```\n\n```text\nUserModule\n```\n\n```text\nsrc/user/user.module.ts\n```\n\n```text\nUserModule\n```\n\n```text\nsrc/user/index.ts\n```\n\n```text\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(User)\n private readonly userRepository: Repository<User>\n ) { }\n\n}\n```\n\n```text\nconst module = await Test.createTestingModule({\n controllers: [AuthController],\n providers: [{\n provide: AuthService,\n useValue: authServiceMock\n }]\n}).compile()\n```\n\n```text\nTypeOrmModule.forFeature(...)\n```\n\n```text\nTypeOrmModule.forRoot(...)\n```\n\n```text\nAuthService\n```\n\n```text\nAuthService\n```\n\n```text\nasync findAll() {\n \n return await this.userRepository.createCursor(this.userRepository.find()).toArray();\n }\n```\n\n========================================\n\nComments:\n- Did you solve it somehow? I\"m having the same issue\n- @alex88 yes. I recreated project and copied all old files to new. Seems like it was some typeorm bug.\n- UserService injects repository and AuthService injects UserService. I tryed ur code but still getting same error.\n- Weird, `typeorm` is not involved at all in the controller test. What's the stacktrace of the error, where does it point to?\n- Have a look at this test for reference: github.com/kiwikern/shassi-nest/blob/master/src/auth/…\n- Its point to @InjectRepository(User) at at Object.getRepositoryToken\n- That's really weird. The actual `UserService` should *never* be instantiated when you unit test the `AuthController` or the `AuthService` with mocks.\n- Let us continue this discussion in chat.\n- In order to let more user benefit form your answer, could you provide more explanation please.\n- You saved me alive!","metadata":{"transformedAt":"2026-08-18T18:33:44.698Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":351,"estimatedTokens":1791}}181{"id":"stack-60677582","source":"stackoverflow","questionId":60677582,"title":"EntityMetadataNotFound: No metadata for \"BusinessApplication\" was found","tags":["typescript","webpack","next.js","typeorm","webpack-hmr"],"text":"Title: EntityMetadataNotFound: No metadata for \"BusinessApplication\" was found\nTags: typescript, webpack, next.js, typeorm, webpack-hmr\nSource: Stack Overflow\n\nQuestion:\nI've been using TypeORM with no problems for a while, but then suddenly this error pops up when making an API call:\n\n```\nEntityMetadataNotFound: No metadata for \"BusinessApplication\" was found.\n at new EntityMetadataNotFoundError (C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\typeorm\\error\\EntityMetadataNotFoundError.js:10:28)\n at Connection.getMetadata (C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\typeorm\\connection\\Connection.js:336:19)\n at EntityManager. (C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\typeorm\\entity-manager\\EntityManager.js:459:44)\n at step (C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\tslib\\tslib.js:136:27)\n at Object.next (C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\tslib\\tslib.js:117:57)\n at C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\tslib\\tslib.js:110:75\n at new Promise ()\n at Object.__awaiter (C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\tslib\\tslib.js:106:16)\n at EntityManager.find (C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\typeorm\\entity-manager\\EntityManager.js:456:24)\n at module.exports../src/pages/api/business-applications/[id].ts.__webpack_exports__.default.Object (C:\\Users\\Robbie\\Code\\fit-society\\.next\\server\\static\\development\\pages\\api\\business-applications\\[id].js:1648:65)\n at process._tickCallback (internal/process/next_tick.js:68:7)\n```\n\nIt happens when this code is called:\n\n```\nimport { BusinessApplication } from '../../../backend/all-entities';\nimport db from '../../../backend/database';\n\n// in a function...\n const manager = await db.getManager();\n // in this case, req.data.id does equal \"oldest\"\n const application: BusinessApplication | undefined =\n req.data.id === 'oldest'\n ? (await manager.find(BusinessApplication, { order: { dateSubmitted: 'DESC' }, take: 1 }))[0]\n : await manager.findOne(BusinessApplication, { where: { id: parseInt(req.data.id, 10) } });\n if (application == null) throw createError(404, 'Business application not found');\n return application;\n```\n\nIn backend/all-entities.ts:\n\n```\n/**\n * This file exists to solve circular dependency problems with Webpack by explicitly specifying the module loading order.\n * @see https://medium.com/visual-development/how-to-fix-nasty-circular-dependency-issues-once-and-for-all-in-javascript-typescript-a04c987cf0de\n */\n\nimport Account_ from './entities/Account';\n\nexport { default as Qualification } from './entities/Qualification';\n\nexport { default as EditableAccount } from './entities/EditableAccount';\nexport { default as EditableBusiness } from './entities/EditableBusiness';\nexport { default as Business } from './entities/Business';\nexport { default as BusinessApplication, SendableBusinessApplication } from './entities/BusinessApplication';\nexport { default as EditableCustomer } from './entities/EditableCustomer';\nexport { default as Customer } from './entities/Customer';\n\nexport { default as Offer } from './entities/Offer';\nexport { default as ProductOffer } from './entities/ProductOffer';\nexport { default as ServiceOffer } from './entities/ServiceOffer';\n```\n\nIn backend/database.ts:\n\n```\nimport 'reflect-metadata';\nimport {\n Connection,\n ConnectionManager,\n ConnectionOptions,\n createConnection,\n EntityManager,\n getConnectionManager\n} from 'typeorm';\nimport { Business, BusinessApplication, Customer, ProductOffer, ServiceOffer, Qualification } from './all-entities';\n\n/**\n * Database manager class\n */\nclass Database {\n private connectionManager: ConnectionManager;\n\n constructor() {\n this.connectionManager = getConnectionManager();\n }\n\n private async getConnection(): Promise {\n const CONNECTION_NAME = 'default';\n let connection: Connection;\n\n if (this.connectionManager.has(CONNECTION_NAME)) {\n connection = this.connectionManager.get(CONNECTION_NAME);\n if (!connection.isConnected) {\n connection = await connection.connect();\n }\n } else {\n const connectionOptions: ConnectionOptions = {\n name: CONNECTION_NAME,\n type: 'postgres',\n url: process.env.DATABASE_URL,\n synchronize: true,\n entities: [Business, BusinessApplication, Qualification, Customer, ProductOffer, ServiceOffer]\n };\n connection = await createConnection(connectionOptions);\n }\n\n return connection;\n }\n\n public getManager(): Promise {\n return this.getConnection().then(conn => conn.manager);\n }\n}\n\nconst db = new Database();\nexport default db;\n```\n\nIn backend/entities/BusinessApplication.ts:\n\n```\nimport { IsIn, IsString, IsOptional } from 'class-validator';\nimport { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn } from 'typeorm';\nimport { EditableBusiness } from '../all-entities';\n\nclass PasswordlessBusinessApplication extends EditableBusiness {\n @Column()\n @IsIn(['individual', 'company'])\n type!: 'individual' | 'company';\n\n @Column({ nullable: true })\n @IsOptional()\n @IsString()\n fein?: string;\n\n @Column({ nullable: true })\n @IsOptional()\n @IsString()\n professionalCertificationUrl?: string;\n}\n\n@Entity()\nexport default class BusinessApplication extends PasswordlessBusinessApplication {\n @PrimaryGeneratedColumn()\n id!: number;\n\n @CreateDateColumn()\n dateSubmitted!: Date;\n\n @Column()\n @IsString()\n passwordHash!: string;\n}\n\n/**\n * A business application sent by the client, which contains a password instead of a password hash.\n * Qualification objects do not require id or business.\n */\nexport class SendableBusinessApplication extends PasswordlessBusinessApplication {\n @IsString()\n password!: string;\n}\n```\n\nFrom what I can see, the imports all point to the right file, I imported reflect-metadata, and I put the `@Entity()` decorator on the `BusinessApplication` class. So what could be going wrong? Notably, if I change `await manager.find(BusinessApplication, ...)` in the first file to `await manager.find('BusinessApplication', ...)` it works fine, but I don't want to do that because I'll lose intellisense. Also, this error doesn't happen the first time the server is initialized, but after it is hot-module-reloaded by Webpack it breaks (this can happen after Next.js disposes of the page or after I change the code).\n\n========================================\n\nTop Answer:\nremove dist folder from your project and run again\n\n========================================\n\nCode:\n```text\nEntityMetadataNotFound: No metadata for \"BusinessApplication\" was found.\n at new EntityMetadataNotFoundError (C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\typeorm\\error\\EntityMetadataNotFoundError.js:10:28)\n at Connection.getMetadata (C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\typeorm\\connection\\Connection.js:336:19)\n at EntityManager.<anonymous> (C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\typeorm\\entity-manager\\EntityManager.js:459:44)\n at step (C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\tslib\\tslib.js:136:27)\n at Object.next (C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\tslib\\tslib.js:117:57)\n at C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\tslib\\tslib.js:110:75\n at new Promise (<anonymous>)\n at Object.__awaiter (C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\tslib\\tslib.js:106:16)\n at EntityManager.find (C:\\Users\\Robbie\\Code\\fit-society\\node_modules\\typeorm\\entity-manager\\EntityManager.js:456:24)\n at module.exports../src/pages/api/business-applications/[id].ts.__webpack_exports__.default.Object (C:\\Users\\Robbie\\Code\\fit-society\\.next\\server\\static\\development\\pages\\api\\business-applications\\[id].js:1648:65)\n at process._tickCallback (internal/process/next_tick.js:68:7)\n```\n\n```js\nimport { BusinessApplication } from '../../../backend/all-entities';\nimport db from '../../../backend/database';\n\n// in a function...\n const manager = await db.getManager();\n // in this case, req.data.id does equal \"oldest\"\n const application: BusinessApplication | undefined =\n req.data.id === 'oldest'\n ? (await manager.find(BusinessApplication, { order: { dateSubmitted: 'DESC' }, take: 1 }))[0]\n : await manager.findOne(BusinessApplication, { where: { id: parseInt(req.data.id, 10) } });\n if (application == null) throw createError(404, 'Business application not found');\n return application;\n```\n\n```js\n/**\n * This file exists to solve circular dependency problems with Webpack by explicitly specifying the module loading order.\n * @see https://medium.com/visual-development/how-to-fix-nasty-circular-dependency-issues-once-and-for-all-in-javascript-typescript-a04c987cf0de\n */\n\nimport Account_ from './entities/Account';\n\nexport { default as Qualification } from './entities/Qualification';\n\nexport { default as EditableAccount } from './entities/EditableAccount';\nexport { default as EditableBusiness } from './entities/EditableBusiness';\nexport { default as Business } from './entities/Business';\nexport { default as BusinessApplication, SendableBusinessApplication } from './entities/BusinessApplication';\nexport { default as EditableCustomer } from './entities/EditableCustomer';\nexport { default as Customer } from './entities/Customer';\n\nexport { default as Offer } from './entities/Offer';\nexport { default as ProductOffer } from './entities/ProductOffer';\nexport { default as ServiceOffer } from './entities/ServiceOffer';\n```\n\n```js\nimport 'reflect-metadata';\nimport {\n Connection,\n ConnectionManager,\n ConnectionOptions,\n createConnection,\n EntityManager,\n getConnectionManager\n} from 'typeorm';\nimport { Business, BusinessApplication, Customer, ProductOffer, ServiceOffer, Qualification } from './all-entities';\n\n/**\n * Database manager class\n */\nclass Database {\n private connectionManager: ConnectionManager;\n\n constructor() {\n this.connectionManager = getConnectionManager();\n }\n\n private async getConnection(): Promise<Connection> {\n const CONNECTION_NAME = 'default';\n let connection: Connection;\n\n if (this.connectionManager.has(CONNECTION_NAME)) {\n connection = this.connectionManager.get(CONNECTION_NAME);\n if (!connection.isConnected) {\n connection = await connection.connect();\n }\n } else {\n const connectionOptions: ConnectionOptions = {\n name: CONNECTION_NAME,\n type: 'postgres',\n url: process.env.DATABASE_URL,\n synchronize: true,\n entities: [Business, BusinessApplication, Qualification, Customer, ProductOffer, ServiceOffer]\n };\n connection = await createConnection(connectionOptions);\n }\n\n return connection;\n }\n\n public getManager(): Promise<EntityManager> {\n return this.getConnection().then(conn => conn.manager);\n }\n}\n\nconst db = new Database();\nexport default db;\n```\n\n```js\nimport { IsIn, IsString, IsOptional } from 'class-validator';\nimport { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn } from 'typeorm';\nimport { EditableBusiness } from '../all-entities';\n\nclass PasswordlessBusinessApplication extends EditableBusiness {\n @Column()\n @IsIn(['individual', 'company'])\n type!: 'individual' | 'company';\n\n @Column({ nullable: true })\n @IsOptional()\n @IsString()\n fein?: string;\n\n @Column({ nullable: true })\n @IsOptional()\n @IsString()\n professionalCertificationUrl?: string;\n}\n\n@Entity()\nexport default class BusinessApplication extends PasswordlessBusinessApplication {\n @PrimaryGeneratedColumn()\n id!: number;\n\n @CreateDateColumn()\n dateSubmitted!: Date;\n\n @Column()\n @IsString()\n passwordHash!: string;\n}\n\n/**\n * A business application sent by the client, which contains a password instead of a password hash.\n * Qualification objects do not require id or business.\n */\nexport class SendableBusinessApplication extends PasswordlessBusinessApplication {\n @IsString()\n password!: string;\n}\n```\n\n```text\n@Entity()\n```\n\n```text\nBusinessApplication\n```\n\n```text\nawait manager.find(BusinessApplication, ...)\n```\n\n```text\nawait manager.find('BusinessApplication', ...)\n```\n\n```text\ndatabase.ts\n```\n\n```text\nmanager.find(BusinessApplication, ...)\n```\n\n```text\nmanager.connection.entityMetadatas\n```\n\n```text\n.entity\n```\n\n```text\nexport const dataSource = new DataSource({\n ...\n ...\n entities: [BusinessApplication],\n ...\n ...\n})\n```\n\n========================================\n\nComments:\n- Can you please the code snippets of the solution? or some more detail about the solution?\n- @AkshayPethani What specifically are you wondering? All that had to be done was create new connections with different (randomly generated in my case) names rather than \"default\" and close them manually.","metadata":{"transformedAt":"2026-08-18T18:33:44.698Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":372,"estimatedTokens":3121}}182{"id":"stack-51583085","source":"stackoverflow","questionId":51583085,"title":"repository.save uses insert instead of update","tags":["typeorm"],"text":"Title: repository.save uses insert instead of update\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI am using TypeORM's repository pattern with a simple table, two columns, `estate_num` as primary key and `estateId` with mysql.\n\nThe `repository.save` method is supposed to insert if the record by primary key does not exist, otherwise, update it.\n\nInstead, I get the following error:\n\n```\nquery: SELECT `estate`.`estate_num` AS `estate_estate_num`, `estate`.`estateId` AS `estate_estateId` FROM `estate` `estate` WHERE (`estate`.`estate_num` = ?) -- PARAMETERS: [\"0\"]\nquery: START TRANSACTION\nquery: INSERT INTO `estate`(`estate_num`, `estateId`) VALUES (?, ?) -- PARAMETERS: [\"0\",\"caae4e67796e4ac000743f009210fcb0467fdf87d0fbbf6107359cf53f5b544b79eefdfdd78f95d50301f20a9c3212cd3970af22b722e59313813e8c5d2732d0\"]\nquery failed: INSERT INTO `estate`(`estate_num`, `estateId`) VALUES (?, ?) -- PARAMETERS: [\"0\",\"caae4e67796e4ac000743f009210fcb0467fdf87d0fbbf6107359cf53f5b544b79eefdfdd78f95d50301f20a9c3212cd3970af22b722e59313813e8c5d2732d0\"]\nerror: { Error: ER_DUP_ENTRY: Duplicate entry '0' for key 'PRIMARY'\n```\n\nI can run the `SELECT` manually, which is what I think determines whether to insert vs update. It returns a row as I would expect with the matching `estate_num`.\n\nThe entity model for this is:\n\n```\n@Entity()\nexport class Estate {\n @PrimaryColumn({\n name: 'estate_num',\n })\n estateNum: number;\n\n @Column({\n name: 'estateId',\n })\n estateId: string;\n}\n```\n\nNote: the `estate_num` is *not* auto-increment, the key will be always supplied. It is odd, I understand.\n\nThanks!\n\n========================================\n\nTop Answer:\nI had the same problem. I was doing it wrong.\n\nBefore I was doing it multiple ways, but in the wrong way. \n\nFirst I was doing it like this: \n\n```\nconst user = User.create({ id: 1, username: \"newName\" })\n\nuser.save();\n```\n\ngiving me an error of `ID Duplicate Entry` \n\nSecond I was doing it like this:\n\n```\nconst user = User.create({ id: 1, username: \"newName\" })\n\nUser.save(user);\n```\n\nsame error, Duplicate Entry.\n\nThird I was doing it like this:\n\n```\nconst user = User.findOneOrFaile(1);\nconst newUser = { ...user, ..req.body }\nUser.save(newUser);\n```\n\nsame error.\n\nAnd I just got helped and It should be done like this. You need to get the instance and merged it using `Object.assign()`\n\n```\ntry {\n const user: User = await User.findOneOrFail(id);\n Object.assign(user, { ...req.body }); <---- SO ITS LIKE THIS\n await user.save();\n res.json({\n meta: {},\n payload: {\n ...req.body\n }\n });\n } catch (error) {\n logger.error(error);\n res.status(404).json({\n error\n });\n }\n```\n\n========================================\n\nCode:\n```text\nquery: SELECT `estate`.`estate_num` AS `estate_estate_num`, `estate`.`estateId` AS `estate_estateId` FROM `estate` `estate` WHERE (`estate`.`estate_num` = ?) -- PARAMETERS: [\"0\"]\nquery: START TRANSACTION\nquery: INSERT INTO `estate`(`estate_num`, `estateId`) VALUES (?, ?) -- PARAMETERS: [\"0\",\"caae4e67796e4ac000743f009210fcb0467fdf87d0fbbf6107359cf53f5b544b79eefdfdd78f95d50301f20a9c3212cd3970af22b722e59313813e8c5d2732d0\"]\nquery failed: INSERT INTO `estate`(`estate_num`, `estateId`) VALUES (?, ?) -- PARAMETERS: [\"0\",\"caae4e67796e4ac000743f009210fcb0467fdf87d0fbbf6107359cf53f5b544b79eefdfdd78f95d50301f20a9c3212cd3970af22b722e59313813e8c5d2732d0\"]\nerror: { Error: ER_DUP_ENTRY: Duplicate entry '0' for key 'PRIMARY'\n```\n\n```text\n@Entity()\nexport class Estate {\n @PrimaryColumn({\n name: 'estate_num',\n })\n estateNum: number;\n\n @Column({\n name: 'estateId',\n })\n estateId: string;\n}\n```\n\n```text\nestate_num\n```\n\n```text\nestateId\n```\n\n```text\nrepository.save\n```\n\n```text\nSELECT\n```\n\n```text\nestate_num\n```\n\n```text\nestate_num\n```\n\n```text\n-- PARAMETERS: [\"0\"]\n```\n\n```text\nEstate\n```\n\n```text\nestateNum\n```\n\n```text\nnumber\n```\n\n```text\nrepository.save\n```\n\n```text\nimport 'reflect-metadata';\nimport { createConnection } from 'typeorm';\nimport { Estate } from './entity/Estate';\n\ncreateConnection().then(async connection => {\n const estate = new Estate();\n estate.estateNum = 0;\n estate.estateId = 'alpha';\n\n await connection.getRepository(Estate).save(estate);\n\n estate.estateId = 'beta';\n\n await connection.getRepository(Estate).save(estate);\n});\n```\n\n```text\nquery: SELECT \"Estate\".\"estate_num\" AS \"Estate_estate_num\", \"Estate\".\"estateId\" AS \n\"Estate_estateId\" FROM \"estate\" \"Estate\" WHERE (\"Estate\".\"estate_num\" = ?) -- \nPARAMETERS: [0]\nquery: BEGIN TRANSACTION\nquery: INSERT INTO \"estate\"(\"estate_num\", \"estateId\") VALUES (?, ?) -- PARAMETERS: \n[0,\"alpha\"]\nquery: COMMIT\nquery: SELECT \"Estate\".\"estate_num\" AS \"Estate_estate_num\", \"Estate\".\"estateId\" AS \n\"Estate_estateId\" FROM \"estate\" \"Estate\" WHERE (\"Estate\".\"estate_num\" = ?) -- \nPARAMETERS: [0]\nquery: BEGIN TRANSACTION\nquery: UPDATE \"estate\" SET \"estateId\" = ? WHERE \"estate_num\" = ? -- PARAMETERS: \n[\"beta\",0]\nquery: COMMIT\n```\n\n```text\nconst user = User.create({ id: 1, username: \"newName\" })\n\nuser.save();\n```\n\n```text\nconst user = User.create({ id: 1, username: \"newName\" })\n\nUser.save(user);\n```\n\n```text\nconst user = User.findOneOrFaile(1);\nconst newUser = { ...user, ..req.body }\nUser.save(newUser);\n```\n\n```text\ntry {\n const user: User = await User.findOneOrFail(id);\n Object.assign(user, { ...req.body }); <---- SO ITS LIKE THIS\n await user.save();\n res.json({\n meta: {},\n payload: {\n ...req.body\n }\n });\n } catch (error) {\n logger.error(error);\n res.status(404).json({\n error\n });\n }\n```\n\n```text\nID Duplicate Entry\n```\n\n```text\nObject.assign()\n```\n\n========================================\n\nComments:\n- you definitely do something wrong. try to test things on a minimal code, check the input before you give it to `save` method.\n- @Ryan Rampersad do you have a solution for this? I have the same problem. I tried the create() method and supplied it with the id it throws a duplicate error when even though I supplied an ID for it to update and not save. This giving me a head ache","metadata":{"transformedAt":"2026-08-18T18:33:44.698Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":255,"estimatedTokens":1508}}183{"id":"stack-53638949","source":"stackoverflow","questionId":53638949,"title":"Typeorm connection terminated","tags":["node.js","postgresql","typeorm"],"text":"Title: Typeorm connection terminated\nTags: node.js, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am using Typeorm with a postgresql database. I am testing a function that runs a findOne query and it throws the following error:\n\n```\n{ QueryFailedError: Connection terminated\n at new QueryFailedError (/Users/juanjosegutierrez/projects/banking-server/node_modules/typeorm/error/QueryFailedError.js:27:28)\n at Query.callback (/Users/juanjosegutierrez/projects/banking-server/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:212:38)\n at Query.Object..Query.handleError (/Users/juanjosegutierrez/projects/banking-server/node_modules/pg/lib/query.js:142:17)\n at process.nextTick (/Users/juanjosegutierrez/projects/banking-server/node_modules/pg/lib/client.js:59:13)\n at process._tickCallback (internal/process/next_tick.js:61:11)\n message: 'Connection terminated',\n name: 'QueryFailedError',\n query:\n 'SELECT \"Contact\".\"id\" AS \"Contact_id\", \"Contact\".\"type\" AS \"Contact_type\" FROM \"contacts\" \"Contact\" WHERE \"Contact\".\"id\" = $1',\n parameters: [ '52e1da6e-f4e1-41dc-9dcd-22679c4265e4' ] }\n```\n\nWhen I look at my postgres logs I see the following:\n\n```\nLOG: unexpected EOF on client connection with an open transaction\n```\n\nWhy am I getting connection terminated?\n\n========================================\n\nCode:\n```text\n{ QueryFailedError: Connection terminated\n at new QueryFailedError (/Users/juanjosegutierrez/projects/banking-server/node_modules/typeorm/error/QueryFailedError.js:27:28)\n at Query.callback (/Users/juanjosegutierrez/projects/banking-server/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:212:38)\n at Query.Object.<anonymous>.Query.handleError (/Users/juanjosegutierrez/projects/banking-server/node_modules/pg/lib/query.js:142:17)\n at process.nextTick (/Users/juanjosegutierrez/projects/banking-server/node_modules/pg/lib/client.js:59:13)\n at process._tickCallback (internal/process/next_tick.js:61:11)\n message: 'Connection terminated',\n name: 'QueryFailedError',\n query:\n 'SELECT \"Contact\".\"id\" AS \"Contact_id\", \"Contact\".\"type\" AS \"Contact_type\" FROM \"contacts\" \"Contact\" WHERE \"Contact\".\"id\" = $1',\n parameters: [ '52e1da6e-f4e1-41dc-9dcd-22679c4265e4' ] }\n```\n\n```text\nLOG: unexpected EOF on client connection with an open transaction\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.698Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":49,"estimatedTokens":578}}184{"id":"stack-72344455","source":"stackoverflow","questionId":72344455,"title":"Create repository when EntityRepository is deprecated typeorm","tags":["nestjs","typeorm"],"text":"Title: Create repository when EntityRepository is deprecated typeorm\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI usually use this code to create a repository:\n\n```\nimport { EntityRepository, Repository } from 'typeorm'\nimport { User } from './user.entity'\n \n@EntityRepository(User)\nexport class UserRepository extends Repository {\n getInactiveUsers(): Promise {\n return this.createQueryBuilder()\n .where('isActive = :active', { active: false })\n .getMany()\n }\n}\n```\n\nHowever, now `EntityRepository` is deprecated. I found a reference but I think it's quite complex. I wonder if there is a simpler way to solve it?\n\n========================================\n\nTop Answer:\nfor the time being syntax below works for me:\n\n```\nconst queryBuilder = AppDataSource.getRepository(Post).createQueryBuilder(\"post\");\n```\n\nI hope this helps\n\nhttps://typeorm.io/select-query-builder#what-is-querybuilder\n\n========================================\n\nCode:\n```js\nimport { EntityRepository, Repository } from 'typeorm'\nimport { User } from './user.entity'\n \n@EntityRepository(User)\nexport class UserRepository extends Repository<User> {\n getInactiveUsers(): Promise<User[]> {\n return this.createQueryBuilder()\n .where('isActive = :active', { active: false })\n .getMany()\n }\n}\n```\n\n```text\nEntityRepository\n```\n\n```text\n\"typeorm\": \"0.2.45\",\n\"@nestjs/typeorm\": \"8.0.3\",\n```\n\n```text\nnpm i @nestjs/typeorm@8.0.3 typeorm@0.2.45\n```\n\n```text\nconst queryBuilder = AppDataSource.getRepository(Post).createQueryBuilder(\"post\");\n```\n\n========================================\n\nComments:\n- not working \"Property 'getRepository' does not exist on type 'typeof DataSource'\"\n- This is not possible when you have @nestjs/common in version 9.X as a dependency.","metadata":{"transformedAt":"2026-08-18T18:33:44.698Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":75,"estimatedTokens":439}}185{"id":"stack-57805787","source":"stackoverflow","questionId":57805787,"title":"TypeORM throws \"Type instantiation is excessively deep and possibly infinite.ts(2589)\" error on Repository typing","tags":["typescript","typescript-typings","typeorm","typescript-3.6"],"text":"Title: TypeORM throws \"Type instantiation is excessively deep and possibly infinite.ts(2589)\" error on Repository typing\nTags: typescript, typescript-typings, typeorm, typescript-3.6\nSource: Stack Overflow\n\nQuestion:\nAfter update to VSCode August 2019 (version 1.38) and Typescript 3.6 i'm getting a lot of `Type instantiation is excessively deep and possibly infinite.ts(2589)` on TypeORM repository initialization.\n\n```\nimport { Connection, Repository, Entity, BaseEntity, createConnection } from 'typeorm';\n\n@Entity()\nclass MyEntity extends BaseEntity {\n public id: number;\n}\n\nclass Test {\n async test() {\n const connection: Connection = await createConnection();\n const myRepo: Repository = connection.getRepository(MyEntity); // only here cast the error above\n }\n}\n```\n\nHow can I ignore or fix them?\n\n- VSCode v1.38.0 (user setup)\n\n- Node.js v10.11.0\n\n- Typescript v3.4.5\n\n- TypeORM v0.2.18\n\nI also noticed that the error is gone if the typing is removed `: Repository`\n\nThere also is the `\"Excessive stack depth comparing types 'FindConditions' and 'FindConditions'` error on the same line.\n\n========================================\n\nTop Answer:\n**Update** (23 September 2019):\n\nThis issue seems to have been fixed in Typescript version 3.6.3.\n\nSource: https://github.com/typeorm/typeorm/issues/3194#issuecomment-529911310\n\n========================================\n\nCode:\n```text\nimport { Connection, Repository, Entity, BaseEntity, createConnection } from 'typeorm';\n\n@Entity()\nclass MyEntity extends BaseEntity {\n public id: number;\n}\n\nclass Test {\n async test() {\n const connection: Connection = await createConnection();\n const myRepo: Repository<MyEntity> = connection.getRepository(MyEntity); // only here cast the error above\n }\n}\n```\n\n```text\nType instantiation is excessively deep and possibly infinite.ts(2589)\n```\n\n```text\n: Repository<MyEntity>\n```\n\n```text\n\"Excessive stack depth comparing types 'FindConditions<?>' and 'FindConditions<?>'\n```\n\n```text\n\"dependencies\": {\n ...\n \"typescript\": \"^3.0.3\"\n}\n```\n\n```text\n3.6\n```\n\n```text\npackage.json\n```\n\n```text\n3.6.x\n```\n\n```text\nnpm install typescript@3.4.3\n```\n\n```text\n.ts\n```\n\n```text\n^3.6.x\n```\n\n```text\n3.6.x\n```\n\n```text\n3.4.3\n```\n\n```text\n^3.4.x\n```\n\n```text\ntsc\n```\n\n```text\nnpm run build\n```\n\n```text\ntsc\n```\n\n```text\n{\n \"compilerOptions\": {\n ...\n \"skipLibCheck\": true,\n ...\n }\n}\n```\n\n```text\nskipLibCheck: true\n```\n\n```text\ntsconfig.json\n```\n\n========================================\n\nComments:\n- In addition to this issue (which I assume is yours), there's also this one and this one so it's safe to assume that this is indeed a bug.\n- Per the comments in the thread on that link, v3.6.3 does not solve the problem. If you find the TypeScript repo issues, it's still not fixed github.com/microsoft/TypeScript/issues/34933","metadata":{"transformedAt":"2026-08-18T18:33:44.698Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":155,"estimatedTokens":710}}186{"id":"stack-71548592","source":"stackoverflow","questionId":71548592,"title":"Nest JS & TypeORM cannot use findOne properly","tags":["javascript","nestjs","typeorm"],"text":"Title: Nest JS & TypeORM cannot use findOne properly\nTags: javascript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to get a user instance based on `id` (same happens for other attributes such as `email`. Inside the Service, this is my code:\n\n```\n@Injectable()\nexport class UserService {\n @InjectRepository(User)\n private readonly repository: Repository;\n\n async findOne(id: number): Promise {\n const user = await this.repository.findOne(id);\n return user;\n }\n}\n```\n\nand my User entity is:\n\n```\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ type: 'varchar', length: 120 })\n public name: string;\n\n @Column({ type: 'varchar', length: 120 })\n public email: string;\n}\n```\n\nThe problem is that I always get this error:\n`src/api/user/user.service.ts - error TS2559: Type 'number' has no properties in common with type 'FindOneOptions'.`\n\nOther methods such as `getAll` work just fine:\n\n```\npublic getAllUsers(): Promise {\n return this.repository.find();\n}\n```\n\n========================================\n\nTop Answer:\nThere are some breaking changes in `typeorm`. I wouldn't suggest downgrading, instead check the latest methods.\n\n`findOne(id);`\nis now changed to\n\n```\nfindOneBy({\nid: id // where id is your column name\n})\n```\n\nAnd `find()` is now\n\n```\nfind({\n select: {\n id: true,\n email: true,\n password: true,\n },\n});\n```\n\nPlease check this link for more information.\n\n========================================\n\nCode:\n```js\n@Injectable()\nexport class UserService {\n @InjectRepository(User)\n private readonly repository: Repository<User>;\n\n async findOne(id: number): Promise<User> {\n const user = await this.repository.findOne(id);\n return user;\n }\n}\n```\n\n```js\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ type: 'varchar', length: 120 })\n public name: string;\n\n @Column({ type: 'varchar', length: 120 })\n public email: string;\n}\n```\n\n```js\npublic getAllUsers(): Promise<User[]> {\n return this.repository.find();\n}\n```\n\n```text\nid\n```\n\n```text\nemail\n```\n\n```text\nsrc/api/user/user.service.ts - error TS2559: Type 'number' has no properties in common with type 'FindOneOptions<User>'.\n```\n\n```text\ngetAll\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeorm@0.2\n```\n\n```text\n@nestjs/typeorm@8.0\n```\n\n```text\ntypeorm@0.3\n```\n\n```text\npackage.json\n```\n\n```text\n\"typeorm\": \"^0.2.34\"\n```\n\n```text\nfindOneBy({\nid: id // where id is your column name\n})\n```\n\n```text\nfind({\n select: {\n id: true,\n email: true,\n password: true,\n },\n});\n```\n\n```text\ntypeorm\n```\n\n```text\nfindOne(id);\n```\n\n```text\nfind()\n```\n\n```text\nasync findOne(id: number): Promise<User> {\n const user = await this.repository.findOne({\n where: { id }\n });\n return user;\n}\n```\n\n```text\ntypeorm\n```\n\n```text\nfindOne\n```\n\n```text\nconst user = await userRepository.findOneBy({\n id: id // where id is your column name\n})\n```\n\n========================================\n\nComments:\n- I think this should be the correct answer. The approach is mentioned in the change log typeorm.io/changelog#features-4\n- What if I have nested entity. Something like- `select: { client: { user: true } }` This thing does not work in latest version. Is there any solution?\n- @Srk95 I think you need to use the `where` in the docs github.com/typeorm/typeorm/releases/tag/0.3.0. For example `userRepository.find({ where: { photos: { album: { name: \"profile\" } } } })`\n- @SananAli `select` clause and `where` clause are different. I want to have the nested structure under `select` clause.","metadata":{"transformedAt":"2026-08-18T18:33:44.698Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":209,"estimatedTokens":889}}187{"id":"stack-49463691","source":"stackoverflow","questionId":49463691,"title":"TypeORM column type dependant on database","tags":["mysql","node.js","sqlite","typescript","typeorm"],"text":"Title: TypeORM column type dependant on database\nTags: mysql, node.js, sqlite, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have simple entity\n\n```\n@Entity()\nexport class File {\n @PrimaryGeneratedColumn()\n id: number;\n @Column({type: \"mediumblob\"})\n data: Buffer;\n}\n```\n\nWhich I want to use on production with Mysql (\"mediumblob\" because I want to store 10MB files).\n\nI also want to run integration tests but with `sqlite` but it supports only \"blob\". \n\nThen I want test like that:\n\n```\ndescribe(\"CR on File and blobs\", () => {\n it(\"should store arbitrary binary file\", async (done) => {\n const conn = await createConnection({\n type: \"sqlite\",\n database: \":memory:\",\n entities: [\"src/models/file.ts\"],\n synchronize: true\n });\n const fileRepo = await conn.getRepository(File);\n fileRepo.createQueryBuilder(\"file\")\n .where(\"file.id == :id\", {id: 1})\n .select([\n \"file.data\"\n ])\n .stream();\n done();\n });\n});\n```\n\nWhen I run such code I get error like this\n`DataTypeNotSupportedError: Data type \"mediumblob\" in \"File.data\" is not supported by \"sqlite\" database.`\n\nIf I change column type to `blob` then for `mysql` I get following error when uploading `116kb` file \n`QueryFailedError: ER_DATA_TOO_LONG: Data too long for column 'data' at row 1`\n\nIs it somehow possible to generate some kind of logic/mapping to work arround incompatibility of `mysql`/`sqlite` so `\"blob\"` is used for `sqlite` while `\"mediumblob\"` is used for `mysql`?\n\n========================================\n\nTop Answer:\nI run into a similar problem. I'm using Postgres and wanted to use SQLite for unit tests.\n\n@Hung's answer was basically what I was looking for.\n\nHowever, I am using JSON types alongside default values so I had to add some improvements there.\n\nI'm posting it here to with you and I hope it will be useful to somebody else.\n\n```\nconst Env = {isTest: process.env.NODE_ENV === 'test'};\n\nfunction resolveType(type: ColumnType): ColumnType {\n if (!Env.isTest) return type;\n\n if (type === 'timestamp') return 'datetime';\n if (type === 'mediumblob') return 'blob';\n if (type === 'mediumtext') return 'text';\n if (type === 'jsonb') return 'text';\n if (type === 'json') return 'text';\n if (type === 'enum') return 'text';\n if (type === 'uuid') return 'text';\n\n return type;\n}\n\nfunction resolveDefault(defaultValue: unknown): any {\n if (!Env.isTest) return defaultValue;\n\n const whitelist = ['string', 'number'];\n const type = typeof defaultValue;\n if (!whitelist.includes(type)) return JSON.stringify(defaultValue);\n\n return defaultValue;\n}\n\nexport function EnvSpecificDecoratorValue(options: ColumnOptions) {\n if (options.type) options.type = resolveType(options.type);\n if (options.default) options.default = resolveDefault(options.default);\n\n return options;\n}\n\nimport { ColumnOptions, Column as OriginalColumn } from 'typeorm';\nimport { UpdateDateColumn as OriginalUpdateDateColumn } from 'typeorm';\nimport { CreateDateColumn as OriginalCreateDateColumn } from 'typeorm';\n\nexport function Column(columnOptions: ColumnOptions) {\n return OriginalColumn(EnvSpecificDecoratorValue(columnOptions));\n}\n\nexport function CreateDateColumn(columnOptions: ColumnOptions) {\n return OriginalCreateDateColumn(EnvSpecificDecoratorValue(columnOptions));\n}\n\nexport function UpdateDateColumn(columnOptions: ColumnOptions) {\n return OriginalUpdateDateColumn(EnvSpecificDecoratorValue(columnOptions));\n}\n```\n\nNow you can reference `Column`, `CreateDateColumn`, `UpdateDateColumn` as it was the original decorator but imported from your local file.\n\n========================================\n\nCode:\n```js\n@Entity()\nexport class File {\n @PrimaryGeneratedColumn()\n id: number;\n @Column({type: \"mediumblob\"})\n data: Buffer;\n}\n```\n\n```js\ndescribe(\"CR on File and blobs\", () => {\n it(\"should store arbitrary binary file\", async (done) => {\n const conn = await createConnection({\n type: \"sqlite\",\n database: \":memory:\",\n entities: [\"src/models/file.ts\"],\n synchronize: true\n });\n const fileRepo = await conn.getRepository(File);\n fileRepo.createQueryBuilder(\"file\")\n .where(\"file.id == :id\", {id: 1})\n .select([\n \"file.data\"\n ])\n .stream();\n done();\n });\n});\n```\n\n```text\nsqlite\n```\n\n```text\nDataTypeNotSupportedError: Data type \"mediumblob\" in \"File.data\" is not supported by \"sqlite\" database.\n```\n\n```text\nblob\n```\n\n```text\nmysql\n```\n\n```text\n116kb\n```\n\n```text\nQueryFailedError: ER_DATA_TOO_LONG: Data too long for column 'data' at row 1\n```\n\n```text\nmysql\n```\n\n```text\nsqlite\n```\n\n```text\n\"blob\"\n```\n\n```text\nsqlite\n```\n\n```text\n\"mediumblob\"\n```\n\n```text\nmysql\n```\n\n```text\nimport { Column, ColumnOptions, ColumnType } from 'typeorm';\n\nconst mysqlSqliteTypeMapping: { [key: string]: ColumnType } = {\n 'mediumtext': 'text',\n 'timestamp': 'datetime',\n 'mediumblob': 'blob'\n};\n\nexport function resolveDbType(mySqlType: ColumnType): ColumnType {\n const isTestEnv = process.env.NODE_ENV === 'test';\n if (isTestEnv && mySqlType in mysqlSqliteTypeMapping) {\n return mysqlSqliteTypeMapping[mySqlType.toString()];\n }\n return mySqlType;\n}\n\nexport function DbAwareColumn(columnOptions: ColumnOptions) {\n if (columnOptions.type) {\n columnOptions.type = resolveDbType(columnOptions.type);\n }\n return Column(columnOptions);\n}\n```\n\n```text\n@Entity({name: 'document'})\nexport class Document {\n\n @DbAwareColumn({ name: 'body', type: 'mediumtext'})\n body: string;\n\n @DbAwareColumn({type: \"mediumblob\"})\n data: Buffer;\n\n @DbAwareColumn({type: \"timestamp\"})\n createdAt: Date;\n}\n```\n\n```js\nconst Env = {isTest: process.env.NODE_ENV === 'test'};\n\nfunction resolveType(type: ColumnType): ColumnType {\n if (!Env.isTest) return type;\n\n if (type === 'timestamp') return 'datetime';\n if (type === 'mediumblob') return 'blob';\n if (type === 'mediumtext') return 'text';\n if (type === 'jsonb') return 'text';\n if (type === 'json') return 'text';\n if (type === 'enum') return 'text';\n if (type === 'uuid') return 'text';\n\n return type;\n}\n\nfunction resolveDefault(defaultValue: unknown): any {\n if (!Env.isTest) return defaultValue;\n\n const whitelist = ['string', 'number'];\n const type = typeof defaultValue;\n if (!whitelist.includes(type)) return JSON.stringify(defaultValue);\n\n return defaultValue;\n}\n\nexport function EnvSpecificDecoratorValue(options: ColumnOptions) {\n if (options.type) options.type = resolveType(options.type);\n if (options.default) options.default = resolveDefault(options.default);\n\n return options;\n}\n\n\n\nimport { ColumnOptions, Column as OriginalColumn } from 'typeorm';\nimport { UpdateDateColumn as OriginalUpdateDateColumn } from 'typeorm';\nimport { CreateDateColumn as OriginalCreateDateColumn } from 'typeorm';\n\n\nexport function Column(columnOptions: ColumnOptions) {\n return OriginalColumn(EnvSpecificDecoratorValue(columnOptions));\n}\n\nexport function CreateDateColumn(columnOptions: ColumnOptions) {\n return OriginalCreateDateColumn(EnvSpecificDecoratorValue(columnOptions));\n}\n\nexport function UpdateDateColumn(columnOptions: ColumnOptions) {\n return OriginalUpdateDateColumn(EnvSpecificDecoratorValue(columnOptions));\n}\n```\n\n```text\nColumn\n```\n\n```text\nCreateDateColumn\n```\n\n```text\nUpdateDateColumn\n```\n\n========================================\n\nComments:\n- Yes, don't hard code the string `\"mediumblob\"`. Determine if you are running in test mode, however you normally do, and either set some shared configuration (using that) or change to a class factory approach.\n- Isn't typeorm supposed to be handling this kind of stuff? I want to use an ORM so I don't have to manually fiddle with db options when switching dbs....\n- How did you solve this ?\n- This worked great! One minor issue with the code above: `DbAwareColumn` references `setAppropriateDbType` but the function is named `setAppropriateColumnType`\n- this is genious! That's what I was looking for!","metadata":{"transformedAt":"2026-08-18T18:33:44.698Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":312,"estimatedTokens":1983}}188{"id":"stack-61136081","source":"stackoverflow","questionId":61136081,"title":"How to catch error in nestjs when a query fails","tags":["postgresql","nestjs","typeorm"],"text":"Title: How to catch error in nestjs when a query fails\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am new to `nestjs` and was trying to convert my backend from `nodejs` to `nestjs`. Hope that makes sense? I am using `typeorm. But I am not sure as what could be the best of way of catching errors.\n\n`entity.ts`\n\n```\nimport { Entity, Column, PrimaryGeneratedColumn, PrimaryColumn } from 'typeorm';\n\n@Entity()\nexport class Course {\n\n @PrimaryColumn()\n course: string;\n\n @Column(\"varchar\", { array: true })\n subject: string[];\n}\n```\n\n`controller.ts`\n\n```\nimport { Controller, Get, Post, Body } from '@nestjs/common';\nimport { CourseService } from './course.service';\nimport { Course } from './course.entity';\n\n@Controller('course')\nexport class CourseController {\n constructor(private courseService: CourseService) {}\n\n @Get()\n getCourses(): Promise {\n return this.courseService.findAll();\n }\n\n @Post()\n addCourse(@Body() courseDto: Course[]) {\n return this.courseService.create(courseDto);\n }\n}\n```\n\n`service.ts`\n\n```\nimport { Injectable, Catch, ExceptionFilter, ArgumentsHost, ConflictException } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository, QueryFailedError } from 'typeorm';\nimport { Course } from './course.entity';\n\n@Injectable()\nexport class CourseService {\n constructor(\n @InjectRepository(Course)\n private courseRepository: Repository,\n ) { }\n\n catch(exception: any, host: ArgumentsHost) {\n throw new Error(\"Error in course service.\" + exception.code);\n }\n\n findAll(): Promise {\n return this.courseRepository.find();\n }\n\n create(courseDto) {\n return this.courseRepository.insert(courseDto)\n .catch((err: any) => {\n // throw new ConflictException();\n\n switch (err.name) {\n case 'QueryFailedError':\n console.log(\"**++**\" + JSON.stringify(err));\n // throw new Error(\"Error\" + err.message + \"\" + err.detail);\n // throw new ConflictException();\n throw JSON.stringify(err); //\"Error creating a course\" + err.message + \"::: \" + err.detail;\n default:\n throw err; \n\n }\n });\n }\n}\n```\n\nNow, all I am able to throw is `throw new ConflictException();`. I wanted to throw different errors based on the result, like -\n1. For duplicate record\n2. Missing mandatory fields\n3. etc\n\nBut not sure how can we handle and customize the same and also make full use of nestjs.\n\nLike I see the below trace in console but `500, Internal server in postman` -\n\n```\n{\"message\":\"duplicate key value violates unique constraint \\\"PK_d7fc152bc721b3f55a56ed3ad33\\\"\",\"name\":\"QueryFailedError\",\"length\":293,\"severity\":\"ERROR\",\"code\":\"23505\",\"detail\":\"Key (course)=(II) already exists.\",\"schema\":\"public\",\"table\":\"course\",\"constraint\":\"PK_d7fc152bc721b3f55a56ed3ad33\",\"file\":\"d:\\\\pginstaller.auto\\\\postgres.windows-x64\\\\src\\\\backend\\\\access\\\\nbtree\\\\nbtinsert.c\",\"line\":\"535\",\"routine\":\"_bt_check_unique\",\"query\":\"INSERT INTO \\\"course\\\"(\\\"course\\\", \\\"subject\\\") VALUES ($1, $2)\",\"parameters\":[\"II\",[\"A\",\"B\",\"C\"]]}\n[Nest] 12152 - 04/10/2020, 1:18:40 PM [ExceptionsHandler] {\"message\":\"duplicate key value violates unique constraint \\\"PK_d7fc152bc721b3f55a56ed3ad33\\\"\",\"name\":\"QueryFailedError\",\"length\":293,\"severity\":\"ERROR\",\"code\":\"23505\",\"detail\":\"Key (course)=(II) already exists.\",\"schema\":\"public\",\"table\":\"course\",\"constraint\":\"PK_d7fc152bc721b3f55a56ed3ad33\",\"file\":\"d:\\\\pginstaller.auto\\\\postgres.windows-x64\\\\src\\\\backend\\\\access\\\\nbtree\\\\nbtinsert.c\",\"line\":\"535\",\"routine\":\"_bt_check_unique\",\"query\":\"INSERT INTO \\\"course\\\"(\\\"course\\\", \\\"subject\\\") VALUES ($1, $2)\",\"parameters\":[\"II\",[\"A\",\"B\",\"C\"]]} +190924ms\n```\n\n========================================\n\nTop Answer:\nDont return service function directly, nest will catch that exception and assume its from controller, another solution is wrap with try/catch\n\ncontroller.ts\n\n```\ntry {\n return await this.courseService.create(courseDto)\n} catch (error) {\n // handle error\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Entity, Column, PrimaryGeneratedColumn, PrimaryColumn } from 'typeorm';\n\n@Entity()\nexport class Course {\n\n @PrimaryColumn()\n course: string;\n\n @Column(\"varchar\", { array: true })\n subject: string[];\n}\n```\n\n```text\nimport { Controller, Get, Post, Body } from '@nestjs/common';\nimport { CourseService } from './course.service';\nimport { Course } from './course.entity';\n\n@Controller('course')\nexport class CourseController {\n constructor(private courseService: CourseService) {}\n\n @Get()\n getCourses(): Promise<Course[]> {\n return this.courseService.findAll();\n }\n\n @Post()\n addCourse(@Body() courseDto: Course[]) {\n return this.courseService.create(courseDto);\n }\n}\n```\n\n```text\nimport { Injectable, Catch, ExceptionFilter, ArgumentsHost, ConflictException } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository, QueryFailedError } from 'typeorm';\nimport { Course } from './course.entity';\n\n@Injectable()\nexport class CourseService {\n constructor(\n @InjectRepository(Course)\n private courseRepository: Repository<Course>,\n ) { }\n\n catch(exception: any, host: ArgumentsHost) {\n throw new Error(\"Error in course service.\" + exception.code);\n }\n\n findAll(): Promise<Course[]> {\n return this.courseRepository.find();\n }\n\n create(courseDto) {\n return this.courseRepository.insert(courseDto)\n .catch((err: any) => {\n // throw new ConflictException();\n\n switch (err.name) {\n case 'QueryFailedError':\n console.log(\"**++**\" + JSON.stringify(err));\n // throw new Error(\"Error\" + err.message + \"\" + err.detail);\n // throw new ConflictException();\n throw JSON.stringify(err); //\"Error creating a course\" + err.message + \"::: \" + err.detail;\n default:\n throw err; \n\n }\n });\n }\n}\n```\n\n```text\n{\"message\":\"duplicate key value violates unique constraint \\\"PK_d7fc152bc721b3f55a56ed3ad33\\\"\",\"name\":\"QueryFailedError\",\"length\":293,\"severity\":\"ERROR\",\"code\":\"23505\",\"detail\":\"Key (course)=(II) already exists.\",\"schema\":\"public\",\"table\":\"course\",\"constraint\":\"PK_d7fc152bc721b3f55a56ed3ad33\",\"file\":\"d:\\\\pginstaller.auto\\\\postgres.windows-x64\\\\src\\\\backend\\\\access\\\\nbtree\\\\nbtinsert.c\",\"line\":\"535\",\"routine\":\"_bt_check_unique\",\"query\":\"INSERT INTO \\\"course\\\"(\\\"course\\\", \\\"subject\\\") VALUES ($1, $2)\",\"parameters\":[\"II\",[\"A\",\"B\",\"C\"]]}\n[Nest] 12152 - 04/10/2020, 1:18:40 PM [ExceptionsHandler] {\"message\":\"duplicate key value violates unique constraint \\\"PK_d7fc152bc721b3f55a56ed3ad33\\\"\",\"name\":\"QueryFailedError\",\"length\":293,\"severity\":\"ERROR\",\"code\":\"23505\",\"detail\":\"Key (course)=(II) already exists.\",\"schema\":\"public\",\"table\":\"course\",\"constraint\":\"PK_d7fc152bc721b3f55a56ed3ad33\",\"file\":\"d:\\\\pginstaller.auto\\\\postgres.windows-x64\\\\src\\\\backend\\\\access\\\\nbtree\\\\nbtinsert.c\",\"line\":\"535\",\"routine\":\"_bt_check_unique\",\"query\":\"INSERT INTO \\\"course\\\"(\\\"course\\\", \\\"subject\\\") VALUES ($1, $2)\",\"parameters\":[\"II\",[\"A\",\"B\",\"C\"]]} +190924ms\n```\n\n```text\nnestjs\n```\n\n```text\nnodejs\n```\n\n```text\nnestjs\n```\n\n```text\nentity.ts\n```\n\n```text\ncontroller.ts\n```\n\n```text\nservice.ts\n```\n\n```text\nthrow new ConflictException();\n```\n\n```text\n500, Internal server in postman\n```\n\n```text\ncreate(courseDto) {\n return this.courseRepository.insert(courseDto)\n}\n```\n\n```text\nimport {\n Controller,\n Get,\n Post,\n HttpException,\n HttpStatus,\n} from '@nestjs/common';\n\n...\n\n@Post()\nasync addCourse(@Body() courseDto: Course[]) {\n return await this.courseService.create(courseDto).catch(err => {\n throw new HttpException({\n message: err.message\n }, HttpStatus.BAD_REQUEST);\n })\n}\n```\n\n```text\ntry {\n return await this.courseService.create(courseDto)\n} catch (error) {\n // handle error\n}\n```\n\n========================================\n\nComments:\n- What would be best, to let service handle it and controller handle it like you mentioned above?\n- From a design perspective I wouldn't support this solution. In hexagonal architecture an endpoint (ie. controller) is only **one** way to access your business layer. If you add a CLI command for your service or (staying in web context) a GraphQL resolver you would need to re-build all that error handling for each entry point. Better let the service layer handle the exceptions when they are crucial to the business. I.e. when the service require an entity to fetch/persist and it fails, let it fail.\n- @agoldev Totally agree with your statement, except if it's to return an HTTP-specific error (with a HTTP status code for example). Then in that case I would be OK with it (it would be incorrect to return it from the service), even though in Nest.js I'd prefer to see an exception filter so the code doesn't end up duplicated in every controller.\n- Thanks your post helped me indirectly, my problem was I didn't have the `await`.","metadata":{"transformedAt":"2026-08-18T18:33:44.698Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":276,"estimatedTokens":2247}}189{"id":"stack-67589835","source":"stackoverflow","questionId":67589835,"title":"TypeORM / NestJS - @BeforeUpdate hook not working","tags":["javascript","nestjs","typeorm","node.js-typeorm","nestjs-config"],"text":"Title: TypeORM / NestJS - @BeforeUpdate hook not working\nTags: javascript, nestjs, typeorm, node.js-typeorm, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nI'm having problems using TypeOrm hook \"BeforeUpdate\"\n\nI'm trying to update the user entity password, by passing a simple string and calling the save method to trigger the beforeUpdate hook and then hash the password, but this hook is not working while calling the save method.\n\nThis is what i have\n\n**user.service.ts**\n\n```\nasync update(id: number, updateUserDto: UpdateUserDto) {\n const roles =\n updateUserDto.roles &&\n (await Promise.all(\n updateUserDto.roles.map((name) => this.preloadRoleByName(name))\n ));\n const user = await this.userRepository.findOneOrFail(id);\n if (!user) {\n throw new NotFoundException(`User with ID #${id} not found`);\n }\n const toSaveUser = {\n ...user,\n ...updateUserDto,\n roles,\n };\n return await this.userRepository.save(toSaveUser);\n}\n```\n\n**user.entity.ts**\n\n```\n.\n.\n.\n@Column()\n@Exclude()\npassword: string;\n\n@BeforeInsert()\n@BeforeUpdate()\nprivate async hashPassword() {\n const rounds = 10;\n const salt = await bcrypt.genSalt(rounds);\n this.password = await bcrypt.hash(this.password, salt);\n}\n```\n\n**user.controller.ts**\n\n```\n@Patch(\":id\")\n@UseInterceptors(ClassSerializerInterceptor)\nasync update(@Param(\"id\") id: string, @Body() updateUserDto: UpdateUserDto) {\n return await this.usersService.update(+id, updateUserDto);\n}\n```\n\nWhat I'm doing wrong?\n\n`BeforeInsert` hook works or if I call `userRepository.preload()` method to update it works but it doesn't replace the relationship of the role, that's why I take this approach.\n\nAny ideas?\n\n========================================\n\nTop Answer:\nYou need to create DTO(Data Transfer Object) first and then update. this code is for update temporary password.\n\nHow create DTO:\n\n```\nthis..create()\n```\n\nExample:\n\n```\nasync updatePassword(id: number, tempPassword: string): Promise {\n let newUser = { tempPassword: tempPassword };\n const userDto = this.userAccountRepository.create(newUser)\n const userAccount = this.userAccountRepository.update(\n {\n userAccountId: id,\n },\n userDto \n );\n if (userAccount) {\n return true;\n } else {\n return false;\n }\n }\n```\n\nThis is my entity:\n\n```\nimport {\n BeforeInsert,\n BeforeUpdate,\n Column,\n Entity,\n JoinColumn,\n OneToMany,\n OneToOne,\n PrimaryColumn,\n } from 'typeorm';\nimport { Users } from '../users/users.entity';\nconst crypto = require('crypto');\n\n @Entity()\n export class UserAccount {\n @PrimaryColumn()\n userAccountId: number;\n @OneToOne(() => Users, { cascade: true })\n @JoinColumn({ name: 'userAccountId' })\n @Column({ nullable: true })\n tempPassword: string;\n @BeforeInsert()\n @BeforeUpdate()\n async hashPassword(): Promise {\n if (!!this.password) {\n this.password = crypto.createHmac('sha256', this.password).digest('hex');\n }\n if (!!this.tempPassword) {\n this.tempPassword = crypto\n .createHmac('sha256', this.tempPassword)\n .digest('hex');\n }\n }\n }\n```\n\n========================================\n\nCode:\n```js\nasync update(id: number, updateUserDto: UpdateUserDto) {\n const roles =\n updateUserDto.roles &&\n (await Promise.all(\n updateUserDto.roles.map((name) => this.preloadRoleByName(name))\n ));\n const user = await this.userRepository.findOneOrFail(id);\n if (!user) {\n throw new NotFoundException(`User with ID #${id} not found`);\n }\n const toSaveUser = {\n ...user,\n ...updateUserDto,\n roles,\n };\n return await this.userRepository.save(toSaveUser);\n}\n```\n\n```js\n.\n.\n.\n@Column()\n@Exclude()\npassword: string;\n\n@BeforeInsert()\n@BeforeUpdate()\nprivate async hashPassword() {\n const rounds = 10;\n const salt = await bcrypt.genSalt(rounds);\n this.password = await bcrypt.hash(this.password, salt);\n}\n```\n\n```js\n@Patch(\":id\")\n@UseInterceptors(ClassSerializerInterceptor)\nasync update(@Param(\"id\") id: string, @Body() updateUserDto: UpdateUserDto) {\n return await this.usersService.update(+id, updateUserDto);\n}\n```\n\n```text\nBeforeInsert\n```\n\n```text\nuserRepository.preload()\n```\n\n```text\nconst user = await this.userRepository.findOneOrFail(id); // entity instance\nconst toSaveUser = { ...user, ...updateUserDto, roles }; // plain object\nreturn await this.userRepository.save(toSaveUser); // not running trigger\n```\n\n```text\nconst user = await this.userRepository.findOneOrFail(id); // entity instance\n// still entity instance\nconst toSaveUser = this.userRepository.create({\n ...user,\n ...updateUserDto,\n roles,\n});\nreturn await this.userRepository.save(toSaveUser); // running trigger\n```\n\n```text\nProblem:\n```\n\n```text\nSolution:\n```\n\n```text\nrepository.save()\n```\n\n```text\nrepository.create()\n```\n\n```text\nrepository.preload()\n```\n\n```text\n@BeforeUpdate()\n async hashPasswordBeforeUpdate() {\n this.password = await bcrypt.hash(this.password, 10);\n }\n```\n\n```text\nquery: UPDATE `users` SET `levelId` = ?, `updatedAt` = ?, `password` = ? WHERE `id` IN (?) -- PARAMETERS: [null,\"2021-05-07T07:27:47.198Z\",\"$2b$10$uQOMNv57BZLB/W/9SWPbke6/OMdIDWxv3i25A8rUhA0/vEMloWb2W\",1]\n```\n\n```text\nPUT\n```\n\n```text\nPATCH\n```\n\n```js\nthis.<YOUR_REPOSITORY_NAME>.create(<INPUT_OBJECT>)\n```\n\n```js\nasync updatePassword(id: number, tempPassword: string): Promise<boolean> {\n let newUser = { tempPassword: tempPassword };\n const userDto = this.userAccountRepository.create(newUser)\n const userAccount = this.userAccountRepository.update(\n {\n userAccountId: id,\n },\n userDto \n );\n if (userAccount) {\n return true;\n } else {\n return false;\n }\n }\n```\n\n```js\nimport {\n BeforeInsert,\n BeforeUpdate,\n Column,\n Entity,\n JoinColumn,\n OneToMany,\n OneToOne,\n PrimaryColumn,\n } from 'typeorm';\nimport { Users } from '../users/users.entity';\nconst crypto = require('crypto');\n\n @Entity()\n export class UserAccount {\n @PrimaryColumn()\n userAccountId: number;\n @OneToOne(() => Users, { cascade: true })\n @JoinColumn({ name: 'userAccountId' })\n @Column({ nullable: true })\n tempPassword: string;\n @BeforeInsert()\n @BeforeUpdate()\n async hashPassword(): Promise<void> {\n if (!!this.password) {\n this.password = crypto.createHmac('sha256', this.password).digest('hex');\n }\n if (!!this.tempPassword) {\n this.tempPassword = crypto\n .createHmac('sha256', this.tempPassword)\n .digest('hex');\n }\n }\n }\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.698Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":308,"estimatedTokens":1596}}190{"id":"stack-46720962","source":"stackoverflow","questionId":46720962,"title":"TypeORM FindById doesn't work with MongoDB","tags":["mongodb","express","typeorm"],"text":"Title: TypeORM FindById doesn't work with MongoDB\nTags: mongodb, express, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use TypeORM with MongoDB and express but I'm having problems with the basic stuff.\n\nI just created a controller with basic CRUD operations for an entity. The methods save, findAll and find by Filter works ok, but I can't make the methods that require an mongo id work.\n\n```\nrouter.get(\"/\", async(req: Request, res: Response) => {\n const investmentRepository = getMongoRepository(Investment);\n\n const investments = await investmentRepository.find();\n res.send(investments);\n});\n\nrouter.get(\"/:id\", async(req: Request, res: Response) => {\n const investmentRepository = getMongoRepository(Investment);\n const investment = await \n investmentRepository.findOneById(req.params.id);\n if (!investment) {\n res.status(404);\n res.end();\n }\n res.send(investment);\n});\n```\n\nThe second method is always returning 404.\nFor example, this is an entity returned on get all \"investment/\"\n\n```\n{\n \"id\": \"59dfd8cadcbd9d1720457008\",\n \"name\": \"Teste LCI\",\n \"startDate\": 1466305200,\n \"numberOfDays\": 365,\n \"type\": \"LCI_LCA\"\n}\n```\n\nIf I try to send a request for this specific object calling \n\n investment/59dfd8cadcbd9d1720457008\n\nthe response is always 404.\n\nThe same behavior happen with the delete method, raising an exception\n\n Cannot find entity to remove by a given id\n\nI also tried to convert the string to ObjectID using:\n\n```\nnew ObjectID(req.params.id);\n```\n\nbut it fails with the error ObjectID is not a constructor.\n\n========================================\n\nTop Answer:\nIf you are importing from typeorm that might occur, you need to use:\n\n```\nimport { ObjectId } from 'mongodb'\n```\n\nHere is an example :\n\n```\nimport { Injectable, NotFoundException } from '@nestjs/common';\nimport { TaskStatus } from './task-status.enum';\nimport { CreateTaskDto} from './dto/create-task.dto';\nimport { GetTasksFilterDto } from './dto/get-tasks-filter.dto';\nimport { TaskRepository } from './dto/task.respository';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Task } from './entities/task.entity';\nimport { ObjectId} from 'mongodb';\n\n@Injectable()\nexport class TasksService {\n constructor(\n @InjectRepository(Task)\n private tasksRepository: TaskRepository\n )\n {}\n\n async getTaskById(id: ObjectId): Promise {\n console.log(`Finding task with id '${id}'`);\n const found = await this.tasksRepository.findOne({\n where: { _id: new ObjectId(id) }\n });\n\n console.log(found);\n if (!found) {\n throw new NotFoundException(`The task with '${id}' does not exist`);\n }\n return found;\n }\n```\n\n========================================\n\nCode:\n```text\nrouter.get(\"/\", async(req: Request, res: Response) => {\n const investmentRepository = getMongoRepository(Investment);\n\n const investments = await investmentRepository.find();\n res.send(investments);\n});\n\nrouter.get(\"/:id\", async(req: Request, res: Response) => {\n const investmentRepository = getMongoRepository(Investment);\n const investment = await \n investmentRepository.findOneById(req.params.id);\n if (!investment) {\n res.status(404);\n res.end();\n }\n res.send(investment);\n});\n```\n\n```text\n{\n \"id\": \"59dfd8cadcbd9d1720457008\",\n \"name\": \"Teste LCI\",\n \"startDate\": 1466305200,\n \"numberOfDays\": 365,\n \"type\": \"LCI_LCA\"\n}\n```\n\n```text\nnew ObjectID(req.params.id);\n```\n\n```text\nconst ObjectId = require('mongodb').ObjectId;\n```\n\n```js\nimport { ObjectId } from 'mongodb'\n```\n\n```js\nimport { Injectable, NotFoundException } from '@nestjs/common';\nimport { TaskStatus } from './task-status.enum';\nimport { CreateTaskDto} from './dto/create-task.dto';\nimport { GetTasksFilterDto } from './dto/get-tasks-filter.dto';\nimport { TaskRepository } from './dto/task.respository';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Task } from './entities/task.entity';\nimport { ObjectId} from 'mongodb';\n\n@Injectable()\nexport class TasksService {\n constructor(\n @InjectRepository(Task)\n private tasksRepository: TaskRepository\n )\n {}\n\n async getTaskById(id: ObjectId): Promise<Task> {\n console.log(`Finding task with id '${id}'`);\n const found = await this.tasksRepository.findOne({\n where: { _id: new ObjectId(id) }\n });\n\n console.log(found);\n if (!found) {\n throw new NotFoundException(`The task with '${id}' does not exist`);\n }\n return found;\n }\n```\n\n========================================\n\nComments:\n- Thanks, I could make it work importing mongodb. `import * as mongodb from \"mongodb\";` `new mongodb.ObjectId(req.params.id);` I don`t know why ObjectID from typeorm package doesnt work.\n- Because it's just `declare abstract class` for typings, not for runtime purpose. In new release you will be able to find by id which is hex string.\n- Hi, this is a different example; a better answer should adapt (or fix) the original code, Giving a totally different subject doesn't help much","metadata":{"transformedAt":"2026-08-18T18:33:44.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":186,"estimatedTokens":1235}}191{"id":"stack-56720054","source":"stackoverflow","questionId":56720054,"title":"How to initialize a TypeORM Repository based on a Generic Type \"T\"?","tags":["typescript","generics","typeorm"],"text":"Title: How to initialize a TypeORM Repository based on a Generic Type \"T\"?\nTags: typescript, generics, typeorm\nSource: Stack Overflow\n\nQuestion:\nI would like to Initiate a TypeORM Repository based on a Generic Type.\n\nfor instance:\n\n```\nimport { Connection, Repository } from 'typeorm';\n\nexport class GenericService {\n private repository: Repository;\n\n constructor(connection: Connection) {\n this.repository = connection.getRepository(T);\n // 'T' only refers to a type, but is being used as a value here.ts(2693)\n }\n\n public async list(): Promise {\n return await this.repository.find();\n }\n\n}\n```\n\nBut I was not able to pass Generic Type to the ORM Repository Factory.\n\n 'T' only refers to a type, but is being used as a value here.ts(2693\n\nHow can I create this generic service based on the Generic Type?\n\nPS. I did exactly this with C# and works like a charm. it saves me a lot of time\n\n========================================\n\nTop Answer:\nUsually I use`EntityTarget` type to avoid this error. The code looks like:\n\n```\nimport { Connection, Repository, EntityTarget } from 'typeorm';\n\nexport class GenericService {\n private repository: Repository;\n\n constructor(connection: Connection, repo: EntityTarget) {\n this.repository = connection.getRepository(repo);\n }\n\n public async list(): Promise {\n return await this.repository.find();\n }\n\n}\n```\n\n========================================\n\nCode:\n```text\nimport { Connection, Repository } from 'typeorm';\n\nexport class GenericService<T> {\n private repository: Repository<T>;\n\n constructor(connection: Connection) {\n this.repository = connection.getRepository(T);\n // 'T' only refers to a type, but is being used as a value here.ts(2693)\n }\n\n public async list(): Promise<T[]> {\n return await this.repository.find();\n }\n\n}\n```\n\n```text\nimport { Connection, Repository } from 'typeorm';\n \nexport class GenericService<T> {\n private repository: Repository<T>;\n \n constructor(connection: Connection, repo: T) {\n this.repository: T = connection.getRepository(repo);\n }\n \n public async list(): Promise<T[]> {\n return await this.repository.find();\n }\n \n}\n```\n\n```js\nimport { Connection, Repository, EntityTarget } from 'typeorm';\n\nexport class GenericService<T> {\n private repository: Repository<T>;\n\n constructor(connection: Connection, repo: EntityTarget<T>) {\n this.repository = connection.getRepository<T>(repo);\n }\n\n public async list(): Promise<T[]> {\n return await this.repository.find();\n }\n\n}\n```\n\n```text\nEntityTarget\n```\n\n```text\nexport class GenericService<T extends EntityTarget<ObjectLiteral>> {\n private entityManager: EntityManager;\n private repository: Repository<ObjectLiteral>;\n\n constructor(entity: T) {\n this.repository = this.entityManager.getRepository(entity);\n }\n\n public async list() {\n return await this.repository.find();\n }\n}\n```\n\n```text\n^0.3.17\n```\n\n```text\n5.1.3\n```\n\n```text\nConnection\n```\n\n```text\nEntity\n```\n\n```text\n<T>\n```\n\n```text\nlist()\n```\n\n```text\nPromise<ObjectLiteral[]>\n```\n\n```text\nPromise<T[]>\n```\n\n========================================\n\nComments:\n- You need to understand that TypeScript is not C#. TypeScripts eventually get transpiled into JavaScripts, and all the generics, types etc. are only there for the moment to help you making sure that your code is sound. Once transpiled, all those things are gone and you don't see them anywhere in the resulting JavaScript. So there is no `T`, and thus of course you cannot use it as a parameter. A workaround is provided by Yeysides below.\n- This is the best solution on current TypeORM version.","metadata":{"transformedAt":"2026-08-18T18:33:44.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":168,"estimatedTokens":913}}192{"id":"stack-54163467","source":"stackoverflow","questionId":54163467,"title":"How to access relationship ID from Parent's joined field in NestJS/TypeORM","tags":["node.js","graphql","nestjs","typeorm"],"text":"Title: How to access relationship ID from Parent's joined field in NestJS/TypeORM\nTags: node.js, graphql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm setting up a NestJS GraphQL API that utilizes TypeORM, and am having trouble implementing relationships between entities.\n\nSpecifically, the TypeORM relationships are working great, and the entities are linking correctly in the database. However, the problem comes in when I try to query the API to get the results.\n\nRight now I have 2 entities, each with their own resolver: Users and Photos. Each User can have multiple Photos, while each Photo is only connected to one User (Many-to-One).\n\n### Here's how the entities are linked with TypeORM\n\n*Photo Entity, with a relationship to the User Entity*\n\n```\n@ManyToOne(type => User, user => user.photos, {\n onDelete: 'CASCADE',\n})\n@JoinColumn()\nuser: User;\n```\n\n*User Entity, completing connection to the Photo Entity*\n\n```\n@OneToMany(type => Photo, photo => photo.user, {\n eager: true,\n})\nphotos: Photo[];\n```\n\n### This code works, and let's us retrieve a User's Photos\n\n*User resolver*\n\n```\n@ResolveProperty('photos')\nasync photos(@Parent() user): Promise {\n return await this.service.readPhotos(user.id);\n}\n```\n\n*User service*\n\n```\nasync readPhotos(userId): Promise {\n return await this.photoRepository.find({\n where: {\n user: userId\n }\n });\n}\n```\n\n*** *Note that the photoRepository is able to be filtered by the 'user' field.* ***\n\n### This code, however, does not work. It should let us view which User is connected to the Photo, instead it returns null.\n\n*Photo resolver*\n\n```\n@ResolveProperty('user')\nasync user(@Parent() photo): Promise {\n console.log(photo);\n return await this.service.readUser(photo.user);\n}\n```\n\nThis Photo resolver seems to contain the problem; the photo object being output by the console indicates that while the @Parent photo object has all of its static fields available (like the ID, datePublished, URL), for some reason the actual 'user' field is not accessible here. So the 'photo.user' variable is null.\n*** *Note that this seems to indicated that the photoRepository is UNABLE to be filtered by/access the 'user' field.* ***\n\n*Photo service*\n\n```\nasync readUser(userId): Promise {\n return await this.userRepository.findOne({\n where: {\n user: userId\n }\n });\n}\n```\n\nThis returns null since the userId is blank, due to the previous Photo resolver not being able to access the 'user' field.\n\n### Conclusion\n\nWhy can't the Photo resolver access the @Parent photo 'user' field? The User service seems to be able to filter by the 'user' field just fine, yet I can't seem to be able to access the Photo 'user' field directly.\n\nThank you for any help on this! I've been stumped on this for the last two days...\n\n========================================\n\nTop Answer:\nI was struggling with a similar problem and although @bashleigh's solution works if you want the entire entity returned I only needed the id. So if that's your case you can pass the `loadRelationIds` option, and set it to `true`.\n\n```\nreturn await this.photoRepository.find({\n where: {\n id: photoId\n },\n loadRelationIds: true\n});\n```\n\nThis will return user as just the id (string or int).\n\n========================================\n\nCode:\n```text\n@ManyToOne(type => User, user => user.photos, {\n onDelete: 'CASCADE',\n})\n@JoinColumn()\nuser: User;\n```\n\n```text\n@OneToMany(type => Photo, photo => photo.user, {\n eager: true,\n})\nphotos: Photo[];\n```\n\n```text\n@ResolveProperty('photos')\nasync photos(@Parent() user): Promise<Photo[]> {\n return await this.service.readPhotos(user.id);\n}\n```\n\n```text\nasync readPhotos(userId): Promise<Photo[]> {\n return await this.photoRepository.find({\n where: {\n user: userId\n }\n });\n}\n```\n\n```text\n@ResolveProperty('user')\nasync user(@Parent() photo): Promise<User> {\n console.log(photo);\n return await this.service.readUser(photo.user);\n}\n```\n\n```text\nasync readUser(userId): Promise<User> {\n return await this.userRepository.findOne({\n where: {\n user: userId\n }\n });\n}\n```\n\n```text\nasync readPhotos(userId): Promise<Photo[]> {\n return await this.photoRepository.find({\n where: {\n user: userId\n },\n relations: ['user'],\n });\n}\n```\n\n```text\nasync readUser(userId): Promise<User> {\n return await this.userRepository.findOne({\n where: {\n user: userId\n },\n relations: ['photos'],\n });\n}\n```\n\n```text\nphoto.user\n```\n\n```text\nFindOptions\n```\n\n```text\nphoto.user\n```\n\n```text\nuser.photos\n```\n\n```text\nPhoto\n```\n\n```text\nFindOptions\n```\n\n```text\nreturn await this.photoRepository.find({\n where: {\n id: photoId\n },\n loadRelationIds: true\n});\n```\n\n```text\nloadRelationIds\n```\n\n```text\ntrue\n```\n\n========================================\n\nComments:\n- Can you your GraphQL schema as well? Specifically the definitions for your Photo and User","metadata":{"transformedAt":"2026-08-18T18:33:44.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":228,"estimatedTokens":1229}}193{"id":"stack-70179506","source":"stackoverflow","questionId":70179506,"title":"TypeORM: What is the difference between getRawMany() and getMany()?","tags":["typeorm","node.js-typeorm"],"text":"Title: TypeORM: What is the difference between getRawMany() and getMany()?\nTags: typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nI have this code:\n\n```\nlet otherParticipants = await chatRoomParticipantRepo\n .createQueryBuilder(\"chatRoomParticipant\")\n .leftJoinAndSelect(\"chatRoomParticipant.user\", \"user\")\n .select(\"user.connectionId\")\n .where(\"chatRoomParticipant.chatRoomId = :chatRoomId AND chatRoomParticipant.userId != :userId\")\n .setParameters({ chatRoomId: chatRoomId, userId: userId })\n .getRawMany();\n```\n\nWhich gives me this result:\n\n```\n[{user_connectionId: 's7p7bUbzt0wudKcxAAAD'}]\n```\n\nIf I do it with `getMany()` it gives me empty array:\n\n```\n[]\n```\n\nI am trying to get the `ID` from `user` which connected to `chatRoomParticipant`, but I cannot do it with this code:\n\n```\nlet otherParticipants = await chatRoomParticipantRepo\n .createQueryBuilder(\"chatRoomParticipant\")\n .leftJoinAndSelect(\"chatRoomParticipant.user\", \"user\")\n .select(\"user.connectionId\")\n .where(\"chatRoomParticipant.chatRoomId = :chatRoomId AND chatRoomParticipant.userId != :userId\")\n .setParameters({ chatRoomId: chatRoomId, userId: userId })\n .getMany(); Why is this happening? I thought `getRawMany()` is just for `SUM, COUNT, etc`. In this case I am trying to get the ID which should work with `getMany()` as well?\n\n========================================\n\nTop Answer:\nThere are two types of results you can get using select query builder: entities and raw results. Most of the time, you need to select real entities from your database, for example, users. For this purpose, you use getOne and getMany. However, sometimes you need to select specific data, like the sum of all user photos. Such data is not a entity, it's called raw data. To get raw data, you use getRawOne and getRawMany.\n\n- refer to Typeorm documentation.\n\nHope it is helpful for you\n\n========================================\n\nCode:\n```text\nlet otherParticipants = await chatRoomParticipantRepo\n .createQueryBuilder(\"chatRoomParticipant\")\n .leftJoinAndSelect(\"chatRoomParticipant.user\", \"user\")\n .select(\"user.connectionId\")\n .where(\"chatRoomParticipant.chatRoomId = :chatRoomId AND chatRoomParticipant.userId != :userId\")\n .setParameters({ chatRoomId: chatRoomId, userId: userId })\n .getRawMany();\n```\n\n```text\n[{user_connectionId: 's7p7bUbzt0wudKcxAAAD'}]\n```\n\n```text\n[]\n```\n\n```text\nlet otherParticipants = await chatRoomParticipantRepo\n .createQueryBuilder(\"chatRoomParticipant\")\n .leftJoinAndSelect(\"chatRoomParticipant.user\", \"user\")\n .select(\"user.connectionId\")\n .where(\"chatRoomParticipant.chatRoomId = :chatRoomId AND chatRoomParticipant.userId != :userId\")\n .setParameters({ chatRoomId: chatRoomId, userId: userId })\n .getMany(); <-- This gives nothing\n```\n\n```text\ngetMany()\n```\n\n```text\nID\n```\n\n```text\nuser\n```\n\n```text\nchatRoomParticipant\n```\n\n```text\ngetRawMany()\n```\n\n```text\nSUM, COUNT, etc\n```\n\n```text\ngetMany()\n```\n\n```text\ngetRawMany()\n```\n\n```text\ngetMany()\n```\n\n```text\n.leftJoinAndSelect(\"chatRoomParticipant.user\", \"user\")\n.select(\"user.connectionId\")\n```\n\n```text\n.select(\"user.connectionId\", \"connectionId\")\n.addSelect(\"dep.branchName\", \"branchName\")\n```\n\n========================================\n\nComments:\n- @Musilix it means that the `getMany()` return the list entities ( in a basic way the columns you defined in the entity class )\n- man I'm having a hard time with this junk :/\n- What doesn't make sense to me is that a call to getMany() doesn't work when I'm trying to select ONLY the columns of entity B for an inner join between some Entity A and Entity B. When I try to select some columns of Entity B after an inner join of Entity A and B, I have to use getRawMany() in order to properly return the columns of Entity B that I need. Your explanation of getRawMany() and getMany() don't help clarify this issue at all sadly.","metadata":{"transformedAt":"2026-08-18T18:33:44.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":132,"estimatedTokens":967}}194{"id":"stack-58747303","source":"stackoverflow","questionId":58747303,"title":"How to cover TypeORM @Column decorator with Jest unit testing?","tags":["typescript","unit-testing","jestjs","nestjs","typeorm"],"text":"Title: How to cover TypeORM @Column decorator with Jest unit testing?\nTags: typescript, unit-testing, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to Unit and e2e test my applications as much as possible and my goal is a coverage of 101%. Problem right now with my setup is, that the @Column decorator from typeorm uses an arrow function to set a default value like the current timestamp on a database update. This arrow function is not covered with jest test coverage. Message is: `statement not covered`\n\nI run the code coverage with: `jest --coverage`.\nMy versions:\n\n```\n\"jest\": \"^24.9.0\",\n\"typeorm\": \"^0.2.20\"\n```\n\nJest configuration within package.json:\n\n```\n{\n \"jest\": {\n \"moduleFileExtensions\": [\n \"js\",\n \"json\",\n \"ts\"\n ],\n \"rootDir\": \"src\",\n \"testRegex\": \".spec.ts$\",\n \"transform\": {\n \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n },\n \"coverageDirectory\": \"../build/coverage\",\n \"testEnvironment\": \"node\",\n \"coverageThreshold\": {\n \"global\": {\n \"branches\": 80,\n \"functions\": 80,\n \"lines\": 80,\n \"statements\": -10\n }\n }\n },\n}\n```\n\nMy entity looks like this:\n\n```\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Role {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n tenantId: number;\n\n @Column({ type: 'timestamp', update: false, default: () => 'CURRENT_TIMESTAMP()' })\n createdAt: Date;\n\n @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP()', onUpdate: 'CURRENT_TIMESTAMP()' })\n updatedAt: Date;\n}\n```\n\nCoverage for this entity:\n\nhttps://i.sstatic.net/XSr5J.png\n\n========================================\n\nTop Answer:\nThis is the solution that worked for me, based off of @JayMcDoniel's answer.\n\n- database type: `postgreSQl`\n\n- testing: `jest/chai`\n\nFunctions class:\n\n```\nexport abstract class EntityDefaultFunctions {\n public static defaultNull = (): string => 'NULL';\n public static defaultZero = (): string => '0';\n }\n```\n\nTests:\n\n```\nexpect(EntityDefaultFunctions.defaultNull()).to.equal('NULL');\n expect(EntityDefaultFunctions.defaultZero()).to.equal('0');\n```\n\nExample Entity Column definition:\n\n```\n@Column('text', {\n default: EntityDefaultFunctions.defaultNull,\n name: 'somePropertyName'\n })\n```\n\n========================================\n\nCode:\n```text\n\"jest\": \"^24.9.0\",\n\"typeorm\": \"^0.2.20\"\n```\n\n```json\n{\n \"jest\": {\n \"moduleFileExtensions\": [\n \"js\",\n \"json\",\n \"ts\"\n ],\n \"rootDir\": \"src\",\n \"testRegex\": \".spec.ts$\",\n \"transform\": {\n \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n },\n \"coverageDirectory\": \"../build/coverage\",\n \"testEnvironment\": \"node\",\n \"coverageThreshold\": {\n \"global\": {\n \"branches\": 80,\n \"functions\": 80,\n \"lines\": 80,\n \"statements\": -10\n }\n }\n },\n}\n```\n\n```js\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Role {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n tenantId: number;\n\n @Column({ type: 'timestamp', update: false, default: () => 'CURRENT_TIMESTAMP()' })\n createdAt: Date;\n\n @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP()', onUpdate: 'CURRENT_TIMESTAMP()' })\n updatedAt: Date;\n}\n```\n\n```text\nstatement not covered\n```\n\n```text\njest --coverage\n```\n\n```js\nexport const returnString = () => String;\n\n@Query(returnString)\n```\n\n```js\nexpect(returnString()).toBe(String);\n```\n\n```text\nexpect(namedFunction).toBe('CURRENT_TIMESTAMP()')\n```\n\n```text\nexport abstract class EntityDefaultFunctions {\n public static defaultNull = (): string => 'NULL';\n public static defaultZero = (): string => '0';\n }\n```\n\n```text\nexpect(EntityDefaultFunctions.defaultNull()).to.equal('NULL');\n expect(EntityDefaultFunctions.defaultZero()).to.equal('0');\n```\n\n```text\n@Column('text', {\n default: EntityDefaultFunctions.defaultNull,\n name: 'somePropertyName'\n })\n```\n\n```text\npostgreSQl\n```\n\n```text\njest/chai\n```\n\n========================================\n\nComments:\n- You are the hero we need in these dark times.\n- Amazing. Coverage is 100% now without those annoying \"ignore\" comments <3\n- Only problem left is the missing return type of those newly created functions. E.g.: `export const returnString = () => String;` I can't provide `: String` as return type because it moans about missing methods of type *StringConstructor*\n- You should still be able to do something like `expect(returnString()).toBe(String)`. I've got that running in my test classes without a problem\n- Thanks for the updates @JayMcDoniel. This was enough to get me to a solution that worked for my case.","metadata":{"transformedAt":"2026-08-18T18:33:44.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":214,"estimatedTokens":1135}}195{"id":"stack-66086508","source":"stackoverflow","questionId":66086508,"title":"NestJS [TypeOrmModule] Unable to connect to the database","tags":["postgresql","nestjs","typeorm"],"text":"Title: NestJS [TypeOrmModule] Unable to connect to the database\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to connect to a remote PostgreSQL database (which is being hosted on Heroku) and getting this error:\n\n```\nerror: no pg_hba.conf entry for host \"\", user \"\", database \"\", SSL off\n```\n\nHere's my `app.module.ts`\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nconst cfg: TypeOrmModuleOptions = {\n type: 'postgres',\n host: process.env.DB_HOST,\n database: process.env.DB_NAME,\n username: process.env.DB_USER,\n password: process.env.DB_PASSWORD,\n port: Number(process.env.DB_PORT),\n};\n\n@Module({\n imports: [TypeOrmModule.forRoot(cfg)],\n})\nexport class AppModule {}\n```\n\nEvery `DB_*` variable matches corresponding values in Heroku's `Database Credentials`\n\nI think that the problem is somewhere in `TypeORM`, because connecting to the same DB with the same `.env` file values worked in my other application (written in different programming language)\n\nAny ideas on what could be wrong?\n\n========================================\n\nTop Answer:\nI got the same error and looks like the same dev environment as you.\n\nin my case, I resolved the error from this Heloku Postgres Connecting in Node.js\n\nI chose the alternative way to omit the ssl configuration as the link says.\n\non the console of your project path, type the following command.\n\nheroku config:set PGSSLMODE=no-verify\n\nabove command is the same as this.\nhttps://i.sstatic.net/5FpJ1.png\n\n========================================\n\nCode:\n```text\nerror: no pg_hba.conf entry for host \"<My public IP address>\", user \"<username>\", database \"<dbname>\", SSL off\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nconst cfg: TypeOrmModuleOptions = {\n type: 'postgres',\n host: process.env.DB_HOST,\n database: process.env.DB_NAME,\n username: process.env.DB_USER,\n password: process.env.DB_PASSWORD,\n port: Number(process.env.DB_PORT),\n};\n\n@Module({\n imports: [TypeOrmModule.forRoot(cfg)],\n})\nexport class AppModule {}\n```\n\n```text\napp.module.ts\n```\n\n```text\nDB_*\n```\n\n```text\nDatabase Credentials\n```\n\n```text\nTypeORM\n```\n\n```text\n.env\n```\n\n```text\nssl: true,\nextra: {\n ssl: {\n rejectUnauthorized: false,\n },\n},\n```\n\n```text\nssl: true\n```\n\n```js\nimport { DynamicModule, Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport * as fs from 'fs';\n\n@Module({})\nexport class DatabaseModule {\n static async forRoot(): Promise<DynamicModule> {\n const creds = JSON.parse(process.env.VCAP_SERVICES || '{}')[\"postgresql-db\"][0].credentials;\n await new Promise(resolve => setTimeout(resolve, 1000));\n return {\n module: DatabaseModule,\n imports: [\n TypeOrmModule.forRoot({\n // type: 'postgres',\n // host: process.env.PG_HOST,\n // port: Number(process.env.PG_PORT),\n // username: process.env.POSTGRES_USER,\n // password: process.env.POSTGRES_PASSWORD,\n // database: process.env.POSTGRES_DB,\n // // ssl: {\n // // rejectUnauthorized: false, // quick fix\n // // },\n\n type: 'postgres',\n host: creds.hostname,\n port: Number(creds.port),\n username: creds.username,\n password: creds.password,\n database: creds.dbname,\n ssl: {\n rejectUnauthorized: true,\n ca: creds.sslrootcert.replace(/\\\\n/g, '\\n'),\n cert: creds.sslcert.replace(/\\\\n/g, '\\n'),\n // key: creds.sslkey?.replace(/\\\\n/g, '\\n'), // not provided in your binding\n },\n\n entities: [__dirname + '/../**/*.entity{.ts,.js}'],\n synchronize: true,\n logging: ['query', 'error', 'log', 'warn', 'info'],\n autoLoadEntities: true,\n }),\n ],\n };\n }\n}\n```\n\n========================================\n\nComments:\n- Man!!! I spent hours struggling with this issue, and this solution finally helped!","metadata":{"transformedAt":"2026-08-18T18:33:44.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":165,"estimatedTokens":1016}}196{"id":"stack-67081931","source":"stackoverflow","questionId":67081931,"title":"How to configure NestJS TypeOrm with URI instead of host, port, username and password fields?","tags":["database","postgresql","heroku","nestjs","typeorm"],"text":"Title: How to configure NestJS TypeOrm with URI instead of host, port, username and password fields?\nTags: database, postgresql, heroku, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThe Heroku Postgres addon provides DB connection details as `postgres://user:pw@host:port` in the `DATABASE_URL` env var.\n\nI'm wondering how to configure a NestJS app using TypeOrm, because all the examples look like this:\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: '...',\n port: 5432,\n username: '...',\n password: '...',\n }),\n ],\n})\n```\n\n========================================\n\nTop Answer:\nI also had problem with `postgres://` protocol and I had change to `postgresql://` to have database connection fully working.\n\n========================================\n\nCode:\n```js\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: '...',\n port: 5432,\n username: '...',\n password: '...',\n }),\n ],\n})\n```\n\n```text\npostgres://user:pw@host:port\n```\n\n```text\nDATABASE_URL\n```\n\n```js\nTypeOrmModule.forRoot({\n type: 'postgres',\n url: process.env.DATABASE_URL,\n}),\n```\n\n```text\npostgres://postgres:@<db_service_name>:5432\n```\n\n```text\nurl\n```\n\n```text\npostgres\n```\n\n```text\npostgres://\n```\n\n```text\npostgresql://\n```\n\n========================================\n\nComments:\n- you saved my time as well. i wrote `mysql://~~` text using mysql. thanks\n- options like synchronize how to paass that?","metadata":{"transformedAt":"2026-08-18T18:33:44.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":85,"estimatedTokens":369}}197{"id":"stack-65242872","source":"stackoverflow","questionId":65242872,"title":"How to dynamically get column names from TypeORM?","tags":["javascript","typeorm"],"text":"Title: How to dynamically get column names from TypeORM?\nTags: javascript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have tried\n\n```\nlet modelClass = (await import('@models/' + modelName + '.ts'))[modelName];\nlet keys = Object.keys(modelClass);//no column names included, only custom helper vars i.e. NoteColumnVarcharLength\nlet keys = Object.keys(new modelClass());//nothing at all in this model\n```\n\nIs there a helper function in the library to automatically get them all?\n\n========================================\n\nTop Answer:\nThe accepted answer looks incomplete, and many questions appeared in my head when I tried to apply the answer. So I write my own to cover the question well.\n\nWe must first retrieve EntityMetadata to get column names. We can retrieve **EntityMetadata** from Connection, which we can get in any comfortable way.\n\n```\nimport { getConnection, getManager } from 'typeorm';\n\nconst connection1 = getConnection();\nconst connection2 = getManager().connection;\n```\n\nNext, we need to retrieve entity metadata.\n\nWe can do it via\n\n```\nconst metadata = connection.getMetadata(modelClass);\n```\n\nInside entity metadata you can use several options to find a column. If you need to look for all columns, you need to use `columns`. If you are going to look only over user-defined columns, you can use `ownColumns`.\n\nThese properties contain arrays with `ColumnMetadata`.\n\nIf you just need a list of user-defined columns, you can just return mapped values of `propertyName`.\n\n```\nconst columns = metadata.columns.map((column) => column.propertyName);\n```\n\nIn my case, I needed to find the database column name by a property name.\n\nI used a `find()` method for my case.\n\n```\nconst column = metadata.ownColumns.find((column) => column.propertyName === propertyName);\n```\n\nIf I need to find several columns I would create a map between `propertyName` and `databaseName`;\n\n```\nconst columnMap = Object.fromEntries(\n metadata.ownColumns((column) => ([column.propertyName, column.databaseName]))\n);\n```\n\n========================================\n\nCode:\n```text\nlet modelClass = (await import('@models/' + modelName + '.ts'))[modelName];\nlet keys = Object.keys(modelClass);//no column names included, only custom helper vars i.e. NoteColumnVarcharLength\nlet keys = Object.keys(new modelClass());//nothing at all in this model\n```\n\n```text\nconnection.getMetadata(\"User\").columns\n```\n\n```text\nimport { getConnection, getManager } from 'typeorm';\n\nconst connection1 = getConnection();\nconst connection2 = getManager().connection;\n```\n\n```text\nconst metadata = connection.getMetadata(modelClass);\n```\n\n```text\nconst columns = metadata.columns.map((column) => column.propertyName);\n```\n\n```text\nconst column = metadata.ownColumns.find((column) => column.propertyName === propertyName);\n```\n\n```text\nconst columnMap = Object.fromEntries(\n metadata.ownColumns((column) => ([column.propertyName, column.databaseName]))\n);\n```\n\n```text\ncolumns\n```\n\n```text\nownColumns\n```\n\n```text\nColumnMetadata\n```\n\n```text\npropertyName\n```\n\n```text\nfind()\n```\n\n```text\npropertyName\n```\n\n```text\ndatabaseName\n```\n\n========================================\n\nComments:\n- I think it might help: connection.getMetadata(MyEntity); Source: github.com/typeorm/typeorm/issues/1764\n- I like that solution at the bottom of your link, put that in an answer and I'll accept it!\n- Also `getConnection().getMetadata(Organization).ownColumns.map(col‌​umn => column.propertyName)`\n- For people who set an alias in their entity via `@Column({name: 'foo'})`, check for `column.databaseName` instead. `column.propertyName` will go off the entity instead of the actual name in the database.\n- Is there a way to retrieve the embedded entity columns? For example, if my \"user\" table has a relationship with the \"photo\" table, can I access the columns of the \"photo\" entity from the user entity's metadata?\n- @GisCat, I already left that project, where we were using TypeORM, so I can't answer this question. Most possibly there might be something useful inside `column.relationMetadata.inverseRelationMetadata` typeorm.delightful.studio/classes/…, but it is just a suggestion. Feel free to your investigations if you find something useful. Or maybe someone else will be able to respond to your question.\n- I find a way to get it, Thank you for the help ! I used this to retrieve the columns `connection.getMetadata(User).relations.map((relation) => relation.inverseEntityMetadata.propertiesMap);`","metadata":{"transformedAt":"2026-08-18T18:33:44.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":139,"estimatedTokens":1118}}198{"id":"stack-66129683","source":"stackoverflow","questionId":66129683,"title":"How to consolidate TypeORM migrations","tags":["database","orm","typeorm"],"text":"Title: How to consolidate TypeORM migrations\nTags: database, orm, typeorm\nSource: Stack Overflow\n\nQuestion:\nAt the moment I'm not a guru on TypeORM and have made a few mistakes with my migrations - with our non-production database now in a state where I'd like it, is it possible to consolidate the TypeORM migrations into a single file of \"create table 1 ... (n)\" and remove all the other migrations?\n\nAll documents I find tell me \"how\" to migrate, but I haven't seen anything on a \"reset and make this the default\"\n\nThanks\n\n========================================\n\nComments:\n- Thanks - sorry I missed your post - left that job 2 years ago; have voted up and accepted as that was pretty close to what I did around the time ...","metadata":{"transformedAt":"2026-08-18T18:33:44.699Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":15,"estimatedTokens":182}}199{"id":"stack-50034430","source":"stackoverflow","questionId":50034430,"title":"Using TypeORM migrations, how do I specify a particular connection?","tags":["database-migration","typeorm"],"text":"Title: Using TypeORM migrations, how do I specify a particular connection?\nTags: database-migration, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using TypeORM and trying to run a migration on a test connection. In my `ormconfig.json`, I specify two separate connections as follows:\n\n```\n[{\n \"name\": \"default\",\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"username\",\n \"password\": \"\",\n \"database\": \"database\",\n \"entities\": [\n \"build/entity/**/*.js\"\n ],\n \"migrations\": [\n \"build/migration/**/*.js\"\n ],\n \"synchronize\": false,\n \"autoSchemaSync\": true,\n \"logging\": false,\n \"cli\": {\n \"migrationsDir\": \"src/migration\",\n \"entitiesDir\": \"src/entity\",\n \"subscribersDir\": \"src/subscriber\"\n }\n},\n{\n \"name\": \"test\",\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"username\",\n \"password\": \"\",\n \"database\": \"database-test\",\n \"entities\": [\n \"build/entity/**/*.js\"\n ],\n \"migrations\": [\n \"build/migration/**/*.js\"\n ],\n \"synchronize\": false,\n \"autoSchemaSync\": true,\n \"logging\": false,\n \"cli\": {\n \"migrationsDir\": \"src/migration\",\n \"entitiesDir\": \"src/entity\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}]\n```\n\nHow do I specify the connection with name `test` from the TypeORM CLI? I'm trying things like:\n\n```\ntypeorm migrations:run -c test\n```\n\nbut I'm not having any luck. Is there a better way to do this?\n\n========================================\n\nCode:\n```text\n[{\n \"name\": \"default\",\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"username\",\n \"password\": \"\",\n \"database\": \"database\",\n \"entities\": [\n \"build/entity/**/*.js\"\n ],\n \"migrations\": [\n \"build/migration/**/*.js\"\n ],\n \"synchronize\": false,\n \"autoSchemaSync\": true,\n \"logging\": false,\n \"cli\": {\n \"migrationsDir\": \"src/migration\",\n \"entitiesDir\": \"src/entity\",\n \"subscribersDir\": \"src/subscriber\"\n }\n},\n{\n \"name\": \"test\",\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"username\",\n \"password\": \"\",\n \"database\": \"database-test\",\n \"entities\": [\n \"build/entity/**/*.js\"\n ],\n \"migrations\": [\n \"build/migration/**/*.js\"\n ],\n \"synchronize\": false,\n \"autoSchemaSync\": true,\n \"logging\": false,\n \"cli\": {\n \"migrationsDir\": \"src/migration\",\n \"entitiesDir\": \"src/entity\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}]\n```\n\n```text\ntypeorm migrations:run -c test\n```\n\n```text\normconfig.json\n```\n\n```text\ntest\n```\n\n```text\n$(npm bin)/ts-node $(npm bin)/typeorm migration:run -c test\n```\n\n```text\nts-node\n```\n\n```text\normconfig.json\n```\n\n========================================\n\nComments:\n- That was exactly my issue. It was just a typo that caused me that grief. Thanks for the response!\n- This was a problem I was having too, typeorm wasn't reading my `ormconfig.ts` and I had to use the `$(npm bin)/typeorm` path for it to work.\n- What if I want to use both connections within the migration? (I'm copying data from one DB into another)","metadata":{"transformedAt":"2026-08-18T18:33:44.699Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":146,"estimatedTokens":732}}200{"id":"stack-67580233","source":"stackoverflow","questionId":67580233,"title":"How to test custom Repository in Nestjs/TypeORM applications","tags":["nestjs","typeorm"],"text":"Title: How to test custom Repository in Nestjs/TypeORM applications\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to add more testing codes to improve the quality of my sample codes.\n\nCurrently, I have a problem when testing `UserRepository` (**not mock UserRepository**), there are some custom methods I added in my custom `UserRepository` like this.\n\n```\n@EntityRepository(UserEntity)\nexport class UserRepository extends Repository {\n findByEmail(email: string): Promise {\n return this.findOne({ email: email });\n }\n}\n```\n\nSo I want to verify the `findOne` is called from the parent `Repository`.\n\nI tried to add the following testing codes.\n\n```\ndescribe('UserRepository', () => {\n let local;\n let parentMock;\n\n beforeEach(() => {\n local = Object.getPrototypeOf(UserRepository);\n parentMock = {\n new: jest.fn(),\n construtor: jest.fn(),\n findOne: jest.fn(),\n };\n Object.setPrototypeOf(UserRepository, parentMock);\n });\n\n afterEach(() => {\n Object.setPrototypeOf(UserRepository, local);\n });\n\n it('should call findOne', async () => {\n const findByEmailSpy = jest.spyOn(parentMock, 'findOne');\n const users = new UserRepository();\n await users.findByEmail('test@example.com');\n expect(parentMock.mock.calls.length).toBe(1);\n expect(findByEmailSpy).toBeCalledWith({\n email: 'test@example.com',\n });\n });\n});\n```\n\nWhen running the tests, it complains there is no constructor() for `new UserRepository()`.\n\nIs there any way to fix this issue, or a better way to write these testing codes?\n\n========================================\n\nCode:\n```js\n@EntityRepository(UserEntity)\nexport class UserRepository extends Repository<UserEntity> {\n findByEmail(email: string): Promise<UserEntity> {\n return this.findOne({ email: email });\n }\n}\n```\n\n```js\ndescribe('UserRepository', () => {\n let local;\n let parentMock;\n\n beforeEach(() => {\n local = Object.getPrototypeOf(UserRepository);\n parentMock = {\n new: jest.fn(),\n construtor: jest.fn(),\n findOne: jest.fn(),\n };\n Object.setPrototypeOf(UserRepository, parentMock);\n });\n\n afterEach(() => {\n Object.setPrototypeOf(UserRepository, local);\n });\n\n it('should call findOne', async () => {\n const findByEmailSpy = jest.spyOn(parentMock, 'findOne');\n const users = new UserRepository();\n await users.findByEmail('test@example.com');\n expect(parentMock.mock.calls.length).toBe(1);\n expect(findByEmailSpy).toBeCalledWith({\n email: 'test@example.com',\n });\n });\n});\n```\n\n```text\nUserRepository\n```\n\n```text\nUserRepository\n```\n\n```text\nfindOne\n```\n\n```text\nRepository\n```\n\n```text\nnew UserRepository()\n```\n\n```js\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { Repository } from 'typeorm';\nimport { UserEntity } from './user.entity';\nimport { UserRepository } from './user.repository';\n\ndescribe('UserRepository', () => {\n let userRepository: UserRepository;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [UserRepository],\n }).compile();\n\n userRepository = module.get<UserRepository>(UserRepository);\n });\n\n describe('findByEmail', () => {\n it('should return found user', async () => {\n const email = 'email';\n const user = {\n email,\n };\n const findOneSpy = jest\n .spyOn(userRepository, 'findOne')\n .mockResolvedValue(user as UserEntity);\n\n const foundUser = await userRepository.findByEmail(email);\n expect(foundUser).toEqual(user);\n expect(findOneSpy).toHaveBeenCalledWith(user);\n });\n });\n});\n```\n\n```text\nfindOne\n```\n\n========================================\n\nComments:\n- If use EntityManager and QueryBuilder in the `Repository`, eg `findByAuthor` in the PostRepository, how to mock this?\n- for QueryBuilder, it can be mocked like the following: `jest.spyOn(Repository.prototype, 'createQueryBuilder').mockReturnValue(SelectQueryBuilder.pro‌​totype); jest.spyOn(SelectQueryBuilder.prototype, 'where').mockReturnThis(); // the same goes for setParameter, skip and take methods jest.spyOn(SelectQueryBuilder.prototype, 'getMany').mockResolvedValue(data);`\n- not sure about mocking `manager.findOne`, what is the reason for using `this.manager.find` instead of `this.find`?\n- I added a test make it work. But all *readonly* properties in the `Repository` should be injectable, but it does not work as expected like other injectable components.\n- Any ideas on how to do this when extending from `AbstractRepository`? I have created a separate question for it here.","metadata":{"transformedAt":"2026-08-18T18:33:44.699Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":167,"estimatedTokens":1139}}201{"id":"stack-64185541","source":"stackoverflow","questionId":64185541,"title":"How to use ConfigService in Nestjs DatabaseModule","tags":["nestjs","typeorm","nestjs-config"],"text":"Title: How to use ConfigService in Nestjs DatabaseModule\nTags: nestjs, typeorm, nestjs-config\nSource: Stack Overflow\n\nQuestion:\nI have created a DatabaseModule using the nestjs typeorm\n\n```\nimport { createConnection } from 'typeorm';\nimport { ConfigService } from '@nestjs/config';\n\nexport const databaseConnection = [\n {\n provide: 'DATABASE_CONNECTION',\n useFactory: async (configService: ConfigService) => await createConnection({\n type: configService.get('DBTYPE'),\n host: configService.get('DBHOST'),\n port: configService.get('DBPORT'),\n username: configService.get('DBUSERNAME'),\n password: configService.get('DBPASSWORD'),\n database: configService.get('DBNAME'),\n synchronize: true,\n entities: [\n __dirname + '/../**/*.entity.ts'\n ]\n })\n }\n];\n```\n\nWhile starting the rest service I am getting the following error\n\n```\nCannot read property 'get' of undefined - {\"stack\":[\"TypeError: Cannot read property 'get' of undefined\n\n at InstanceWrapper.useFactory [as metatype] (../database/database.provider.js:9:33)\n at Injector.instantiateClass (../node_modules/@nestjs/core/injector/injector.js:293:55)\n at callback (../node_modules/@nestjs/core/injector/injector.js:77:41)\n at process._tickCallback (internal/process/next_tick.js:68:7)\n at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)\n at startup (internal/bootstrap/node.js:283:19)\n at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)\"]}\n```\n\nI have imported the `ConfigModule` inside `DatabaseModule`.\n\nCan someone help me out with this?\n\n**EDIT**\n\nMy database config\n\n```\nimport { registerAs } from '@nestjs/config';\n\n// Configuration factory class for database configuration.\nconst DatabaseConfig = registerAs('DBConfig', () => ({\n DBTYPE: process.env.DATABASE_TYPE,\n DBHOST: process.env.DATABASE_HOST || 'localhost',\n DBPORT: process.env.DATABASE_PORT || 5432,\n DBUSERNAME: process.env.DATABASE_USERNAME,\n DBPASSWORD: process.env.DATABASE_PASSWORD,\n DBNAME: process.env.DATABASE_NAME\n}));\n```\n\nIn app.module.ts imports\n\n```\nConfigModule.forRoot({\n isGlobal: true,\n expandVariables: true,\n load: [AppConfig, DatabaseConfig]\n}),\n```\n\n========================================\n\nCode:\n```text\nimport { createConnection } from 'typeorm';\nimport { ConfigService } from '@nestjs/config';\n\n\nexport const databaseConnection = [\n {\n provide: 'DATABASE_CONNECTION',\n useFactory: async (configService: ConfigService) => await createConnection({\n type: configService.get('DBTYPE'),\n host: configService.get('DBHOST'),\n port: configService.get('DBPORT'),\n username: configService.get('DBUSERNAME'),\n password: configService.get('DBPASSWORD'),\n database: configService.get('DBNAME'),\n synchronize: true,\n entities: [\n __dirname + '/../**/*.entity.ts'\n ]\n })\n }\n];\n```\n\n```text\nCannot read property 'get' of undefined - {\"stack\":[\"TypeError: Cannot read property 'get' of undefined\n\n at InstanceWrapper.useFactory [as metatype] (../database/database.provider.js:9:33)\n at Injector.instantiateClass (../node_modules/@nestjs/core/injector/injector.js:293:55)\n at callback (../node_modules/@nestjs/core/injector/injector.js:77:41)\n at process._tickCallback (internal/process/next_tick.js:68:7)\n at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)\n at startup (internal/bootstrap/node.js:283:19)\n at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)\"]}\n```\n\n```text\nimport { registerAs } from '@nestjs/config';\n\n// Configuration factory class for database configuration.\nconst DatabaseConfig = registerAs('DBConfig', () => ({\n DBTYPE: process.env.DATABASE_TYPE,\n DBHOST: process.env.DATABASE_HOST || 'localhost',\n DBPORT: process.env.DATABASE_PORT || 5432,\n DBUSERNAME: process.env.DATABASE_USERNAME,\n DBPASSWORD: process.env.DATABASE_PASSWORD,\n DBNAME: process.env.DATABASE_NAME\n}));\n```\n\n```text\nConfigModule.forRoot({\n isGlobal: true,\n expandVariables: true,\n load: [AppConfig, DatabaseConfig]\n}),\n```\n\n```text\nConfigModule\n```\n\n```text\nDatabaseModule\n```\n\n```js\nexport const databaseConnection = [\n {\n provide: 'DATABASE_CONNECTION',\n inject: [ConfigService],\n useFactory: async (configService: ConfigService) => await createConnection({\n type: configService.get('DBConfig.DBTYPE'),\n host: configService.get('DBConfig.DBHOST'),\n port: configService.get('DBConfig.DBPORT'),\n username: configService.get('DBConfig.DBUSERNAME'),\n password: configService.get('DBConfig.DBPASSWORD'),\n database: configService.get('DBConfig.DBNAME'),\n synchronize: true,\n entities: [\n __dirname + '/../**/*.entity.ts'\n ]\n })\n }\n];\n```\n\n```text\nConfigService\n```\n\n```text\ninject\n```\n\n```text\nDBConfig.DBTYPE\n```\n\n```text\nConfigService\n```\n\n```text\ninject: [ConfigService]\n```\n\n```text\nimports: [ConfigModule]\n```\n\n========================================\n\nComments:\n- The config service does come from the global module. After adding `inject` the `configService.get('DBTYPE')` returns `undefined`\n- Well, how is the `ConfigModule` registered? Do you have `DBTYPE` in a `.env` file? You can see the `ConfigService` is working as expected\n- I have updated my question. I have invoked the `AppConfig` inside main.ts and it works\n- You're using a config namesapce. You need to do `configService.get(namespace.value)`. In this case `configService.get('DBConfig.DBTYPE')`","metadata":{"transformedAt":"2026-08-18T18:33:44.699Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":197,"estimatedTokens":1394}}202{"id":"stack-60271852","source":"stackoverflow","questionId":60271852,"title":"can I use a partial entity to save with typeorm?","tags":["typescript","typeorm","typeorm-datamapper"],"text":"Title: can I use a partial entity to save with typeorm?\nTags: typescript, typeorm, typeorm-datamapper\nSource: Stack Overflow\n\nQuestion:\nSo I have this table structure\n\n```\n--changeset 0004-order:ccushing\ncreate table if not exists \"order\".\"order\"\n(\n id uuid primary key not null default uuid_generate_v4(),\n state uuid references \"order\".order_status\n);\n\n--changeset 0004-h0-table-order_event_type:ccushing\ncreate table if not exists \"order\".order_event_type\n(\n id uuid primary key not null default uuid_generate_v4(),\n key text unique not null\n);\n\n--changeset 0004-h1-table-order_event:ccushing\ncreate table if not exists \"order\".order_event\n(\n id uuid primary key not null default uuid_generate_v4(),\n order_id uuid not null references \"order\".\"order\" (id),\n event_type uuid not null references \"order\".order_event_type (id),\n event jsonb not null,\n unique (order_id, event),\n unique (order_id, event_type)\n);\n```\n\nI want to create a new `OrderEventEntity`, but I don't want to load `Order` when doing it, since I'll just be getting the `order_id` in the event. \n\n```\n@Entity('order.order_event')\nexport default class OrderEventEntity implements Identifiable {\n @PrimaryGeneratedColumn({ type: 'uuid' })\n readonly id!: string;\n\n @ManyToOne(() => OrderEventTypeEntity, ({ event }) => event)\n readonly eventType!: string;\n\n @ManyToOne(() => OrderEntity, ({ events }) => events)\n readonly order!: OrderEntity;\n}\n```\n\nam I able to do\n\n```\nconst order = new Order({ id: 1234 })\nrepo.save( new OrderEventEntity({ order: order, ... })\n```\n\nor similar (maybe some partial load) without losing the OneToMany? but still only having the order id.\n\n========================================\n\nCode:\n```sql\n--changeset 0004-order:ccushing\ncreate table if not exists \"order\".\"order\"\n(\n id uuid primary key not null default uuid_generate_v4(),\n state uuid references \"order\".order_status\n);\n\n--changeset 0004-h0-table-order_event_type:ccushing\ncreate table if not exists \"order\".order_event_type\n(\n id uuid primary key not null default uuid_generate_v4(),\n key text unique not null\n);\n\n--changeset 0004-h1-table-order_event:ccushing\ncreate table if not exists \"order\".order_event\n(\n id uuid primary key not null default uuid_generate_v4(),\n order_id uuid not null references \"order\".\"order\" (id),\n event_type uuid not null references \"order\".order_event_type (id),\n event jsonb not null,\n unique (order_id, event),\n unique (order_id, event_type)\n);\n```\n\n```text\n@Entity('order.order_event')\nexport default class OrderEventEntity implements Identifiable<string> {\n @PrimaryGeneratedColumn({ type: 'uuid' })\n readonly id!: string;\n\n @ManyToOne(() => OrderEventTypeEntity, ({ event }) => event)\n readonly eventType!: string;\n\n @ManyToOne(() => OrderEntity, ({ events }) => events)\n readonly order!: OrderEntity;\n}\n```\n\n```text\nconst order = new Order({ id: 1234 })\nrepo.save( new OrderEventEntity({ order: order, ... })\n```\n\n```text\nOrderEventEntity\n```\n\n```text\nOrder\n```\n\n```text\norder_id\n```\n\n```text\n@Entity('order.order_event')\nexport default class OrderEventEntity implements Identifiable<string> {\n @PrimaryGeneratedColumn({ type: 'uuid' })\n readonly id!: string;\n\n @ManyToOne(() => OrderEventTypeEntity, ({ event }) => event)\n readonly eventType!: string;\n\n @Column()\n order_id: string;\n\n @ManyToOne(() => OrderEntity, ({ events }) => events)\n readonly order!: OrderEntity;\n}\n```\n\n```text\nconst order = { id: 1234 } as Order;\nrepo.save( new OrderEventEntity({ order: order, ... })\n```\n\n```text\norder_id\n```\n\n```text\nOrderEventEntity\n```\n\n========================================\n\nComments:\n- I should have guessed this, but it doesn't actually care if the object is from a loaded instance.","metadata":{"transformedAt":"2026-08-18T18:33:44.699Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":154,"estimatedTokens":1026}}203{"id":"stack-71740574","source":"stackoverflow","questionId":71740574,"title":"Cannot add cli parameters to DataSourceOptions in TypeORM","tags":["javascript","typescript","typeorm"],"text":"Title: Cannot add cli parameters to DataSourceOptions in TypeORM\nTags: javascript, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn the typeORM documentation a cli parameter can be added to `DataSourceOptions` according to https://github.com/typeorm/typeorm/blob/master/docs/data-source-options.md. The example I saw on https://typeorm.io/using-cli looks was\n\n```\n{\n cli: {\n entitiesDir: \"src/entity\",\n subscribersDir: \"src/subscriber\",\n migrationsDir: \"src/migration\"\n }\n}\n```\n\nI tried this in my code as follows:\n\n```\nlet dataSource = new DataSource(\n {\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n database: 'website',\n username: 'test',\n password: 'test',\n logging: true,\n synchronize: false,\n entities: [User, Posts],\n cli: {\n entitiesDir: \"src/entity\",\n subscribersDir: \"src/subscriber\",\n migrationsDir: \"src/migration\"\n }\n })\n```\n\nHowever I get the following error:\nArgument of type `'{ type: \"postgres\"; host: string; port: number; database: string; username: string; password: string; logging: true; synchronize: false; entities: (typeof User | typeof Wallet)[]; cli: { entitiesDir: string; subscribersDir: string; migrationsDir: string; }; }'` is not assignable to parameter of type `'DataSourceOptions'`.\nObject literal may only specify known properties, and `'cli'` does not exist in type `'PostgresConnectionOptions'.ts`(2345)\n\n========================================\n\nTop Answer:\n**TypeORM** and **TypeORM CLI** not works perfectly after **0.3.0**. I had the same problem, so I advice you to downgrade to version **0.2**\n\n========================================\n\nCode:\n```text\n{\n cli: {\n entitiesDir: \"src/entity\",\n subscribersDir: \"src/subscriber\",\n migrationsDir: \"src/migration\"\n }\n}\n```\n\n```text\nlet dataSource = new DataSource(\n {\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n database: 'website',\n username: 'test',\n password: 'test',\n logging: true,\n synchronize: false,\n entities: [User, Posts],\n cli: {\n entitiesDir: \"src/entity\",\n subscribersDir: \"src/subscriber\",\n migrationsDir: \"src/migration\"\n }\n })\n```\n\n```text\nDataSourceOptions\n```\n\n```text\n'{ type: \"postgres\"; host: string; port: number; database: string; username: string; password: string; logging: true; synchronize: false; entities: (typeof User | typeof Wallet)[]; cli: { entitiesDir: string; subscribersDir: string; migrationsDir: string; }; }'\n```\n\n```text\n'DataSourceOptions'\n```\n\n```text\n'cli'\n```\n\n```text\n'PostgresConnectionOptions'.ts\n```\n\n```text\ntypeorm migration:create -n UrlMigration -d src/migrations\n```\n\n```text\n\"scripts\": {\n ...\n \"typeorm\": \"typeorm-ts-node-commonjs -d ormconfig.ts\"\n}\n```\n\n```text\n// ormconfig.ts\n\nexport const datasource = new DataSource({\n type: \"postgres\",\n host: \"localhost\",\n port: 5432,\n database: \"database\",\n username: \"username\",\n password: \"password\",\n entities: [EntityA, EntityB, EntityC],\n migrations: [__dirname + \"/migrations/*{.js,.ts}\"],\n subscribers: [],\n})\n```\n\n```text\nimport { DataSource } from 'typeorm';\n\nconst configMigration = new DataSource({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'mediumclone',\n password: 'qwerty',\n database: 'mediumclone',\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: false,\n migrations: [__dirname + '/migrations/**/*{.ts,.js}'],\n});\n\nexport default configMigration;\n```\n\n```text\nimport { DataSourceOptions } from 'typeorm';\n\nconst config: DataSourceOptions = {\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'mediumclone',\n password: 'qwerty',\n database: 'mediumclone',\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: false,\n migrations: [__dirname + '/migrations/**/*{.ts,.js}'],\n};\n\nexport default config;\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from '@app/app.controller';\nimport { AppService } from '@app/app.service';\nimport { TagModule } from '@app/tag/tag.module';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport ormconfig from '@app/config/ormconfig';\n\n@Module({\n imports: [TypeOrmModule.forRoot(ormconfig), TagModule],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\n\"scripts\": {\n \"typeorm\": \"typeorm-ts-node-commonjs -d src/config/ormconfig-migrations.ts\",\n \"db:drop\": \"yarn run typeorm schema:drop\"\n}\n```\n\n```text\nyarn run db:drop\n```\n\n```text\nyarn run typeorm migration:generate -n\n```\n\n```text\nimport { DataSource } from \"typeorm\"\n\nconst AppDataSource = new DataSource({\n\n type: \"mysql\",\n host: \"localhost\",\n port: 3306,\n username: \"root\",\n password: \"\",\n database: \"test\",\n logging: true,\n synchronize: false,\n entities: [],\n subscribers: [],\n});\n```\n\n```text\ntype\n```\n\n```text\nyarn run typeorm migration:generate ./src/db/migrations/NameMyMigration\n```\n\n```text\nyarn run typeorm migration:generate -n\n```\n\n========================================\n\nComments:\n- same problem. switched to version 0.2, everything worked without errors\n- Thank you! The documentation on this is opaque to say the least.\n- If typeorm is not installed globally, one can do `npm/yarn typeorm migration:create etc.`\n- Typeorm changed from calling it ormconfig.ts to datasource.ts typically\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:44.699Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":233,"estimatedTokens":1410}}204{"id":"stack-62822943","source":"stackoverflow","questionId":62822943,"title":"NestJS/TypeORM unit testing: Can't resolve dependencies of JwtService","tags":["jestjs","nestjs","typeorm","nestjs-jwt"],"text":"Title: NestJS/TypeORM unit testing: Can't resolve dependencies of JwtService\nTags: jestjs, nestjs, typeorm, nestjs-jwt\nSource: Stack Overflow\n\nQuestion:\nI'm trying to unit test this controller and mock away the services/repositories that it needs.\n\n```\n@Controller('auth')\nexport class AuthController {\n constructor(\n private readonly authService: AuthService,\n private readonly usersService: UsersService,\n ) {}\n\n @Post('register')\n public async registerAsync(@Body() createUserModel: CreateUserModel) {\n const result = await this.authenticationService.registerUserAsync(createUserModel);\n\n // more code here\n }\n\n @Post('login')\n public async loginAsync(@Body() login: LoginModel): Promise {\n const user = await this.usersService.getUserByUsernameAsync(login.username);\n\n // more code here\n }\n}\n```\n\nHere is my unit test file:\n\n```\ndescribe('AuthController', () => {\n let authController: AuthController;\n let authService: AuthService;\n\n beforeEach(async () => {\n const moduleRef: TestingModule = await Test.createTestingModule({\n imports: [JwtModule],\n controllers: [AuthController],\n providers: [\n AuthService,\n UsersService,\n {\n provide: getRepositoryToken(User),\n useClass: Repository,\n },\n ],\n }).compile();\n\n authController = moduleRef.get(AuthenticationController);\n authService = moduleRef.get(AuthenticationService);\n });\n\n describe('registerAsync', () => {\n it('Returns registration status when user registration succeeds', async () => {\n let createUserModel: CreateUserModel = {...}\n\n let registrationStatus: RegistrationStatus = {\n success: true,\n message: 'User registered successfully',\n };\n\n jest.spyOn(authService, 'registerUserAsync').mockImplementation(() =>\n Promise.resolve(registrationStatus),\n );\n\n expect(await authController.registerAsync(createUserModel)).toEqual(registrationStatus);\n });\n });\n});\n```\n\nBut when running this, I get the following error(s):\n\n```\n● AuthController › registerAsync › Returns registration status when user registration succeeds\n\n Nest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0] is available in the JwtModule context.\n\n Potential solutions:\n - If JWT_MODULE_OPTIONS is a provider, is it part of the current JwtModule?\n - If JWT_MODULE_OPTIONS is exported from a separate @Module, is that module imported within JwtModule?\n @Module({\n imports: [ /* the Module containing JWT_MODULE_OPTIONS */ ]\n })\n\n at Injector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:191:19)\n at Injector.resolveComponentInstance (../node_modules/@nestjs/core/injector/injector.js:147:33)\n at resolveParam (../node_modules/@nestjs/core/injector/injector.js:101:38)\n at async Promise.all (index 0)\n at Injector.resolveConstructorParams (../node_modules/@nestjs/core/injector/injector.js:116:27)\n at Injector.loadInstance (../node_modules/@nestjs/core/injector/injector.js:80:9)\n at Injector.loadProvider (../node_modules/@nestjs/core/injector/injector.js:37:9)\n at Injector.lookupComponentInImports (../node_modules/@nestjs/core/injector/injector.js:223:17)\n at Injector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:189:33)\n\n ● AuthController › registerAsync › Returns registration status when user registration succeeds\n\n Cannot spyOn on a primitive value; undefined given\n\n 48 | };\n 49 |\n > 50 | jest.spyOn(authService, 'registerUserAsync').mockImplementation(() =>\n | ^\n 51 | Promise.resolve(registrationStatus),\n 52 | );\n 53 |\n\n at ModuleMockerClass.spyOn (../node_modules/jest-mock/build/index.js:780:13)\n at Object. (Authentication/authentication.controller.spec.ts:50:18)\n```\n\nI'm not quite sure how to proceed so I'd like some help.\n\n========================================\n\nTop Answer:\nSince you are registering `AuthService` in the dependency injection container and just spying on `registerUserAsync`, it requires `JWTService` to be registered as well.\n\nYou need to register dependencies that are injected in `AuthService`:\n\n```\nconst moduleRef: TestingModule = await Test.createTestingModule({\n imports: [JwtModule],\n controllers: [AuthController],\n providers: [\n AuthService,\n UsersService,\n JWTService, // or register a fully mocked `AuthService` that doesn't need any other dependency:\n\n```\nconst moduleRef: TestingModule = await Test.createTestingModule({\n imports: [JwtModule],\n controllers: [AuthController],\n providers: [\n {\n provide: AuthService,\n useValue: {\n registerUserAsync: jest.fn(), // <--here\n }\n },\n {\n provide: getRepositoryToken(User),\n useClass: Repository,\n },\n],\n}).compile();\n```\n\n========================================\n\nCode:\n```text\n@Controller('auth')\nexport class AuthController {\n constructor(\n private readonly authService: AuthService,\n private readonly usersService: UsersService,\n ) {}\n\n @Post('register')\n public async registerAsync(@Body() createUserModel: CreateUserModel) {\n const result = await this.authenticationService.registerUserAsync(createUserModel);\n\n // more code here\n }\n\n @Post('login')\n public async loginAsync(@Body() login: LoginModel): Promise<{ accessToken: string }> {\n const user = await this.usersService.getUserByUsernameAsync(login.username);\n\n // more code here\n }\n}\n```\n\n```text\ndescribe('AuthController', () => {\n let authController: AuthController;\n let authService: AuthService;\n\n beforeEach(async () => {\n const moduleRef: TestingModule = await Test.createTestingModule({\n imports: [JwtModule],\n controllers: [AuthController],\n providers: [\n AuthService,\n UsersService,\n {\n provide: getRepositoryToken(User),\n useClass: Repository,\n },\n ],\n }).compile();\n\n authController = moduleRef.get<AuthenticationController>(AuthenticationController);\n authService = moduleRef.get<AuthenticationService>(AuthenticationService);\n });\n\n describe('registerAsync', () => {\n it('Returns registration status when user registration succeeds', async () => {\n let createUserModel: CreateUserModel = {...}\n\n let registrationStatus: RegistrationStatus = {\n success: true,\n message: 'User registered successfully',\n };\n\n jest.spyOn(authService, 'registerUserAsync').mockImplementation(() =>\n Promise.resolve(registrationStatus),\n );\n\n expect(await authController.registerAsync(createUserModel)).toEqual(registrationStatus);\n });\n });\n});\n```\n\n```text\n● AuthController › registerAsync › Returns registration status when user registration succeeds\n\n Nest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0] is available in the JwtModule context.\n\n Potential solutions:\n - If JWT_MODULE_OPTIONS is a provider, is it part of the current JwtModule?\n - If JWT_MODULE_OPTIONS is exported from a separate @Module, is that module imported within JwtModule?\n @Module({\n imports: [ /* the Module containing JWT_MODULE_OPTIONS */ ]\n })\n\n at Injector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:191:19)\n at Injector.resolveComponentInstance (../node_modules/@nestjs/core/injector/injector.js:147:33)\n at resolveParam (../node_modules/@nestjs/core/injector/injector.js:101:38)\n at async Promise.all (index 0)\n at Injector.resolveConstructorParams (../node_modules/@nestjs/core/injector/injector.js:116:27)\n at Injector.loadInstance (../node_modules/@nestjs/core/injector/injector.js:80:9)\n at Injector.loadProvider (../node_modules/@nestjs/core/injector/injector.js:37:9)\n at Injector.lookupComponentInImports (../node_modules/@nestjs/core/injector/injector.js:223:17)\n at Injector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:189:33)\n\n ● AuthController › registerAsync › Returns registration status when user registration succeeds\n\n Cannot spyOn on a primitive value; undefined given\n\n 48 | };\n 49 |\n > 50 | jest.spyOn(authService, 'registerUserAsync').mockImplementation(() =>\n | ^\n 51 | Promise.resolve(registrationStatus),\n 52 | );\n 53 |\n\n at ModuleMockerClass.spyOn (../node_modules/jest-mock/build/index.js:780:13)\n at Object.<anonymous> (Authentication/authentication.controller.spec.ts:50:18)\n```\n\n```js\nbeforeEach(async () => {\n const modRef = await Test.createTestingModule({\n controllers: [AuthController],\n providers: [\n {\n provide: AuthService,\n useValue: {\n registerUserAsync: jest.fn(),\n }\n\n },\n {\n provide: UserService,\n useValue: {\n getUserByUsernameAsync: jest.fn(),\n }\n }\n ]\n }).compile();\n});\n```\n\n```text\nimports\n```\n\n```text\nmodRef.get()\n```\n\n```ts\nconst moduleRef: TestingModule = await Test.createTestingModule({\n imports: [JwtModule],\n controllers: [AuthController],\n providers: [\n AuthService,\n UsersService,\n JWTService, // <--here\n {\n provide: getRepositoryToken(User),\n useClass: Repository,\n },\n],\n}).compile();\n```\n\n```ts\nconst moduleRef: TestingModule = await Test.createTestingModule({\n imports: [JwtModule],\n controllers: [AuthController],\n providers: [\n {\n provide: AuthService,\n useValue: {\n registerUserAsync: jest.fn(), // <--here\n }\n },\n {\n provide: getRepositoryToken(User),\n useClass: Repository,\n },\n],\n}).compile();\n```\n\n```text\nAuthService\n```\n\n```text\nregisterUserAsync\n```\n\n```text\nJWTService\n```\n\n```text\nAuthService\n```\n\n```text\nAuthService\n```\n\n```text\nJwtModule.registerAsync({\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: async (configService: ConfigService) => ({\n secret: configService.get('JWT_SECRET'),\n signOptions: { expiresIn: '1d' }\n })\n }),\n```\n\n```text\nmodule\n```\n\n```text\nAuthService\n```\n\n```text\nJwtService\n```\n\n```text\nNest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0] is available in the RootTestModule context.\n```\n\n```text\nimports: []\n```\n\n```text\nawait Test.createTestingModule({\n```\n\n```text\nJwtService\n```\n\n```text\nJwtModule\n```\n\n```text\nJwtService\n```\n\n========================================\n\nComments:\n- I spent over an hour trying to figure out how to solve my problem with unit testing, and this was the only solution that worked for me. Thank you!","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":396,"estimatedTokens":2713}}205{"id":"stack-72158020","source":"stackoverflow","questionId":72158020,"title":"Proper way to create connection to db in Typeorm - Nodejs","tags":["node.js","database","connection","typeorm"],"text":"Title: Proper way to create connection to db in Typeorm - Nodejs\nTags: node.js, database, connection, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm newbie to typeorm and trying to create a connection to db. I read the typeorm's doc and found this code, it uses **DataSource** to create connection:\n\n```\nimport \"reflect-metadata\"\nimport { DataSource } from \"typeorm\"\nimport { Photo } from \"./entity/Photo\"\n\nconst AppDataSource = new DataSource({\n type: \"postgres\",\n host: \"localhost\",\n port: 5432,\n username: \"root\",\n password: \"admin\",\n database: \"test\",\n entities: [Photo],\n synchronize: true,\n logging: false,\n})\n\nAppDataSource.initialize()\n .then(() => {\n // here you can start to work with your database\n })\n .catch((error) => console.log(error))\n```\n\nBut when searching for some references in other sources, they use **createConnection** instead:\n\n```\nimport { createConnection } from \"typeorm\"\n\ncreateConnection({\n type: \"mysql\",\n host: \"localhost\",\n port: 3306,\n username: \"root\",\n password: \"mysql\",\n database: \"mysql\",\n entities: [\n __dirname + \"/entity/*.ts\"\n ],\n synchronize: true,\n logging: false\n}).then(async connection => {\n…\n…\n}).catch(error => console.log(error));\n```\n\nI'm a bit confused. What approach should I use for creating connection to db between those two above?\n\n========================================\n\nCode:\n```text\nimport \"reflect-metadata\"\nimport { DataSource } from \"typeorm\"\nimport { Photo } from \"./entity/Photo\"\n\nconst AppDataSource = new DataSource({\n type: \"postgres\",\n host: \"localhost\",\n port: 5432,\n username: \"root\",\n password: \"admin\",\n database: \"test\",\n entities: [Photo],\n synchronize: true,\n logging: false,\n})\n\nAppDataSource.initialize()\n .then(() => {\n // here you can start to work with your database\n })\n .catch((error) => console.log(error))\n```\n\n```text\nimport { createConnection } from \"typeorm\"\n\ncreateConnection({\n type: \"mysql\",\n host: \"localhost\",\n port: 3306,\n username: \"root\",\n password: \"mysql\",\n database: \"mysql\",\n entities: [\n __dirname + \"/entity/*.ts\"\n ],\n synchronize: true,\n logging: false\n}).then(async connection => {\n…\n…\n}).catch(error => console.log(error));\n```\n\n```text\ncreateConnection\n```\n\n```text\nnew DataSource\n```\n\n========================================\n\nComments:\n- I am also facing the same confusion. Did you get any reference for this?","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":116,"estimatedTokens":595}}206{"id":"stack-54516730","source":"stackoverflow","questionId":54516730,"title":"typeorm: Select options for relationship","tags":["typeorm"],"text":"Title: typeorm: Select options for relationship\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nMy relationship ManyToMany gives me that result:\n\n```\nProject {\n name: 'Project1',\n users: [\n User{\n id: 1,\n name: 'John',\n email: 'john@johncompany.com'\n }\n ]\n```\n\nHow can I select only `name` or `email` for my users?\n\n========================================\n\nTop Answer:\nyou can also this method.\n\n```\nconst query: any = await this.manager.createQueryBuilder(OrderProduct, 'orderProduct'); \nquery.select('DISTINCT product_id as productId , created_date as CreatedDate');\nquery.orderBy('created_date', 'DESC')\nreturn query.getRawMany();\n```\n\n========================================\n\nCode:\n```text\nProject {\n name: 'Project1',\n users: [\n User{\n id: 1,\n name: 'John',\n email: 'john@johncompany.com'\n }\n ]\n```\n\n```text\nname\n```\n\n```text\nemail\n```\n\n```text\n.createQueryBuilder('project')\n .leftJoin('project.acc', 'acc')\n .addSelect(['acc.id', 'acc.name', 'acc.email', 'acc.pass', 'acc.lang'])\n .getMany()\n```\n\n```text\nconst query: any = await this.manager.createQueryBuilder(OrderProduct, 'orderProduct'); \nquery.select('DISTINCT product_id as productId , created_date as CreatedDate');\nquery.orderBy('created_date', 'DESC')\nreturn query.getRawMany();\n```\n\n========================================\n\nComments:\n- Look at the query builder capability - you may be able to do this with subqueries...\n- @RichDuncan, thanks for your reply. I think this is what I need. But I can not figure out how to use it.\n- Maybe it's working. I'll try use it later and let you know about results. Thanks for you answer!","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":76,"estimatedTokens":416}}207{"id":"stack-48296623","source":"stackoverflow","questionId":48296623,"title":"How to translate an SQL statement to TypeORM query builder?","tags":["sql","node.js","database","typescript","typeorm"],"text":"Title: How to translate an SQL statement to TypeORM query builder?\nTags: sql, node.js, database, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nHow would I convert the code below to TypeORM querybuilder?\nI am trying to the documentation.\n\n```\nthis.repository.manager.query(`\n SELECT item.name, item.id\n FROM item_location\n INNER JOIN item ON item.id = item_location.itemId\n WHERE item_location.locationId = ${queryObject.filter};\n`)\n```\n\nThanks.\n\n========================================\n\nTop Answer:\nLet me know if below is what you are looking for. \n\n```\nconst item = await getManager().createQueryBuilder(Item, \"item\").innerJoinAndSelect(\"item.item_location\", \"item_location\", \"item_location.locationId = :queryfilter\", { queryfilter: queryObject.filter}).select(\"item.name, item.id\").getMany();\n```\n\n========================================\n\nCode:\n```text\nthis.repository.manager.query(`\n SELECT item.name, item.id\n FROM item_location\n INNER JOIN item ON item.id = item_location.itemId\n WHERE item_location.locationId = ${queryObject.filter};\n`)\n```\n\n```text\nawait getManager()\n .createQueryBuilder(Item, 'item')\n .select(['item.id', 'item.name'])\n .innerJoin('item.location', 'location')\n .where('location.id = :id', { id: queryObject.filter });\n```\n\n```text\nconst item = await getManager().createQueryBuilder(Item, \"item\").innerJoinAndSelect(\"item.item_location\", \"item_location\", \"item_location.locationId = :queryfilter\", { queryfilter: queryObject.filter}).select(\"item.name, item.id\").getMany();\n```\n\n========================================\n\nComments:\n- That code is also throwing an error. Relation with property path item_location in entity was not found. item_location is a table, not a property. The table has locationId and itemId properties\n- what is Item? I assume its a class but that alone doesn't work. Can you update with the Item type definition?\n- is there any online tool to convert this easily?","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":3,"totalLines":58,"estimatedTokens":488}}208{"id":"stack-46922472","source":"stackoverflow","questionId":46922472,"title":"Does typeorm support SQL IN clauses","tags":["typeorm"],"text":"Title: Does typeorm support SQL IN clauses\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nDoes typeorm support SQL IN clauses? I'm trying to query a repository where a field matches 1 of multiple values.\n\n```\nmyRepository.find({\n where: {\n SomeID: // IN [1, 2, 3, 4]\n }\n });\n```\n\n========================================\n\nTop Answer:\nI'd just like to suggest another way.\n\n```\nconst user = await this.usersRepository\n.findOne(\n {\n where: { id: In([1, 2, 3]) }\n });\n```\n\n========================================\n\nCode:\n```js\nmyRepository.find({\n where: {\n SomeID: // IN [1, 2, 3, 4]\n }\n });\n```\n\n```js\nconst users = await userRepository.createQueryBuilder(\"user\")\n .where(\"user.id IN (:...ids)\", { ids: [1, 2, 3, 4] })\n .getMany();\n```\n\n```js\nimport {In} from \"typeorm\";\n\nconst loadedPosts = await connection.getRepository(Post).find({\n title: In([\"About #2\", \"About #3\"])\n});\n```\n\n```sql\nSELECT * FROM \"post\" WHERE \"title\" IN ('About #2','About #3')\n```\n\n```text\nconst user = await this.usersRepository\n.findOne(\n {\n where: { id: In([1, 2, 3]) }\n });\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":64,"estimatedTokens":272}}209{"id":"stack-64557556","source":"stackoverflow","questionId":64557556,"title":"TypeORM bulk insert?","tags":["express","mariadb","backend","bulkinsert","typeorm"],"text":"Title: TypeORM bulk insert?\nTags: express, mariadb, backend, bulkinsert, typeorm\nSource: Stack Overflow\n\nQuestion:\nHow do i bulk insert multiple records in 1 query so my db will be efficient\nI want to create Office and insert multiple new equipments into that office.\nTable/model code:\n\nOFFICE\n\n```\n@Entity({ name: 'offices' })\nexport class Office extends Timestamps {\n\n @OneToMany(() => Equipment, (equipment: Equipment) => equipment.office, {\n onDelete: 'CASCADE',\n onUpdate: 'CASCADE'\n })\n equipment: Array;\n}\n```\n\nEQUIPMENT\n\n```\n@Entity({ name: 'equipment' })\nexport class Equipment extends Timestamps {\n @Column({\n name: 'equipment_id',\n type: 'int',\n nullable: false,\n width: 2,\n default: 0\n })\n equipment_id: number;\n\n @ManyToOne(() => Office, (office: Office) => office.equipment)\n @JoinColumn({ name: 'office_id' })\n office: Office;\n}\n```\n\n========================================\n\nCode:\n```text\n@Entity({ name: 'offices' })\nexport class Office extends Timestamps {\n\n @OneToMany(() => Equipment, (equipment: Equipment) => equipment.office, {\n onDelete: 'CASCADE',\n onUpdate: 'CASCADE'\n })\n equipment: Array<Equipment>;\n}\n```\n\n```text\n@Entity({ name: 'equipment' })\nexport class Equipment extends Timestamps {\n @Column({\n name: 'equipment_id',\n type: 'int',\n nullable: false,\n width: 2,\n default: 0\n })\n equipment_id: number;\n\n @ManyToOne(() => Office, (office: Office) => office.equipment)\n @JoinColumn({ name: 'office_id' })\n office: Office;\n}\n```\n\n```text\n@Entity({ name: 'offices' })\nexport class Office extends Timestamps {\n\n @OneToMany(() => Equipment, (equipment: Equipment) => equipment.office, {\n cascade: true, // <= here\n onDelete: 'CASCADE',\n onUpdate: 'CASCADE'\n })\n equipment: Array<Equipment>;\n}\n```\n\n```text\nawait Office.create({equipment: ['whatever']}).save();\n```\n\n```text\nconst officeRepository = connection.getRepository(Office);\nconst office = new Office();\nconst equipment1 = new Equipment(); // and set your properties or make more instances\n\noffice.equipment = [equipment1]; // or more instances\nawait officeRepository.save(office);\n```\n\n========================================\n\nComments:\n- Did not know that i have to use cascade:true . .. cool. But how can i use await Office.create({equipment: ['whatever']}).save(); with Repositories ? Because I use TypeORM repository to handle my db stuff.\n- Based on this link [orkhan.gitbook.io/typeorm/docs/active-record-data-mapper], it's pretty easy to do that. I edit my answer.\n- @PuriaRadJahanbani What If we don't know how many `equipment` models needs to be saved into `office` model ? Is there any way to map through them and insert all of them into office ?\n- @MehdiFaraji In that case, I suggest using a loop method for creating the instances. Then, you can add them to the array like `office.equipment = [...equipments]`","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":109,"estimatedTokens":729}}210{"id":"stack-57363201","source":"stackoverflow","questionId":57363201,"title":"Insert using a select in typeorm","tags":["javascript","mysql","typescript","typeorm","typeorm-datamapper"],"text":"Title: Insert using a select in typeorm\nTags: javascript, mysql, typescript, typeorm, typeorm-datamapper\nSource: Stack Overflow\n\nQuestion:\nI want to reproduce a query where the values are the result of a select in typeorm.\nThe query i want to reproduce is the one i provide here, but i can't find anything in typeorm documentation.\n(Isnt important what the query does for the answer, i only need to know how to write that \"`SELECT`\" in typeorm)\n\nhttp://typeorm.delightful.studio/classes/_query_builder_insertquerybuilder_.insertquerybuilder.html#values\n\n```\nINSERT INTO `furgpezzo`(`giacenza`, `giacenzaMin`, `pezzoBarcode`, `furgoneTarga`, `invStandardId`) \n select '0', '5', '234234234234', f.`furgoneTarga`, '1'\n from `furgpezzo` f\n where f.`invStandardId` = '1'\n group by f.`furgoneTarga`\n```\n\nsomething like:\n\n(Edit:)\n\n```\nreturn await this.dmDatabase.getRepository(FurgPezzo)\n .createQueryBuilder()\n .insert()\n .into(FurgPezzo)\n .values( //here put my select )\n```\n\n========================================\n\nTop Answer:\nThis is the neatest solution I could come up with, hope it helps future explorers. The answer comments inspired me.\n\n```\nconst [selectQuery, params] = this.entityManager\n .createQueryBuilder()\n .select(\"user.name\")\n .from(User, \"user\")\n .where(\"user.id IN (:...ids)\", {\n ids: [\n \"87654321-1234-1234-1234-123456789abc\",\n \"a9876521-aabb-ccdd-ffaa-123abcdefccc\",\n ],\n })\n .getQueryAndParameters();\n\nawait this.entityManager.query(\n `\nINSERT INTO dummy(\"name\")\n${selectQuery}\n`,\n params\n);\n```\n\n========================================\n\nCode:\n```text\nINSERT INTO `furgpezzo`(`giacenza`, `giacenzaMin`, `pezzoBarcode`, `furgoneTarga`, `invStandardId`) \n select '0', '5', '234234234234', f.`furgoneTarga`, '1'\n from `furgpezzo` f\n where f.`invStandardId` = '1'\n group by f.`furgoneTarga`\n```\n\n```text\nreturn await this.dmDatabase.getRepository(FurgPezzo)\n .createQueryBuilder()\n .insert()\n .into(FurgPezzo)\n .values( //here put my select )\n```\n\n```text\nSELECT\n```\n\n```text\nreturn await this.dmDatabase.getRepository(InvStandard)\n .insert()\n .values(qb => {qb.select(FurgPezzo).where()})//here put my select \n\n// with subquery->\n\nreturn await this.dmDatabase.getRepository(InvStandard)\n .insert()\n .values(qb => {qb.select(FurgPezzo).where(\n const subQuery = qb.subQuery()\n // your subquery builder\n return \"your condition \" + subQuery;)})\n```\n\n```text\nFROM\n```\n\n```text\nWHERE\n```\n\n```text\nJOIN\n```\n\n```text\nconst [selectQuery, params] = this.entityManager\n .createQueryBuilder()\n .select(\"user.name\")\n .from(User, \"user\")\n .where(\"user.id IN (:...ids)\", {\n ids: [\n \"87654321-1234-1234-1234-123456789abc\",\n \"a9876521-aabb-ccdd-ffaa-123abcdefccc\",\n ],\n })\n .getQueryAndParameters();\n\nawait this.entityManager.query(\n `\nINSERT INTO dummy(\"name\")\n${selectQuery}\n`,\n params\n);\n```\n\n========================================\n\nComments:\n- I wrote a bad answer... I have to edit it. What i want was use that subquery on \"values\". i can't find a way\n- @MarcoZanonfurbino1 Not sure if it's possible to use on values using the current template. But possible alternative I can think of is using the raw query and run it; example: `await manager.query('INSERT statement... select statement...')`\n- I did so and the problem is solved for now. Thank you very much\n- This answer is out of context\n- `.values()` doesn't even take queryBuilder as parameters.\n- not sure why this is the accepted answer, it doesn't work as mentioned by @Vicary. Was this valid at the time?\n- @Shinjo please remove your answer, TypeORM doesn't allow subqueries for values. Just check the doc and test the code.\n- This does not work because generated query does not preserve column order of your select statement.","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":141,"estimatedTokens":949}}211{"id":"stack-62119498","source":"stackoverflow","questionId":62119498,"title":"typeorm createConnection return Pending even with Await on MacOS with PG","tags":["node.js","postgresql","typescript","macos","typeorm"],"text":"Title: typeorm createConnection return Pending even with Await on MacOS with PG\nTags: node.js, postgresql, typescript, macos, typeorm\nSource: Stack Overflow\n\nQuestion:\nMacOS Catalina 10.15.4\n\nHow to reproduce, simply install using quick guide\n\n```\nnpm install typeorm --save\nnpm install reflect-metadata --save\nnpm install @types/node --save\nnpm install pg --save\nnpm install typeorm -g\ntypeorm init --name MyProject --database postgres\ncd MyProject\nnpm install\nnpm start\n```\n\nIt will simply return\n\n```\n➜ MyProject npm start\n\n> MyProject@0.0.1 start /Users/sergecolle/work/eve/MyProject\n> ts-node src/index.ts\n```\n\nWhen troubleshooting I found that neither the code in then and catch got executed. After modifying the code, to something like\n\n```\nconst connection:Connection = await createConnection()\n```\n\nthe connection will be in state Pending and then the program simply skip then and catch and terminate.\n\nI have ask a friend to try it on his mac and he get the same issue.\n\nthere the package.json generated by the typeorm install\n\n```\n\"name\": \"MyProject\",\n \"version\": \"0.0.1\",\n \"description\": \"Awesome project developed with TypeORM.\",\n \"devDependencies\": {\n \"ts-node\": \"3.3.0\",\n \"@types/node\": \"^8.0.29\",\n \"typescript\": \"3.3.3333\"\n },\n \"dependencies\": {\n \"typeorm\": \"0.2.25\",\n \"reflect-metadata\": \"^0.1.10\",\n \"pg\": \"^7.3.0\",\n \"express\": \"^4.15.4\",\n \"body-parser\": \"^1.18.1\"\n },\n \"scripts\": {\n \"start\": \"ts-node src/index.ts\"\n }\n```\n\nand the ormconfig.json\n\n```\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"test\",\n \"password\": \"test\",\n \"database\": \"test\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"src/entity/**/*.ts\"\n ],\n \"migrations\": [\n \"src/migration/**/*.ts\"\n ],\n \"subscribers\": [\n \"src/subscriber/**/*.ts\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\nand made sure a postgres db with those credential existed using the psql command.\n\nThe tsconfig.json generated\n\n```\n{\n \"compilerOptions\": {\n \"lib\": [\n \"es5\",\n \"es6\"\n ],\n \"target\": \"es5\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"outDir\": \"./build\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"sourceMap\": true\n }\n}\n```\n\nThe lib and target seem a little old to support async/await. I tried updating it to es2017, es2018, and esnext but no luck\n\n========================================\n\nTop Answer:\nhad the same issue on mac mini and macbook pro and getting 12.18.0 version of nodejs from the official website fixed the problem form me.\n\n========================================\n\nCode:\n```text\nnpm install typeorm --save\nnpm install reflect-metadata --save\nnpm install @types/node --save\nnpm install pg --save\nnpm install typeorm -g\ntypeorm init --name MyProject --database postgres\ncd MyProject\nnpm install\nnpm start\n```\n\n```text\n➜ MyProject npm start\n\n> MyProject@0.0.1 start /Users/sergecolle/work/eve/MyProject\n> ts-node src/index.ts\n```\n\n```text\nconst connection:Connection = await createConnection()\n```\n\n```text\n\"name\": \"MyProject\",\n \"version\": \"0.0.1\",\n \"description\": \"Awesome project developed with TypeORM.\",\n \"devDependencies\": {\n \"ts-node\": \"3.3.0\",\n \"@types/node\": \"^8.0.29\",\n \"typescript\": \"3.3.3333\"\n },\n \"dependencies\": {\n \"typeorm\": \"0.2.25\",\n \"reflect-metadata\": \"^0.1.10\",\n \"pg\": \"^7.3.0\",\n \"express\": \"^4.15.4\",\n \"body-parser\": \"^1.18.1\"\n },\n \"scripts\": {\n \"start\": \"ts-node src/index.ts\"\n }\n```\n\n```text\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"test\",\n \"password\": \"test\",\n \"database\": \"test\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"src/entity/**/*.ts\"\n ],\n \"migrations\": [\n \"src/migration/**/*.ts\"\n ],\n \"subscribers\": [\n \"src/subscriber/**/*.ts\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\n```text\n{\n \"compilerOptions\": {\n \"lib\": [\n \"es5\",\n \"es6\"\n ],\n \"target\": \"es5\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"outDir\": \"./build\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"sourceMap\": true\n }\n}\n```\n\n```text\nnpm uninstall pg --save\n```\n\n```text\nnpm install pg --save\n```\n\n========================================\n\nComments:\n- It seem to be a MacOS issue, while we were able to reproduce on Mac machine, the step above work perfectly fine on Linux.\n- I had the same issue, after upgrading pg version it started working, thanks\n- Spent 2 days trying to find solution to this problem and it was this simple!!! Thanks @badrain","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":227,"estimatedTokens":1182}}212{"id":"stack-66044062","source":"stackoverflow","questionId":66044062,"title":"Can we extends multiple classes in NestJS for TypeORM?","tags":["typescript","nestjs","typeorm"],"text":"Title: Can we extends multiple classes in NestJS for TypeORM?\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI faced a situation where I want extends multiple classes. I have class A named `a.entity.ts` and I'm extending this class to `BaseEntity` (which is the predefined class in typeORM) as :\n\n```\n@Entity()\nexport class A extends BaseEntity{\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column({length: 100, nullable: true})\n description: string;\n}\n```\n\nAlso, I have my own custom `abstract class DateAudit` for Auditing date purpose as :\n\n```\nexport abstract class DateAudit {\n \n @CreateDateColumn()\n created: Date;\n \n @UpdateDateColumn()\n updated: Date;\n }\n```\n\nI want to use this `DateAudit` along with `BaseEntity` class in my **class A** like :\n\nexport class A extends BaseEntity, DateAudit\n\nI know multiple inheritances are not possible. Looking forward to knowing how I can achieve this type of scenario.\n\nThanks in advance!\n\n========================================\n\nTop Answer:\n**SOLUTION 1** \n\nTo inherit columns in TypeORM you need to write an abstract class that your entity will inherit from, in your case you can do something:\n\n```\nexport type Constructor = new (...args: any[]) => T;\n\nexport function BaseEntity(Base: TBase) {\n abstract class AbstractBase extends Base {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column({length: 100, nullable: true})\n description: string;\n }\n return AbstractBase;\n}\n\nexport function DateAudit(Base: TBase) {\n abstract class AbstractBase extends Base {\n @CreateDateColumn()\n created: Date;\n\n @UpdateDateColumn()\n updated: Date;\n }\n return AbstractBase;\n}\n\nexport class EmptyClass {}\n```\n\nTo implement it :\n\n```\n@Entity()\nexport class A extends DateAudit(BaseEntity(EmptyClass)){\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column({length: 100, nullable: true})\n description: string;\n}\n```\n\n*ps: inspired by solution from github*\n\n**Solution 2 : is to use *Embedded Entities***\n\nIn your case, we going to extend the `baseEntity`, on the other hand\nwe going to create a class for `auditEntity`\n\n```\nexport class DateAudit {\n \n @CreateDateColumn()\n created: Date;\n \n @UpdateDateColumn()\n updated: Date;\n }\n```\n\nThen we can connect those columns in your entity :\n\n```\n@Entity()\nexport class A extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column({length: 100, nullable: true})\n description: string;\n\n @Column(type => DateAudit )\n audit: DateAudit ;\n}\n```\n\n*ps: the colmun will take `audit` as a prefix* \n\nsource : embedded-entities\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class A extends BaseEntity{\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column({length: 100, nullable: true})\n description: string;\n}\n```\n\n```text\nexport abstract class DateAudit {\n \n @CreateDateColumn()\n created: Date;\n \n @UpdateDateColumn()\n updated: Date;\n }\n```\n\n```text\na.entity.ts\n```\n\n```text\nBaseEntity\n```\n\n```text\nabstract class DateAudit\n```\n\n```text\nDateAudit\n```\n\n```text\nBaseEntity\n```\n\n```js\nexport abstract class DateAudit extends BaseEntity {\n \n @CreateDateColumn()\n created: Date;\n \n @UpdateDateColumn()\n updated: Date;\n }\n```\n\n```js\n@Entity()\nexport class A extends DateAudit {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column({length: 100, nullable: true})\n description: string;\n}\n```\n\n```text\nexport type Constructor<T = {}> = new (...args: any[]) => T;\n\nexport function BaseEntity<TBase extends Constructor>(Base: TBase) {\n abstract class AbstractBase extends Base {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column({length: 100, nullable: true})\n description: string;\n }\n return AbstractBase;\n}\n\nexport function DateAudit<TBase extends Constructor>(Base: TBase) {\n abstract class AbstractBase extends Base {\n @CreateDateColumn()\n created: Date;\n\n @UpdateDateColumn()\n updated: Date;\n }\n return AbstractBase;\n}\n\nexport class EmptyClass {}\n```\n\n```text\n@Entity()\nexport class A extends DateAudit(BaseEntity(EmptyClass)){\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column({length: 100, nullable: true})\n description: string;\n}\n```\n\n```text\nexport class DateAudit {\n \n @CreateDateColumn()\n created: Date;\n \n @UpdateDateColumn()\n updated: Date;\n }\n```\n\n```text\n@Entity()\nexport class A extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column({length: 100, nullable: true})\n description: string;\n\n @Column(type => DateAudit )\n audit: DateAudit ;\n}\n```\n\n```text\nbaseEntity\n```\n\n```text\nauditEntity\n```\n\n```text\naudit\n```\n\n========================================\n\nComments:\n- For some who looking for a solution, this can help - stackoverflow.com/questions/26948400/…\n- Thanks @youba for this solution, this works fine. The only issue is that if you, for some reason, what to have any kind of relation in the abstract class, like ManyToOne, you cannot reference back to EntityWithTenant as it is not a BaseEntity. Imagine you have TenantType entity class TenantType extends BaseEntity { ... @OneToMany(() => EntityWithTenant, entitiyWithTenant => entitiyWithTenant.tenantType) entityWithTenant: EntityWithTenant } are there any work around inside for that too?","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":300,"estimatedTokens":1392}}213{"id":"stack-72104120","source":"stackoverflow","questionId":72104120,"title":"Nestjs: cannot inject ConfigService while testing","tags":["typescript","dependency-injection","jestjs","nestjs","typeorm"],"text":"Title: Nestjs: cannot inject ConfigService while testing\nTags: typescript, dependency-injection, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm having problems setting up a unit test that utilizes the `ConfigService` to set up TypeORM. The test below fails with the following message:\n\nNest can't resolve dependencies of the TypeOrmModuleOptions (?).\nPlease make sure that the argument ConfigService at index [0] is\navailable in the TypeOrmCoreModule context.\n\nI've tried adding the `ConfigService` as a provider, but with no luck. Any ideas on what I'm doing wrong?\n\n```\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { Test } from '@nestjs/testing';\nimport { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';\n\ndescribe('TypeORM setup', () => {\n beforeEach(async () => {\n await Test.createTestingModule({\n providers: [ConfigService],\n imports: [\n ConfigModule.forRoot(),\n TypeOrmModule.forRootAsync({\n useFactory: (config: ConfigService) => ({ ...config.get('db') }),\n inject: [ConfigService],\n }),\n ],\n }).compile();\n });\n\n it('dummy', () => {\n true === true;\n });\n});\n```\n\n========================================\n\nCode:\n```text\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { Test } from '@nestjs/testing';\nimport { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';\n\ndescribe('TypeORM setup', () => {\n beforeEach(async () => {\n await Test.createTestingModule({\n providers: [ConfigService],\n imports: [\n ConfigModule.forRoot(),\n TypeOrmModule.forRootAsync({\n useFactory: (config: ConfigService) => ({ ...config.get('db') }),\n inject: [ConfigService],\n }),\n ],\n }).compile();\n });\n\n it('dummy', () => {\n true === true;\n });\n});\n```\n\n```text\nConfigService\n```\n\n```text\nConfigService\n```\n\n```text\n{ isGlobal: true }\n```\n\n```text\nConfigModule\n```\n\n```text\nimports: [ConfigModule]\n```\n\n```text\nTypeOrmModule.forRootAsync()\n```\n\n========================================\n\nComments:\n- weird enough, `imports: [ConfigModule]` was working for me to run the app but the config wasn't loaded (undefined variables) while running the e2e tests. I had to use `imports: [ConfigModule.forRoot()],` in `MongooseModule.forRootAsync` to fix the issue","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":94,"estimatedTokens":592}}214{"id":"stack-55498140","source":"stackoverflow","questionId":55498140,"title":"Saving Buffer on Postgres bytea with TypeORM only store 10 bytes","tags":["node.js","postgresql","typescript","nestjs","typeorm"],"text":"Title: Saving Buffer on Postgres bytea with TypeORM only store 10 bytes\nTags: node.js, postgresql, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to save some images on a postgres db, but only 10 bytes of data are being saved.\n\nThe flow is something like this:\n\nI receive a base64 encoded string on my server, then i load that to a Buffer, set it to my entity and save it. \nBut then a try to restore that information from db and i'm getting only 10 bytes of data, verified with octet_length() on a query.\n\nMy entity attribute definition:\n\n```\n@Column({ \"name\": \"entima_imagem\", \"type\": \"bytea\", \"nullable\": false })\nentima_imagem: Buffer;\n```\n\nThe code where i receive the data and save it:\n\n```\nentity.entima_imagem = Buffer.from(base64String, \"base64\");\nconst repository = this.getRepositoryTarget(Entity);\nconst saved = await repository.save(entity);\n```\n\nOn the server, before saving, i'm writing the file on disc and i can visualize it without problem.\n\n========================================\n\nTop Answer:\nI had similar issue. It looks like typeorm has problems with 0x00 byte. It slices everything starting from first 0 byte.\n\nA similar workaround worked for me:\n\n```\n@Column({ type: \"bytea\", nullable: false })\npublic file: Buffer;\n```\n\nwhile saving:\n\n```\nlog.file = (\"\\\\x\" + file.toString( \"hex\" )) as any;\n```\n\nCreating a buffer from \"\\\\x\"+content string as @JDuwe suggested didn't work for me.\nI had to provide a string to typeorm, not Buffer.\n\n========================================\n\nCode:\n```js\n@Column({ \"name\": \"entima_imagem\", \"type\": \"bytea\", \"nullable\": false })\nentima_imagem: Buffer;\n```\n\n```js\nentity.entima_imagem = Buffer.from(base64String, \"base64\");\nconst repository = this.getRepositoryTarget(Entity);\nconst saved = await repository.save<any>(entity);\n```\n\n```js\nentity.entima_imagem = Buffer.from(\"\\\\x\" + Buffer.from(base64String, \"base64\").toString(\"hex\"));\n```\n\n```text\n@Column({ type: \"bytea\", nullable: false })\npublic file: Buffer;\n```\n\n```text\nlog.file = (\"\\\\x\" + file.toString( \"hex\" )) as any;\n```\n\n```text\n@Column({\n name: 'imageData',\n type: 'bytea',\n nullable: false,\n})\nimageData: Buffer;\n```\n\n```text\nconstructor(imageDataBase64: string) {\n if (imageDataBase64) {\n this.imageData = Buffer.from(imageDataBase64, 'base64');\n }\n}\n```\n\n```text\nimageData.toString('base64')\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":97,"estimatedTokens":591}}215{"id":"stack-70682220","source":"stackoverflow","questionId":70682220,"title":"TypeORM SUM Operator on Relation's field","tags":["mysql","nestjs","typeorm"],"text":"Title: TypeORM SUM Operator on Relation's field\nTags: mysql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am a student trying to develop a music library just to try out new technologies.\n\nCurrently I use NestJS together with TypeORM as my backend technologies (as well as a MySQL database).\n\nWhat am I trying to achieve? I want to get the total duration of a playlist. So a playlist consists of many songs and songs can appear in multiple playlists. So we have a many-to-many relationship at this point.\nNow for getting the totalDuration I thought using some kind of SUM operator is a great idea. Exactly here is my problem: How would I do that using TypeORM?\n\nI tried following querybuilder:\n\n```\nconst playlist = await this.playlistRepository.createQueryBuilder(\"playlist\")\n .where(\"playlist.id = :playlistId\", { playlistId })\n\n // This is for relations\n .leftJoinAndSelect(\"playlist.author\", \"author\")\n .leftJoinAndSelect(\"playlist.artwork\", \"artwork\")\n .leftJoinAndSelect(\"playlist.collaborators\", \"collaborators\")\n .leftJoin(\"playlist.songs\", \"songs\")\n\n // Counting the songs\n .loadRelationCountAndMap(\"playlist.songsCount\", \"playlist.songs\")\n\n // SUM up the duration of every song to get total duration of the playlist\n .addSelect('SUM(songs.duration)', 'totalDuration')\n .groupBy(\"playlist.id\")\n .getOne()\n```\n\nBut that gave me an error I don't know how to solve:\n\n```\nQueryFailedError: Expression #16 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'soundcore_dev.collaborators.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by\n```\n\nThe resulting query that is build by TypeORM looks like this:\n\n```\nSELECT \n\n `playlist`.`id` AS `playlist_id`, \n `playlist`.`createdAt` AS `playlist_createdAt`, \n `playlist`.`authorId` AS `playlist_authorId`, \n `playlist`.`artworkId` AS `playlist_artworkId`, \n\n `author`.`id` AS `author_id`, \n `artwork`.`id` AS `artwork_id`, \n\n `collaborators`.`id` AS `collaborators_id`,\n \n SUM(`songs`.`duration`) AS `totalDuration` \n\n FROM \n `sc_playlist` `playlist` \n LEFT JOIN `sc_sso_user` `author` ON `author`.`id`=`playlist`.`authorId`\n LEFT JOIN `sc_artwork` `artwork` ON `artwork`.`id`=`playlist`.`artworkId` \n LEFT JOIN `sc_collaborators2playlist` `playlist_collaborators` ON `playlist_collaborators`.`playlistId`=`playlist`.`id` \n LEFT JOIN `sc_sso_user` `collaborators` ON `collaborators`.`id`=`playlist_collaborators`.`ssoUserId` \n LEFT JOIN `sc_song2playlist` `playlist_songs` ON `playlist_songs`.`playlistId`=`playlist`.`id` \n LEFT JOIN `sc_song` `songs` ON `songs`.`id`=`playlist_songs`.`songId` \n\n WHERE \n `playlist`.`id` = ? \n GROUP BY \n `playlist`.`id`\n```\n\nI did some research only and found how to sum up using typeORM, but I didn't get it to work for me. The above code and so on is everything I've found. I think I'm justing missing something quite important...\n\nMaybe some one can support me on this. I would really appreciate this.\nHave a great day! And thanks in advance for your kind support.\n\n========================================\n\nCode:\n```js\nconst playlist = await this.playlistRepository.createQueryBuilder(\"playlist\")\n .where(\"playlist.id = :playlistId\", { playlistId })\n\n // This is for relations\n .leftJoinAndSelect(\"playlist.author\", \"author\")\n .leftJoinAndSelect(\"playlist.artwork\", \"artwork\")\n .leftJoinAndSelect(\"playlist.collaborators\", \"collaborators\")\n .leftJoin(\"playlist.songs\", \"songs\")\n\n // Counting the songs\n .loadRelationCountAndMap(\"playlist.songsCount\", \"playlist.songs\")\n\n // SUM up the duration of every song to get total duration of the playlist\n .addSelect('SUM(songs.duration)', 'totalDuration')\n .groupBy(\"playlist.id\")\n .getOne()\n```\n\n```text\nQueryFailedError: Expression #16 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'soundcore_dev.collaborators.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by\n```\n\n```sql\nSELECT \n\n `playlist`.`id` AS `playlist_id`, \n `playlist`.`createdAt` AS `playlist_createdAt`, \n `playlist`.`authorId` AS `playlist_authorId`, \n `playlist`.`artworkId` AS `playlist_artworkId`, \n\n `author`.`id` AS `author_id`, \n `artwork`.`id` AS `artwork_id`, \n\n `collaborators`.`id` AS `collaborators_id`,\n \n SUM(`songs`.`duration`) AS `totalDuration` \n\n FROM \n `sc_playlist` `playlist` \n LEFT JOIN `sc_sso_user` `author` ON `author`.`id`=`playlist`.`authorId`\n LEFT JOIN `sc_artwork` `artwork` ON `artwork`.`id`=`playlist`.`artworkId` \n LEFT JOIN `sc_collaborators2playlist` `playlist_collaborators` ON `playlist_collaborators`.`playlistId`=`playlist`.`id` \n LEFT JOIN `sc_sso_user` `collaborators` ON `collaborators`.`id`=`playlist_collaborators`.`ssoUserId` \n LEFT JOIN `sc_song2playlist` `playlist_songs` ON `playlist_songs`.`playlistId`=`playlist`.`id` \n LEFT JOIN `sc_song` `songs` ON `songs`.`id`=`playlist_songs`.`songId` \n\n WHERE \n `playlist`.`id` = ? \n GROUP BY \n `playlist`.`id`\n```\n\n```text\nconst playlist = await this.playlistRepository.createQueryBuilder(\"playlist\")\n .where(\"playlist.id = :playlistId\", { playlistId })\n\n // This is for relations\n .leftJoin(\"playlist.songs\", \"songs\")\n\n // Counting the songs\n //.select('COUNT(songs.id)', 'numbersongs') in case you want count of songs\n\n // SUM up the duration of every song to get total duration of the playlist\n .addSelect('SUM(songs.duration)', 'totalDuration')\n .getRawOne()\n```\n\n```text\nsum,max,avg,..\n```\n\n```text\ngetRawOne\n```\n\n```text\ngetRawMany\n```\n\n========================================\n\nComments:\n- Should be marked as an answer, works for my example, needed to sum the product prices!","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":163,"estimatedTokens":1479}}216{"id":"stack-68744139","source":"stackoverflow","questionId":68744139,"title":"Exposing an array of object using class-transformer","tags":["typescript","nestjs","typeorm","class-transformer"],"text":"Title: Exposing an array of object using class-transformer\nTags: typescript, nestjs, typeorm, class-transformer\nSource: Stack Overflow\n\nQuestion:\nI am not able to expose an array of objects.\nThe Followers array is not getting exposed, even though I exposed in the `UserDto`\n\nthis is what I am getting,\n\n```\n{\n \"id\": \"5ff4ec30-d3f4-43d3-b5ad-82b03e1c5481\",\n \"userName\": \"jdbfjl\",\n \"email\": \"jdfbaj@gmail.com\",\n \"bio\": \"Duuude\",\n \"avatar\": \"sjldflaeulajsnlnaefb\",\n \"followerCount\": 0,\n \"followeeCount\": 0,\n \"verified\": false,\n \"followers\": [\n {},\n {},\n {}\n ],\n \"followees\": [\n {}\n ]\n }\n```\n\nand expected is like\n\n```\n{\n \"id\": \"5ff4ec30-d3f4-43d3-b5ad-82b03e1c5481\",\n \"createdAt\": \"2021-08-11T11:07:11.688Z\",\n \"updatedAt\": \"2021-08-11T11:07:11.688Z\",\n \"userName\": \"ashdviah\",\n \"email\": \"hsdvhas@gmail.com\",\n \"bio\": \"I am Handsome\",\n \"avatar\": \"sjldflaeulajsnlnaefb\",\n \"followerCount\": 0,\n \"followeeCount\": 0,\n \"verified\": false,\n \"followers\": [\n {\n \"id\": \"db1d30c6-5607-4d87-8838-69f906c3c44e\",\n \"createdAt\": \"2021-08-11T11:09:33.018Z\",\n \"updatedAt\": \"2021-08-11T11:09:33.018Z\"\n },\n {\n \"id\": \"31492cd6-7c56-48f6-aff3-792a980b5100\",\n \"createdAt\": \"2021-08-11T11:11:01.288Z\",\n \"updatedAt\": \"2021-08-11T11:11:01.288Z\"\n },\n ],\n \"followees\": [\n {\n \"id\": \"ab095d0d-b9fa-41a4-be35-13fe9dd6f7a1\",\n \"createdAt\": \"2021-08-11T12:55:18.139Z\",\n \"updatedAt\": \"2021-08-11T12:55:18.139Z\"\n }\n ]\n }\n```\n\nI am getting this output when I am not specifying interceptor to that route... But it turns out that I am exposing password entry with it...\n\nmy current approach is something like this : which is not working as expected... what am i missing here ?\n\n```\nclass mock {\n @Expose() id : string;\n @Expose() createdAt : Date;\n @Expose() updatedAt : Date;\n}\n\nexport class UserDto {\n @Expose()\n id : string;\n \n @Expose()\n userName : string;\n \n @Expose()\n email : string;\n\n @Expose()\n bio : string;\n\n @Expose()\n avatar : string;\n\n @Expose()\n followerCount : number;\n\n @Expose()\n followeeCount : number;\n\n @Expose()\n verified : boolean;\n\n @Expose()\n followers : Array;\n\n @Expose()\n followees : Array;\n}\n```\n\nAnd transform is getting done by one interceptor that I used at the controller.\n\nusage : `@Serialize(UserDto)` decorator\n\n```\nexport function Serialize(dto: ClassConstructor) {\n return UseInterceptors(new Serializeinterceptor(dto));\n}\n\nexport class Serializeinterceptor implements NestInterceptor {\n constructor(private dto: any) {}\n\n intercept(context: ExecutionContext, handler: CallHandler) {\n return handler.handle().pipe(\n map((data: any) => {\n return plainToClass(this.dto, data, {\n excludeExtraneousValues: true,\n });\n }),\n );\n }\n}\n```\n\n========================================\n\nCode:\n```text\n{\n \"id\": \"5ff4ec30-d3f4-43d3-b5ad-82b03e1c5481\",\n \"userName\": \"jdbfjl\",\n \"email\": \"jdfbaj@gmail.com\",\n \"bio\": \"Duuude\",\n \"avatar\": \"sjldflaeulajsnlnaefb\",\n \"followerCount\": 0,\n \"followeeCount\": 0,\n \"verified\": false,\n \"followers\": [\n {},\n {},\n {}\n ],\n \"followees\": [\n {}\n ]\n }\n```\n\n```text\n{\n \"id\": \"5ff4ec30-d3f4-43d3-b5ad-82b03e1c5481\",\n \"createdAt\": \"2021-08-11T11:07:11.688Z\",\n \"updatedAt\": \"2021-08-11T11:07:11.688Z\",\n \"userName\": \"ashdviah\",\n \"email\": \"hsdvhas@gmail.com\",\n \"bio\": \"I am Handsome\",\n \"avatar\": \"sjldflaeulajsnlnaefb\",\n \"followerCount\": 0,\n \"followeeCount\": 0,\n \"verified\": false,\n \"followers\": [\n {\n \"id\": \"db1d30c6-5607-4d87-8838-69f906c3c44e\",\n \"createdAt\": \"2021-08-11T11:09:33.018Z\",\n \"updatedAt\": \"2021-08-11T11:09:33.018Z\"\n },\n {\n \"id\": \"31492cd6-7c56-48f6-aff3-792a980b5100\",\n \"createdAt\": \"2021-08-11T11:11:01.288Z\",\n \"updatedAt\": \"2021-08-11T11:11:01.288Z\"\n },\n ],\n \"followees\": [\n {\n \"id\": \"ab095d0d-b9fa-41a4-be35-13fe9dd6f7a1\",\n \"createdAt\": \"2021-08-11T12:55:18.139Z\",\n \"updatedAt\": \"2021-08-11T12:55:18.139Z\"\n }\n ]\n }\n```\n\n```text\nclass mock {\n @Expose() id : string;\n @Expose() createdAt : Date;\n @Expose() updatedAt : Date;\n}\n\nexport class UserDto {\n @Expose()\n id : string;\n \n @Expose()\n userName : string;\n \n @Expose()\n email : string;\n\n @Expose()\n bio : string;\n\n @Expose()\n avatar : string;\n\n @Expose()\n followerCount : number;\n\n @Expose()\n followeeCount : number;\n\n @Expose()\n verified : boolean;\n\n @Expose()\n followers : Array<mock>;\n\n @Expose()\n followees : Array<mock>;\n}\n```\n\n```text\nexport function Serialize(dto: ClassConstructor) {\n return UseInterceptors(new Serializeinterceptor(dto));\n}\n\nexport class Serializeinterceptor implements NestInterceptor {\n constructor(private dto: any) {}\n\n intercept(context: ExecutionContext, handler: CallHandler) {\n return handler.handle().pipe(\n map((data: any) => {\n return plainToClass(this.dto, data, {\n excludeExtraneousValues: true,\n });\n }),\n );\n }\n}\n```\n\n```text\nUserDto\n```\n\n```text\n@Serialize(UserDto)\n```\n\n```text\n@Type(() => ClassType)\n```\n\n```text\n@Type(() => mock)\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":268,"estimatedTokens":1252}}217{"id":"stack-70065624","source":"stackoverflow","questionId":70065624,"title":"TypeORM, add condition in `where` if value is presented and not empty string","tags":["node.js","nestjs","typeorm","node.js-typeorm"],"text":"Title: TypeORM, add condition in `where` if value is presented and not empty string\nTags: node.js, nestjs, typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nI am using TypeOrm in my node.js project. I know to find a record from database I can do :\n\n```\nuserRepository.find({ where: { firstName: \"John\" } });\n```\n\nIt executes query:\n\n```\nSELECT * FROM \"user\"\nWHERE \"firstName\" = 'John'\n```\n\nBut now I need do add another filed check in \"where\" condition only if the value is presented. For example, I want to also check `company` in SQL \"where\" condition, but only if `company` value is presented.\n\nI tried following, I wonder can I do the following by giving a default empty string `''` if `company` doesn't present then pass it to `find` function's `where`?\n\n```\nconst company = params.company ? params.company : '';\n\nuserRepository.find({ where: { firstName: \"John\", company: company } });\n```\n\nBut it would still add `\"company\"=''` in the final SQL query which is not good. I wonder is there an existing function in TypeORM that could dynamically decide only add more condition in `where` if value is presented and not empty string?\n\n========================================\n\nTop Answer:\nNote that you don't get type safety when using spread operator. Instead you can conditionally set the property to undefined. Undefined properties in the where clause are excluded from the query. Nulls however are included.\n\nSo instead of:\n\n```\nuserRepository.find({\n where: {\n firstName: \"John\",\n ...(params?.company && { company: params.company }),\n }\n});\n```\n\nYou can write:\n\n```\nuserRepository.find({\n where: {\n firstName: \"John\",\n company: params?.company ? params.company : undefined,\n }\n});\n\nuserRepository.find({\n where: {\n firstName: \"John\",\n company: params?.company || undefined,\n }\n});\n```\n\nOr with nested properties:\n\n```\nuserRepository.find({\n where: {\n firstName: \"John\",\n company: params?.company?.name && { name: params.company.name } || undefined,\n }\n});\n\nuserRepository.find({\n where: {\n firstName: \"John\",\n company: { name: params?.company?.name || undefined},\n }\n});\n```\n\n========================================\n\nCode:\n```text\nuserRepository.find({ where: { firstName: \"John\" } });\n```\n\n```text\nSELECT * FROM \"user\"\nWHERE \"firstName\" = 'John'\n```\n\n```text\nconst company = params.company ? params.company : '';\n\nuserRepository.find({ where: { firstName: \"John\", company: company } });\n```\n\n```text\ncompany\n```\n\n```text\ncompany\n```\n\n```text\n''\n```\n\n```text\ncompany\n```\n\n```text\nfind\n```\n\n```text\nwhere\n```\n\n```text\n\"company\"=''\n```\n\n```text\nwhere\n```\n\n```text\nuserRepository.find({\n where: {\n firstName: \"John\",\n ...(params?.company && { company: params.company }),\n }\n});\n```\n\n```text\n...(undefined && { company: undefined })\n```\n\n```text\n...('company' && { company: 'company' })\n```\n\n```js\nconst companyTestWithValue = 'company';\nconst companyTestWithoutValue = '';\n\nconst whereWithValue = {\n firstName: 'John',\n ...(companyTestWithValue && { company: companyTestWithValue }),\n};\n\nconst whereWithoutValue = {\n firstName: 'John',\n ...(companyTestWithoutValue && { company: companyTestWithoutValue }),\n};\n\nconsole.log('whereWithValue:', whereWithValue);\nconsole.log('whereWithoutValue:', whereWithoutValue);\n```\n\n```text\nparams.company\n```\n\n```text\nundefined\n```\n\n```text\nundefined\n```\n\n```text\n...{}\n```\n\n```text\nparams.company\n```\n\n```text\n...{company: 'company'}\n```\n\n```text\nif(params.company){\n userRepository.find({ where: { firstName: \"John\", company: company } });\n } else{\n userRepository.find({ where: { firstName: \"John\" } });\n }\n```\n\n```text\nuserRepository.find({\n where: {\n firstName: \"John\",\n ...(params?.company && { company: params.company }),\n }\n});\n```\n\n```text\nuserRepository.find({\n where: {\n firstName: \"John\",\n company: params?.company ? params.company : undefined,\n }\n});\n\nuserRepository.find({\n where: {\n firstName: \"John\",\n company: params?.company || undefined,\n }\n});\n```\n\n```text\nuserRepository.find({\n where: {\n firstName: \"John\",\n company: params?.company?.name && { name: params.company.name } || undefined,\n }\n});\n\nuserRepository.find({\n where: {\n firstName: \"John\",\n company: { name: params?.company?.name || undefined},\n }\n});\n```\n\n```text\nuserRepository.find({\n where: getWhere([\n {\n field: \"firstName\",\n searchTerm:\"John\",\n },\n {\n field: \"company.name\",\n searchTerm:\"company\",\n }\n ])\n });\n```\n\n========================================\n\nComments:\n- That's smart! Thanks!\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":26,"totalLines":260,"estimatedTokens":1217}}218{"id":"stack-63244163","source":"stackoverflow","questionId":63244163,"title":"NestJS Do I need DTO's along with entities?","tags":["node.js","nestjs","typeorm"],"text":"Title: NestJS Do I need DTO's along with entities?\nTags: node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am creating simple service, that will do simple CRUD.\nSo far I have the **entity** user:\n\n```\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n username: string;\n\n @Column({ name: \"first_name\" })\n firstName: string;\n\n @Column({ name: \"last_name\" })\n lastName: string;\n\n @Column({ name: \"date_of_birth\" })\n birthDate: string;\n}\n```\n\nController:\n\n```\nimport { Controller, Get, Query } from '@nestjs/common';\nimport { UsersService } from './users.service';\n\n@Controller('api/v1/backoffice')\nexport class UsersController {\n constructor(private readonly usersService: UsersService) {}\n\n @Get(':username')\n findOne(@Query('username') username: string) {\n return this.usersService.findByUsername(username);\n }\n}\n```\n\nService:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository, getRepository } from 'typeorm';\nimport { User } from './user.entity';\n\n@Injectable()\nexport class UsersService {\n constructor(\n @InjectRepository(User)\n private readonly usersRepository: Repository,\n ) {}\n\n findByUsername(username: string): Promise {\n return this.usersRepository.findOne({ username });\n }\n}\n```\n\nWith this basic example, I return values from the DB, where some Columns are rename: first_name --> firstName\n\nIt does serve my purpose, but on so many places, I see DTO's being used. I know I am not doing correct things, and that I should start using it as well.\nHow would I use the DTO approach with my example?\n\nI am trying to grasp the concept here.\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n username: string;\n\n @Column({ name: \"first_name\" })\n firstName: string;\n\n @Column({ name: \"last_name\" })\n lastName: string;\n\n @Column({ name: \"date_of_birth\" })\n birthDate: string;\n}\n```\n\n```text\nimport { Controller, Get, Query } from '@nestjs/common';\nimport { UsersService } from './users.service';\n\n@Controller('api/v1/backoffice')\nexport class UsersController {\n constructor(private readonly usersService: UsersService) {}\n\n @Get(':username')\n findOne(@Query('username') username: string) {\n return this.usersService.findByUsername(username);\n }\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository, getRepository } from 'typeorm';\nimport { User } from './user.entity';\n\n@Injectable()\nexport class UsersService {\n constructor(\n @InjectRepository(User)\n private readonly usersRepository: Repository<User>,\n ) {}\n\n\n findByUsername(username: string): Promise<User | undefined> {\n return this.usersRepository.findOne({ username });\n }\n}\n```\n\n```js\nimport { IsNumber, IsString } from 'class-validator';\nimport { Exclude, Expose } from 'class-transformer';\n\n@Exclude()\nexport class UserResponseDto {\n @Expose()\n @IsNumber()\n id: number;\n\n @Expose()\n @IsString()\n username: string;\n\n @Expose()\n @IsString()\n firstName: string;\n\n @Expose()\n @IsString()\n lastName: string;\n\n @Expose()\n @IsString()\n birthDate: string;\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository, getRepository } from 'typeorm';\nimport { User } from './user.entity';\n\n@Injectable()\nexport class UsersService {\n constructor(\n @InjectRepository(User)\n private readonly usersRepository: Repository<User>,\n ) {}\n\n\n async findByUsername(username: string): Promise<User | undefined> {\n const retrievedUser = await this.usersRepository.findOne({ username });\n\n // instantiate our UserResponseDto from retrievedUser\n const userResponseDto = plainToClass(UserResponseDto, retrievedUser);\n\n // validate our newly instantiated UserResponseDto\n const errors = await validate(userResponseDto);\n if (errors.length) {\n throw new BadRequestException('Invalid user',\nthis.modelHelper.modelErrorsToReadable(errors));\n }\n return userResponseDto;\n }\n}\n```\n\n```js\nimport { ClassSerializerInterceptor, Controller, Get, Query } from '@nestjs/common';\nimport { UsersService } from './users.service';\n\n@Controller('api/v1/backoffice')\n@UseInterceptors(ClassSerializerInterceptor) // <== diff is here\nexport class UsersController {\n constructor(private readonly usersService: UsersService) {}\n\n @Get(':username')\n findOne(@Query('username') username: string) {\n return this.usersService.findByUsername(username);\n }\n}\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository, getRepository } from 'typeorm';\nimport { User } from './user.entity';\n\n@Injectable()\nexport class UsersService {\n constructor(\n @InjectRepository(User)\n private readonly usersRepository: Repository<User>,\n ) {}\n\n\n async findByUsername(username: string): Promise<User | undefined> {\n return this.usersRepository.findOne({ username }); // <== must be an instance of the class, not a plain object\n }\n}\n```\n\n```js\nimport { IsString } from 'class-validator';\nimport { Exclude, Expose } from 'class-transformer';\n\n@Exclude()\nexport class GetUserByUsernameRequestDto {\n @Expose()\n @IsString()\n @IsNotEmpty()\n username: string;\n}\n```\n\n```js\nimport { ClassSerializerInterceptor, Controller, Get, Query } from '@nestjs/common';\nimport { UsersService } from './users.service';\n\n@Controller('api/v1/backoffice')\n@UseInterceptors(ClassSerializerInterceptor) // <== diff is here\n@UsePipes( // <= this is where magic happens :)\n new ValidationPipe({\n forbidUnknownValues: true,\n forbidNonWhitelisted: true,\n transform: true\n })\n)\nexport class UsersController {\n constructor(private readonly usersService: UsersService) {}\n\n @Get(':username')\n findOne(@Param('username') getUserByUsernameReqDto: GetUserByUsernameRequestDto) { \n return this.usersService.findByUsername(getUserByUsernameReqDto.username);\n }\n}\n```\n\n```text\nclass-transformer\n```\n\n```text\nclass-validator\n```\n\n```text\nTypeORM\n```\n\n```text\nuser-response.dto.ts\n```\n\n```text\nUserResponseDto\n```\n\n```text\nUser\n```\n\n```text\nuser-response.dto.ts\n```\n\n```text\nUserResponseDto\n```\n\n```text\nclass-transformer\n```\n\n```text\n@Expose()\n```\n\n```text\nUserResponseDto\n```\n\n```text\n@IsString()\n```\n\n```text\n@IsNumber()\n```\n\n```text\nUserResponseDto\n```\n\n```text\nClassSerializerInterceptor\n```\n\n```text\nEntity\n```\n\n```text\nusers.controller.ts\n```\n\n```text\nusers.service.ts\n```\n\n```text\nclass-transformer\n```\n\n```text\nGetUserByUsernameRequestDto\n```\n\n```text\nget-user-by-username.request.dto.ts\n```\n\n```text\nusers.controller.ts\n```\n\n```text\nValidationPipe\n```\n\n```text\nValidationPipe\n```\n\n========================================\n\nComments:\n- It's way easier than you think. Take a look at this example where you can use TypeORM + class-transformer + class-validator in only 3 lines of code -> HERE. There is also a library that can combine both into one single operation - HERE.\n- Thank you for your time and great explanation. After playing it around, I have come to the same conclusion. Since this is a only search controller, I could do it without DTO, but I need validation on the username property (from the user), and only way I could achieve it is with validation class in DTO.\n- alright, then it's the incoming DTO that needs to be validated, the returned DTO might not need to be validated, but only instantiated with the proper fields you want to expose. I'll edit my answer with the use of Pipes to validate and transform the incoming payload into a DTO\n- Wish I could upvote your answer several times. Thanks again!\n- I'm looking for a solution to have Entity - serializer and validator definition in one place without having trouble if a field is added to entity and update all dtos.","metadata":{"transformedAt":"2026-08-18T18:33:44.700Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":33,"totalLines":366,"estimatedTokens":1981}}219{"id":"stack-66794387","source":"stackoverflow","questionId":66794387,"title":"How to update an entity with relations using QueryBuilder in TypeORM","tags":["node.js","nestjs","typeorm"],"text":"Title: How to update an entity with relations using QueryBuilder in TypeORM\nTags: node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have `UserEntity` and `AddressEntity`, they are related as `OneToOne`, that's one user may have only one address. `UserEntity` has fields `firstName`, `secondName`, `address`. `AddressEntity` has fields `country` and `city`.\n\nIf I wanted to update `UserEntity` without doing it to its relations I would do this:\n\n```\nawait entityManager.getRepository(UserEntity)\n .createQueryBuilder('users')\n .update(UserEntity)\n .set(updateUserObject)\n .where('users.id = :userId', { userId })\n .execute();\n```\n\nwhere `updateUserObject` is formed from a request body. That's to say, if I need to update `firstName`, the object would look like this: `{ firstName: 'Joe' }`. Now what is unclear is how to use that builder if I have the following `updateUserObject`:\n\n```\n{\n firstName: \"Bob\",\n address: {\n \"city\": \"Ottawa\"\n }\n}\n```\n\nThe official documentation does not address such cases.\n\n========================================\n\nCode:\n```text\nawait entityManager.getRepository(UserEntity)\n .createQueryBuilder('users')\n .update(UserEntity)\n .set(updateUserObject)\n .where('users.id = :userId', { userId })\n .execute();\n```\n\n```text\n{\n firstName: \"Bob\",\n address: {\n \"city\": \"Ottawa\"\n }\n}\n```\n\n```text\nUserEntity\n```\n\n```text\nAddressEntity\n```\n\n```text\nOneToOne\n```\n\n```text\nUserEntity\n```\n\n```text\nfirstName\n```\n\n```text\nsecondName\n```\n\n```text\naddress\n```\n\n```text\nAddressEntity\n```\n\n```text\ncountry\n```\n\n```text\ncity\n```\n\n```text\nUserEntity\n```\n\n```text\nupdateUserObject\n```\n\n```text\nfirstName\n```\n\n```text\n{ firstName: 'Joe' }\n```\n\n```text\nupdateUserObject\n```\n\n```js\n@Entity('user')\nexport class UserEntity {\n ...\n\n @OneToOne(\n () => AddressEntity,\n {\n // Make sure that when you delete or update a user, it will affect the\n // corresponding `AddressEntity`\n cascade: true,\n // Make sure when you use `preload`, `AddressEntity` of the user will also\n // return (This means whenever you use any kind of `find` operations on\n // `UserEntity`, it would load this entity as well)\n eager: true\n }\n )\n @JoinColumn()\n address: AddressEntity;\n}\n```\n\n```js\nconst partialUserEntity = {\n id: userId,\n firstName: \"Bob\",\n address: {\n \"city\": \"Ottawa\"\n }\n};\n\nconst userRepository = await entityManager.getRepository(UserEntity);\n\n// Here we load the current user entity value from the database and replace\n// all the related values from `partialUserEntity`\nconst updatedUserEntity = await userRepository.preload(partialUserEntity);\n\n// Here we update (create if not exists) `updatedUserEntity` to the database\nawait userRepository.save(updatedUserEntity);\n```\n\n```js\n/* \n * If `updatedUserEntity.address.id` is `undefined`\n */\n\n// `generateIDForAddress` is a function which would return an `id`\nconst generatedIDForAddress = generateIDForAddress();\nconst partialUserEntity = {\n id: userId,\n firstName: \"Bob\",\n address: {\n \"id\": generatedIDForAddress,\n \"city\": \"Ottawa\"\n }\n};\n```\n\n```text\nUserEntity\n```\n\n```text\nentityManager\n```\n\n```text\nUserEntity\n```\n\n```text\nAddressEntity\n```\n\n```text\nid\n```\n\n```text\nAddressEntity\n```\n\n```text\nsave\n```\n\n```text\nUPDATE\n```\n\n```text\nUserEntity\n```\n\n```text\nAddressEntity\n```\n\n```text\npreload\n```\n\n```text\nsave\n```\n\n========================================\n\nComments:\n- I'm not sure if I correctly understand your question. Do you want to partially update the user without mutating the address?\n- you can't update relationships entity,you have to make another query to update the adress\n- @sandrooco yes, I'd like to be able to update the user partially. I'm implementing the `PATCH` verb right now for the user entity.\n- @Youba So basically, it means that if I have n relations I will have to make n requests or something?\n- @Alber no it's not related to requests, you should make another querybuilder for address, like now, you have one for user, you'll add another one for address because it is another entity\n- @Youba well I meant requests to the DB. I mean that I have one query builder for user and then to update my user I execute the QB using `await` and then I will fire off another query with one more query builder for the address entity. Am I correct?\n- @Alber yes, you right, just to let you know in SQL we should do the same we don't have the ability to update in the same query\n- Wow, sounds great! I've already implemented it somewhat differently though but I will try your method later. Perhaps I will have some question. Yaay, thank you! :)","metadata":{"transformedAt":"2026-08-18T18:33:44.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":32,"totalLines":229,"estimatedTokens":1186}}220{"id":"stack-54493998","source":"stackoverflow","questionId":54493998,"title":"Do not pass e2e tests in framework NestJS","tags":["javascript","typescript","e2e-testing","nestjs","typeorm"],"text":"Title: Do not pass e2e tests in framework NestJS\nTags: javascript, typescript, e2e-testing, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI use the **NestJS** framework. When using **@nestjs/typeorm**, I create a repository with users. Using this approach to creating a repository, my **e2e tests**. When working with a database, all data is successfully saved. There are no problems with the connection. Here are my files:\n\n**app.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Connection } from 'typeorm';\nimport { AuthModule } from './modules/auth/auth.module';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot(),\n AuthModule,\n ],\n})\nexport class AppModule {\n constructor(private readonly connection: Connection) { }\n}\n```\n\n**auth.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { Users } from '../../entity/Users';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Users])],\n controllers: [AuthController],\n providers: [AuthService],\n})\nexport class AuthModule {}\n```\n\n**auth.service.ts**\n\n```\n...\n // my repo\n constructor(\n @InjectRepository(Users)\n private readonly usersRepository: Repository,\n ) { }\n...\n```\n\n**app.e2e-spec.ts**\n\n```\nimport { INestApplication } from '@nestjs/common';\nimport { Test } from '@nestjs/testing';\nimport * as request from 'supertest';\nimport { AppModule } from './../src/app.module';\n\ndescribe('AppController (e2e)', () => {\n let app: INestApplication;\n\n beforeAll(async () => {\n const moduleFixture = await Test.createTestingModule({\n imports: [AppModule],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n });\n\n it('/ (GET)', () => {\n return request(app.getHttpServer())\n .get('/')\n .expect(404)\n .expect('{\"statusCode\":404,\"error\":\"Not Found\",\"message\":\"Cannot GET /\"}'); //todo fix me\n });\n});\n```\n\nEverything is written in accordance with the documentation. When you run **npm run test:e2e**, the console gives the following error:\n\n```\n> project@0.0.0 test:e2e \n> jest --config ./test/jest-e2e.json\n\n[Nest] 7206 - 2/2/2019, 5:06:52 PM [TypeOrmModule] Unable to connect to the database. Retrying (1)...\nError: getaddrinfo ENOTFOUND postgres postgres:5432\n at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:57:26)\n[Nest] 7206 - 2/2/2019, 5:06:55 PM [TypeOrmModule] Unable to connect to the database. Retrying (2)... +3234ms\nError: getaddrinfo ENOTFOUND postgres postgres:5432\n at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:57:26)\n FAIL test/app.e2e-spec.ts (6.198s)\n AppController (e2e)\n ✕ / (GET) (6ms)\n\n ● AppController (e2e) › / (GET)\n\n Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.\n\n at mapper (../node_modules/jest-jasmine2/build/queue_runner.js:41:52)\n\n ● AppController (e2e) › / (GET)\n\n TypeError: Cannot read property 'getHttpServer' of undefined\n\n 17 |\n 18 | it('/ (GET)', () => {\n > 19 | return request(app.getHttpServer())\n | ^\n 20 | .get('/')\n 21 | .expect(404)\n 22 | .expect('{\"statusCode\":404,\"error\":\"Not Found\",\"message\":\"Cannot GET /\"}'); // todo fix me\n\n at Object. (app.e2e-spec.ts:19:24)\n```\n\nPlease, help me!\n\n========================================\n\nTop Answer:\nBe sure to close the `app` object with `app.close()` per the example at https://docs.nestjs.com/fundamentals/testing#end-to-end-testing.\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Connection } from 'typeorm';\nimport { AuthModule } from './modules/auth/auth.module';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot(),\n AuthModule,\n ],\n})\nexport class AppModule {\n constructor(private readonly connection: Connection) { }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { Users } from '../../entity/Users';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Users])],\n controllers: [AuthController],\n providers: [AuthService],\n})\nexport class AuthModule {}\n```\n\n```text\n...\n // my repo\n constructor(\n @InjectRepository(Users)\n private readonly usersRepository: Repository<Users>,\n ) { }\n...\n```\n\n```text\nimport { INestApplication } from '@nestjs/common';\nimport { Test } from '@nestjs/testing';\nimport * as request from 'supertest';\nimport { AppModule } from './../src/app.module';\n\ndescribe('AppController (e2e)', () => {\n let app: INestApplication;\n\n beforeAll(async () => {\n const moduleFixture = await Test.createTestingModule({\n imports: [AppModule],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n });\n\n it('/ (GET)', () => {\n return request(app.getHttpServer())\n .get('/')\n .expect(404)\n .expect('{\"statusCode\":404,\"error\":\"Not Found\",\"message\":\"Cannot GET /\"}'); //todo fix me\n });\n});\n```\n\n```text\n> project@0.0.0 test:e2e \n> jest --config ./test/jest-e2e.json\n\n[Nest] 7206 - 2/2/2019, 5:06:52 PM [TypeOrmModule] Unable to connect to the database. Retrying (1)...\nError: getaddrinfo ENOTFOUND postgres postgres:5432\n at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:57:26)\n[Nest] 7206 - 2/2/2019, 5:06:55 PM [TypeOrmModule] Unable to connect to the database. Retrying (2)... +3234ms\nError: getaddrinfo ENOTFOUND postgres postgres:5432\n at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:57:26)\n FAIL test/app.e2e-spec.ts (6.198s)\n AppController (e2e)\n ✕ / (GET) (6ms)\n\n ● AppController (e2e) › / (GET)\n\n Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.\n\n at mapper (../node_modules/jest-jasmine2/build/queue_runner.js:41:52)\n\n ● AppController (e2e) › / (GET)\n\n TypeError: Cannot read property 'getHttpServer' of undefined\n\n 17 |\n 18 | it('/ (GET)', () => {\n > 19 | return request(app.getHttpServer())\n | ^\n 20 | .get('/')\n 21 | .expect(404)\n 22 | .expect('{\"statusCode\":404,\"error\":\"Not Found\",\"message\":\"Cannot GET /\"}'); // todo fix me\n\n at Object.<anonymous> (app.e2e-spec.ts:19:24)\n```\n\n```js\nimport { INestApplication } from '@nestjs/common';\nimport { Test } from '@nestjs/testing';\nimport * as request from 'supertest';\nimport { AppController } from './../src/app.controller';\nimport { AppService } from './../src/app.service';\n\ndescribe('AppController (e2e)', () => {\n let app: INestApplication;\n\n beforeAll(async () => {\n const moduleFixture = await Test.createTestingModule({\n imports: [],\n controllers: [AppController],\n providers: [AppService],\n }).compile();\n\n app = moduleFixture.createNestApplication();\n await app.init();\n });\n\n it('/ (GET)', () => {\n return request(app.getHttpServer())\n .get('/')\n .expect(404)\n .expect('{\"statusCode\":404,\"error\":\"Not Found\",\"message\":\"Cannot GET /\"}'); //todo fix me\n });\n});\n```\n\n```text\nAppModule\n```\n\n```text\nAppController\n```\n\n```text\nAppService\n```\n\n```text\nTypeOrmModule\n```\n\n```text\nTest\n```\n\n```text\noverrideProvider\n```\n\n```text\nuseClass\n```\n\n```text\nuseValue\n```\n\n```text\nuseFactory\n```\n\n```text\nTypeOrmModule\n```\n\n```text\napp\n```\n\n```text\napp.close()\n```\n\n```text\n/api\n```\n\n```text\n// mytest.e2e-spec.ts\nimport * as request from 'supertest';\nimport { Test } from \"@nestjs/testing\";\nimport { INestApplication } from '@nestjs/common';\nimport { MyTestsController } from './myTests.controller';\nimport { MyTestsService } from \".\";\nimport { Warehouse } from './myTest.entity';\nimport { getRepositoryToken } from '@nestjs/typeorm';\n\ndescribe(\"MyTestsController (e2e)\", () => {\n\n let app: INestApplication;\n const myTests = [\n {\n id: \"1ccc2222a-8072-4ff0-b5ff-103cc85f3be6\",\n name: \"Name #1\",\n }\n ];\n\n const myTestsCount = 1;\n const getAllResult = { myTests, myTestsCount };\n // Mock data for service\n let myTestsService = { getAll: () => getAllResult };\n\n beforeAll(async () => {\n const module = await Test.createTestingModule({\n providers: [\n MyTestsService,\n {\n provide: getRepositoryToken(Warehouse),\n useValue: myTestsService\n }\n ],\n controllers: [MyTestsController],\n })\n .overrideProvider(MyTestsService)\n .useValue(myTestsService)\n .compile();\n\n app = module.createNestApplication();\n await app.init();\n });\n\n beforeEach(async () => {});\n\n it(`/GET all myTests`, async() => {\n return await request(app.getHttpServer())\n .get('/myTests')\n .expect(200)\n .expect(myTestsService.getAll());\n });\n\n afterAll(async () => {\n await app.close();\n });\n\n});\n```\n\n```text\n// myTests.service.ts\npublic async getAll(query?): Promise<myTestsRO> {\n const qb = await this.repo.createQueryBuilder(\"myTests\");\n const myTestsCount = await qb.getCount();\n\n if (\"limit\" in query) {\n qb.limit(query.limit);\n }\n\n if (\"offset\" in query) {\n qb.offset(query.offset);\n }\n\n const myTests = await qb\n .getMany()\n .then(myTests =>\n myTests.map(entity => WarehouseDto.fromEntity(entity))\n );\n\n return { myTests, myTestsCount };\n}\n```\n\n```text\n// myTest.controller.ts\n@Get()\npublic async getAll(@Query() query): Promise<myTestsRO> {\n try {\n return await this.myTestsService.getAll(query);\n } catch (error) {\n throw new InternalServerErrorException(error.message);\n }\n}\n```\n\n```text\nTypeOrmModule\n```\n\n========================================\n\nComments:\n- >Unable to connect to the database. Error: getaddrinfo ENOTFOUND postgres postgres:5432\n- What are you using to configure your database connection? Is it something that depends on the environment? Is the env where tests are running able to connect to that db? (like, are you running the tests in docker and docker doesn't have access to that db?)\n- I have the same problem\n- He's doing e2e (end to end) testing, not unit testing.","metadata":{"transformedAt":"2026-08-18T18:33:44.701Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":23,"totalLines":424,"estimatedTokens":2539}}221{"id":"stack-57553534","source":"stackoverflow","questionId":57553534,"title":"Is there any way to bind parameter in select section for TypeORM?","tags":["postgresql","typescript","typeorm"],"text":"Title: Is there any way to bind parameter in select section for TypeORM?\nTags: postgresql, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement search with `pg_trgm` module in PostgreSQL on project written with TypeScript and TypeOrm.\nSQL what works for me looks like this:\n\n```\nSELECT t, similarity(t, 'word') AS sml\n FROM test_trgm\n WHERE t % 'word'\n ORDER BY sml DESC, t;\n```\n\nBut when I started integrate it in my builder I realize that that I can't protect select statement from SQL injection since TypeOrm doesn't offer to bind parameter in any of select methods (such as `SelectQueryBuilder::addSelect`, `SelectQueryBuilder::select`).\n\nExample of my vulnerable method:\n\n```\n...\napplySearch(builder: SelectQueryBuilder, needle: string) {\n if (needle) {\n builder.addSelect(`similarity(title, ${needle})`);\n builder.andWhere('title % :needle', { needle });\n }\n }\n...\n```\n\nMaybe somebody know better way to realize this search in my technology stack?\n\n========================================\n\nTop Answer:\nI needed a similar solution, however yours wouldn't cut it for me. If you would like to change your parameter in the select anyway you should look at `setParameter`, which is what the second param of `addWhere` is doing internally.\n\nhttps://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#using-parameters-to-escape-data\n\nso in your case you could have ran with\n\n```\napplySearch(builder: SelectQueryBuilder, needle: string) {\n if (needle) {\n builder.addSelect(`similarity(title, :title)`);\n builder.andWhere('title % :needle', { needle });\n builder.setParameter('title', needle);\n }\n }\n```\n\n========================================\n\nCode:\n```sql\nSELECT t, similarity(t, 'word') AS sml\n FROM test_trgm\n WHERE t % 'word'\n ORDER BY sml DESC, t;\n```\n\n```text\n...\napplySearch(builder: SelectQueryBuilder<any>, needle: string) {\n if (needle) {\n builder.addSelect(`similarity(title, ${needle})`);\n builder.andWhere('title % :needle', { needle });\n }\n }\n...\n```\n\n```text\npg_trgm\n```\n\n```text\nSelectQueryBuilder::addSelect\n```\n\n```text\nSelectQueryBuilder::select\n```\n\n```js\napplySearch(builder: SelectQueryBuilder<any>, needle: string) {\n if (needle) {\n builder.addSelect(`similarity(title, :needle)`);\n builder.andWhere('title % :needle', { needle });\n }\n }\n```\n\n```text\nwhere\n```\n\n```text\nselect\n```\n\n```text\napplySearch(builder: SelectQueryBuilder<any>, needle: string) {\n if (needle) {\n builder.addSelect(`similarity(title, :title)`);\n builder.andWhere('title % :needle', { needle });\n builder.setParameter('title', needle);\n }\n }\n```\n\n```text\nsetParameter\n```\n\n```text\naddWhere\n```\n\n========================================\n\nComments:\n- The use of the query builder is to escape the parameters, all parameters should be escaped. You can try it yourself and see the output query. Read : github.com/typeorm/typeorm/issues/3696","metadata":{"transformedAt":"2026-08-18T18:33:44.701Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":123,"estimatedTokens":734}}222{"id":"stack-67755221","source":"stackoverflow","questionId":67755221,"title":"How to specify constraint name in TypeOrm for postgresql","tags":["typeorm","node.js-typeorm"],"text":"Title: How to specify constraint name in TypeOrm for postgresql\nTags: typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nI would like to SQL naming standards for Primary and Foreign Key names.\nOne such approach is in Naming conventions in SQL.\nFor the Primary key, the name should be in the format PK_. The PrimaryGeneratedColumn decorator should allow you to enter the name.\nFor Foreign Key, the name should be in the format FK__. This could be in the relation decorator.\n\nI cannot see how to achieve this.\n\nCurrently the constraints names do not have any semantic meaning - FK_f38670e509f911de73d91cab5bb\n\nCould you let me know if there is another way to achieve this?\n\nMany thanks\n\n========================================\n\nTop Answer:\nFor primary key:\n\n```\n@PrimaryColumn('uuid', { primaryKeyConstraintName: 'custom' })\nid: string;\n```\n\nFor foreign key:\n\n```\n@ManyToOne(() => Currency, {})\n@JoinColumn({\nname: 'currencyId',\nreferencedColumnName: 'id',\nforeignKeyConstraintName: 'custom',\n})\ncurrency: Currency;\n```\n\nFor unique key:\n\n```\n@Unique('custom', ['username'])\n@Column({ length: 200 })\nusername: string;\n```\n\n========================================\n\nCode:\n```text\n@Entity()\n@Unique('UNIQUE_EMAIL_ADDRESS', ['address'])\nexport class Email {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column({ type: 'varchar', length: 64 })\n address: string;\n}\n```\n\n```text\n@JoinColumn([{ name: \"user_id\", referencedColumnName: \"id\", foreignKeyConstraintName: \"fkey_constraint_name\"}])\n```\n\n```text\nforeignKeyConstraintName\n```\n\n```text\n@PrimaryColumn('uuid', { primaryKeyConstraintName: 'custom' })\nid: string;\n```\n\n```text\n@ManyToOne(() => Currency, {})\n@JoinColumn({\nname: 'currencyId',\nreferencedColumnName: 'id',\nforeignKeyConstraintName: 'custom',\n})\ncurrency: Currency;\n```\n\n```text\n@Unique('custom', ['username'])\n@Column({ length: 200 })\nusername: string;\n```\n\n========================================\n\nComments:\n- This doesn't answer the question as the issue is not with naming custom indices but the auto-generated ones such as primary key and foreign key constraints as given in the example. It just doesn't seem to be an option with TypeORM.\n- For anyone not seeing these options: they were just added in v0.3.7 (June 2022). If you don't have that version, your other option is a custom naming strategy.\n- @Paul , I am working with version 0.2.29. When I add custom naming strategies some constrains renames correctly some don't. I noted that primary keys never renamed according to the naming strategy. Do you have any clue why it happens?","metadata":{"transformedAt":"2026-08-18T18:33:44.701Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":98,"estimatedTokens":642}}223{"id":"stack-66443771","source":"stackoverflow","questionId":66443771,"title":"NestJS: Case-insensitive search in PostgreSQL","tags":["node.js","postgresql","typeorm"],"text":"Title: NestJS: Case-insensitive search in PostgreSQL\nTags: node.js, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nIs there any way to do a case-insensitive search with NestJS in PostgreSQL?\n\nI've succeeded in doing a case-sensitive search:\n\n`let result = await myRepository.findOne({firstName: fName, lastName: lName});`\n\nI'm trying to change it to a case-insensitive search.\n\n========================================\n\nCode:\n```text\nlet result = await myRepository.findOne({firstName: fName, lastName: lName});\n```\n\n```js\nimport {ILike} from \"typeorm\";\n\nconst loadedPosts = await connection.getRepository(Post).find({\n title: ILike(\"%out #%\")\n});\n```\n\n```text\nILike\n```\n\n```text\nILIKE\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":35,"estimatedTokens":175}}224{"id":"stack-57391545","source":"stackoverflow","questionId":57391545,"title":"\"QueryFailedError: invalid input syntax for integer:\" when querying on type float","tags":["postgresql","nestjs","typeorm"],"text":"Title: \"QueryFailedError: invalid input syntax for integer:\" when querying on type float\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nWhen querying the database using the TypeORM QueryBuilder() I get: \n\n```\nQueryFailedError: invalid input syntax for integer: \"X\"\n```\n\nWith X being the value stored in the DB.\n\nOriginally my entity was of type;\n\n```\n{type: 'decimal', precision: 5, scale: 2 }\nvalue: number\n```\n\nSince I have changed it to: \n\n```\n{type: 'real'}\nvalue: string\n```\n\nand tried: \n\n```\n'float'\nvalue: string\n```\n\nAll three types throw the same error. However, if the value in the DB doesn't have any decimal places - it works fine. \n\nI am running Postgres v11.4, TypeORM v0.2.18 and Nest.js v6.5.3\n\nThe entity definition: \n\n```\nexport class Entity extends BaseEntity {\n\n @Column('float')\n value: string;\n}\n```\n\nThe query:\n\n```\nconst current = await this.entityRepo\n .createQueryBuilder('uL')\n .leftJoin('uL.user', 'user')\n .leftJoinAndSelect('uL.currentLevel', 'cL')\n .where('user.id = :id', { id: userId })\n .getOne();\n```\n\nI am expecting the entity to be returned with the value being of correct decimal spacing.\n\n========================================\n\nCode:\n```text\nQueryFailedError: invalid input syntax for integer: \"X\"\n```\n\n```text\n{type: 'decimal', precision: 5, scale: 2 }\nvalue: number\n```\n\n```text\n{type: 'real'}\nvalue: string\n```\n\n```text\n'float'\nvalue: string\n```\n\n```text\nexport class Entity extends BaseEntity {\n\n @Column('float')\n value: string;\n}\n```\n\n```text\nconst current = await this.entityRepo\n .createQueryBuilder('uL')\n .leftJoin('uL.user', 'user')\n .leftJoinAndSelect('uL.currentLevel', 'cL')\n .where('user.id = :id', { id: userId })\n .getOne();\n```\n\n```js\n@Column()\nvalue: number;\n```\n\n```js\n@Column({type: 'real'})\nvalue: string;\n```\n\n```sh\nnpm run typeorm:migrate ChangedNumbersTypeToReal\nnpm run build; npm run typeorm:run\n```\n\n========================================\n\nComments:\n- Thanks, it helped me, the only observation is that here I had to clean up the changed column before running the migration","metadata":{"transformedAt":"2026-08-18T18:33:44.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":119,"estimatedTokens":532}}225{"id":"stack-72764116","source":"stackoverflow","questionId":72764116,"title":"create a primary key for a one-to-one relationship","tags":["typeorm","nest"],"text":"Title: create a primary key for a one-to-one relationship\nTags: typeorm, nest\nSource: Stack Overflow\n\nQuestion:\nBackground:\n\nSince any unique entity data is a candidate key to a table, any data column constrained as `unique` is a candidate key. What is the syntax for a foreign key to be constrained as unique and a primary key. E.g. I have entities:\n\n```\n@Entity()\nexport class A extends BaseEntity {\n PrimaryColumn()\n id: number;\n} \n \n@Entity()\nexport class B extends BaseEntity() {\n @OneToOne(() => A) As marked above, I'd like the foreign key to be unique and the primary key of B.\n\nWhat I've tried so far:\n\nI thought I had found the solution, but this syntax seems outdated; the `RelationOptions` does not contain the `primary` property:\n\n```\n@OneToOne( type => A, {primary: true})\n@JoinColumn()\na: A\n```\n\nAlso, it does seem possible to mark a column as unique using the @Unique decorator, but, would like to know if there's a better approach to making the column unique in this case.\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class A extends BaseEntity {\n PrimaryColumn()\n id: number;\n} \n \n@Entity()\nexport class B extends BaseEntity() {\n @OneToOne(() => A) <---- need to set this foreign key unique and the primary key of B\n @JoinColumn()\n a: A;\n}\n```\n\n```text\n@OneToOne( type => A, {primary: true})\n@JoinColumn()\na: A\n```\n\n```text\nunique\n```\n\n```text\nRelationOptions\n```\n\n```text\nprimary\n```\n\n```text\n@ManyToOne(() => User, { primary: true })\nuser: User\n```\n\n```text\n@PrimaryColumn()\nuserId: number\n\n@ManyToOne(() => User)\nuser: User\n```\n\n```text\n@PrimaryColumn()\nuserFirstName: string\n\n@PrimaryColumn()\nuserLastName: string\n\n@ManyToOne(() => User)\nuser: User\n```\n\n========================================\n\nComments:\n- This particular statement seems to be important: `Primary column name must match the relation name + join column name on related entity.`\n- it also seem to be possible to rename the relationship column using the `@JoinColumn({name: 'newName'})`","metadata":{"transformedAt":"2026-08-18T18:33:44.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":97,"estimatedTokens":503}}226{"id":"stack-66687397","source":"stackoverflow","questionId":66687397,"title":"Computed column with alias is not mapping into TypeORM Entity","tags":["mysql","typescript","typeorm","calculated-columns"],"text":"Title: Computed column with alias is not mapping into TypeORM Entity\nTags: mysql, typescript, typeorm, calculated-columns\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get data from a table of a **MySQL** database using **TypeORM** in my **Express.js** project.\n\nI'm using `QueryBuilder` to get data.\n\n**My implementation:**\n\n```\nconst result = await this.repository.createQueryBuilder(\"post\")\n .skip((request.PageNo - 1) * request.PageSize)\n .take(request.PageSize)\n .select([\n \"post.Id\",\n \"post.Title\",\n \"SUBSTRING(post.Content, 1, 150) AS post_Content\",\n \"post.ReadTime\",\n \"post.CreatedDate\"\n ])\n .getRawAndEntities();\n```\n\n**Result:**\n\n```\n{\n raw: [\n TextRow {\n post_Id: '457457',\n post_CreatedDate: 2021-03-17T18:00:00.000Z,\n post_Title: 'This is a random title',\n post_ReadTime: 3,\n post_Content: \"If you're looking for random paragraphs, you've come to the right place. When a random word or a random sentence isn't quite enough, the next logical \"\n }\n ],\n entities: [\n Post {\n CreatedBy: '',\n CreatedDate: 2021-03-17T18:00:00.000Z,\n Content: '',\n Title: 'This is a random title',\n ReadTime: 3,\n IsFeatured: false,\n Id: '457457'\n }\n ]\n}\n```\n\n**Expectation:**\nAs you can see, I need a substring of the `Content` column. I've added alias as TypeORM convention, I think. But the column is not being mapped to the property.\n\nI've also got the raw data, where you can see the substring of the column with alias is working.\n\n**Alternates I've tried:**\n\n- `\"SUBSTRING(post.Content, 1, 150)\"`\n\n- `\"SUBSTRING(post.Content, 1, 150) AS Content\"`\n\n- `\"SUBSTRING(post.Content, 1, 150) AS post.Content\"`\n\n- \"SUBSTRING(post.Content, 1, 150) AS `post.Content`\"\n\nBut not a single one maps the `Content` column to the `Content` property of the `Post` entity.\n\n**Note:** The `Content` column is only mapped when I'm not using any alias.\n\n**For trace:**\nGenerated Raw SQLs:\n\nWhen not using alias\n\nSELECT `post`.`Id` AS `post_Id`, `post`.`CreatedDate` AS `post_CreatedDate`, `post`.`Title` AS `post_Title`, `post`.`Content` AS `post_Content`, `post`.`ReadTime` AS `post_ReadTime` FROM `Posts` `post` LIMIT 10\n\nWhen using alias\n\nSELECT `post`.`Id` AS `post_Id`, `post`.`CreatedDate` AS `post_CreatedDate`, `post`.`Title` AS `post_Title`, `post`.`ReadTime` AS `post_ReadTime`, SUBSTRING(`post`.`Content`, 1, 150) AS `post_Content` FROM `Posts`\n`post` LIMIT 10\n\n**Please help!!!**\n\n**Edit (Working Solution):**\n\n```\nconst result = await this.repository.createQueryBuilder(\"post\")\n .skip((request.PageNo - 1) * request.PageSize)\n .take(request.PageSize)\n .select([\n \"post.Id\",\n \"post.Title\",\n \"post.Content\",\n \"SUBSTRING(post.Content, 1, 150) AS post_Content\",\n \"post.ReadTime\",\n \"post.CreatedDate\"\n ])\n .getMany();\n```\n\n========================================\n\nCode:\n```text\nconst result = await this.repository.createQueryBuilder(\"post\")\n .skip((request.PageNo - 1) * request.PageSize)\n .take(request.PageSize)\n .select([\n \"post.Id\",\n \"post.Title\",\n \"SUBSTRING(post.Content, 1, 150) AS post_Content\",\n \"post.ReadTime\",\n \"post.CreatedDate\"\n ])\n .getRawAndEntities();\n```\n\n```text\n{\n raw: [\n TextRow {\n post_Id: '457457',\n post_CreatedDate: 2021-03-17T18:00:00.000Z,\n post_Title: 'This is a random title',\n post_ReadTime: 3,\n post_Content: \"If you're looking for random paragraphs, you've come to the right place. When a random word or a random sentence isn't quite enough, the next logical \"\n }\n ],\n entities: [\n Post {\n CreatedBy: '',\n CreatedDate: 2021-03-17T18:00:00.000Z,\n Content: '',\n Title: 'This is a random title',\n ReadTime: 3,\n IsFeatured: false,\n Id: '457457'\n }\n ]\n}\n```\n\n```text\nconst result = await this.repository.createQueryBuilder(\"post\")\n .skip((request.PageNo - 1) * request.PageSize)\n .take(request.PageSize)\n .select([\n \"post.Id\",\n \"post.Title\",\n \"post.Content\",\n \"SUBSTRING(post.Content, 1, 150) AS post_Content\",\n \"post.ReadTime\",\n \"post.CreatedDate\"\n ])\n .getMany();\n```\n\n```text\nQueryBuilder\n```\n\n```text\nContent\n```\n\n```text\n\"SUBSTRING(post.Content, 1, 150)\"\n```\n\n```text\n\"SUBSTRING(post.Content, 1, 150) AS Content\"\n```\n\n```text\n\"SUBSTRING(post.Content, 1, 150) AS post.Content\"\n```\n\n```text\nContent\n```\n\n```text\nContent\n```\n\n```text\nPost\n```\n\n```text\nContent\n```\n\n```text\n@Column({ select: false } )\nContent: string;\n```\n\n```text\naddSelect(\"SUBSTRING(post.Content,1,3)\", \"post_Content\")\n```\n\n```text\n{ select: false }\n```\n\n```text\naddSelect(selection, alias)\n```\n\n========================================\n\nComments:\n- `addSelect(selection, alias)` is not available when array is passed into select extension. `@Column({ select: false } )` did the trick for me. Thanks.\n- Indeed, the array doesn't work with alias. I'm glad the workaround worked for you in the end. I'm learning the tricks by answering questions like this.\n- But, I've found an issue with my workaround, that `@Column({ select: false } )` directly doesn't work. You can see at my working solution I've selected the Content column two times, one time without an alias and the other with an alias. So, the SQL selects the column two times and magically maps the one with the alias. But without the column without an alias, it doesn't map.\n- Did you try: .select([columns excluding calculated]).addSelect(\"calculated column\", \"Alias\") ?\n- I tested \".select().addSelect(), and found like you, it doesn't work! It seems \".select()\" in the query breaks it. You can use .addSelect with array, that seems work. Just make sure you remove any \".select\".\n- `addSelect()` selects all the columns with the calculated column. So, if I want to fetch only one calculated column from the table, it will provide me all the columns with the calculated one. Quite frustrating.\n- Yes it's frustrating. All I can suggest if you don't want all the columns, is put {select: false } on all the columns of your entity, and when you need them you have to add them using \"addSelect\".\n- That's the perfect solution for me. Thanks.\n- A convoluted workaround rather than the perfect solution, but I'm glad it's working now.","metadata":{"transformedAt":"2026-08-18T18:33:44.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":224,"estimatedTokens":1625}}227{"id":"stack-75010411","source":"stackoverflow","questionId":75010411,"title":"Float number saves as integer in MySQL using TypeORM","tags":["mysql","node.js","orm","nestjs","typeorm"],"text":"Title: Float number saves as integer in MySQL using TypeORM\nTags: mysql, node.js, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using TypeORM for my Nest.js backend app. When I try to save entity in database:\n\n```\nawait this.dayRepository.save({\n price: item.price,\n ... other columns\n});\n```\n\nAnd my price is float, that float saves in database as integer - always truncated (3.99 round to 3, 5.56 round to 5 etc.). I even try this:\n\n```\nawait this.dayRepository.save({\n price: 3.99,\n ... other columns\n});\n```\n\nAnd it also saves price column in database as 3. I tried to declare my price column in database as float and double - none of that worked. What I'm doing wrong? Or it could be some issue with database?\n\n========================================\n\nCode:\n```text\nawait this.dayRepository.save({\n price: item.price,\n ... other columns\n});\n```\n\n```text\nawait this.dayRepository.save({\n price: 3.99,\n ... other columns\n});\n```\n\n```js\n@Column('decimal', { precision: 6, scale: 2 })\nprice: number\n```\n\n```text\nmysql\n```\n\n```text\nprecision\n```\n\n```text\nscale\n```\n\n```text\nscale\n```\n\n========================================\n\nComments:\n- can you please your entity information, which has information about the price column? Also, did you check your column type on the SQL?","metadata":{"transformedAt":"2026-08-18T18:33:44.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":67,"estimatedTokens":324}}228{"id":"stack-61854512","source":"stackoverflow","questionId":61854512,"title":"NestJS - TypeORM - ManyToOne Entity is undefined","tags":["typescript","entity","nestjs","typeorm","many-to-one"],"text":"Title: NestJS - TypeORM - ManyToOne Entity is undefined\nTags: typescript, entity, nestjs, typeorm, many-to-one\nSource: Stack Overflow\n\nQuestion:\nI am trying to link to entities `Child` & `Client`\n\nSo I have created 2 entities :\n\n```\n// src/children/child.entity.ts\n\n@Entity()\nexport class Child extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n firstname: string;\n\n @Column()\n lastname: string;\n\n @ManyToOne(type => Client, client => client.children, { eager: false })\n client: Client\n\n @Column()\n clientId: number;\n}\n```\n\nand \n\n```\n// src/clients/client.entity.ts\n\n@Entity()\nexport class Client extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n firstname: string;\n\n @Column()\n lastname: string;\n\n @OneToMany(type => Child, child => child.client, { eager: true })\n children: Child[];\n\n}\n```\n\nI'm able to create a `client` & a `child`. When I get a `client`, I can retrieve all his `children`.\n\nBut I am not able to retrieve a `client` with a `child` : \n\nFor example, in `children.controller.ts`\n\nhttps://i.sstatic.net/QKIXK.png\n\nWhen I visit `http://locahost:3000/children/1/parent`\n\nI got on the console : \n\nhttps://i.sstatic.net/hZemK.png\n\nI am really stuck because I don't know how to solve this issue.\n\nHere is `children.module.ts`\n\n```\nimport { Module } from '@nestjs/common';\nimport { ChildrenController } from './children.controller';\nimport { ChildrenService } from './children.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { ChildRepository } from './child.repository';\nimport { ClientRepository } from 'src/clients/client.repository';\nimport { ClientsService } from 'src/clients/clients.service';\nimport { Client } from 'src/clients/client.entity';\n\n@Module({\n imports: [\n TypeOrmModule.forFeature([ChildRepository, ClientRepository, Client]),\n ],\n controllers: [ChildrenController],\n providers: [ChildrenService, ClientsService]\n})\nexport class ChildrenModule {}\n```\n\nHere is `typeorm.config`\n\n```\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nexport const typeOrmConfig: TypeOrmModuleOptions = {\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'myusername',\n password: '',\n database: 'mydatabase',\n entities: [__dirname + '/../**/*.entity.{js,ts}'],\n synchronize: true,\n}\n```\n\n**Edit 1 :**\n\n`children.controller.ts`\n\n```\n// src/children/children.controller.ts\n\n@Controller('children')\nexport class ChildrenController {\n\n constructor(\n private childrenService: ChildrenService,\n private clientsService: ClientsService\n ) {}\n\n @Get('/:id')\n async getChild(id: number): Promise {\n return await this.childrenService.getChild(id);\n }\n}\n```\n\n`children.service.ts`\n\n```\n// src/children/children.service.ts\n\n@Injectable()\nexport class ChildrenService {\n constructor(\n @InjectRepository(ChildRepository)\n private childRepository: ChildRepository,\n @InjectRepository(ClientRepository)\n private clientRepository: ClientRepository\n ) {}\n\n async getChild(id: number): Promise {\n return await this.childRepository.findOne(id)\n }\n}\n```\n\nThanks for you help 😀\n\n========================================\n\nTop Answer:\nas @Yevhenii mention, you forgot to add JoinColumn but you have to specify the client column: \n\n```\n@Entity()\nexport class Child extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n firstname: string;\n\n @Column()\n lastname: string;\n\n @ManyToOne(()=> Client, (client) => client.children, { eager: false })\n @JoinColumn([{ name: \"clientId\", referencedColumnName: \"id\" }])\n client: Client\n\n @Column()\n clientId: number;\n}\n```\n\nDon't hesitate to tell me the result.\n\n========================================\n\nCode:\n```js\n// src/children/child.entity.ts\n\n@Entity()\nexport class Child extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n firstname: string;\n\n @Column()\n lastname: string;\n\n @ManyToOne(type => Client, client => client.children, { eager: false })\n client: Client\n\n @Column()\n clientId: number;\n}\n```\n\n```js\n// src/clients/client.entity.ts\n\n@Entity()\nexport class Client extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n firstname: string;\n\n @Column()\n lastname: string;\n\n @OneToMany(type => Child, child => child.client, { eager: true })\n children: Child[];\n\n}\n```\n\n```js\nimport { Module } from '@nestjs/common';\nimport { ChildrenController } from './children.controller';\nimport { ChildrenService } from './children.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { ChildRepository } from './child.repository';\nimport { ClientRepository } from 'src/clients/client.repository';\nimport { ClientsService } from 'src/clients/clients.service';\nimport { Client } from 'src/clients/client.entity';\n\n@Module({\n imports: [\n TypeOrmModule.forFeature([ChildRepository, ClientRepository, Client]),\n ],\n controllers: [ChildrenController],\n providers: [ChildrenService, ClientsService]\n})\nexport class ChildrenModule {}\n```\n\n```js\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nexport const typeOrmConfig: TypeOrmModuleOptions = {\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'myusername',\n password: '',\n database: 'mydatabase',\n entities: [__dirname + '/../**/*.entity.{js,ts}'],\n synchronize: true,\n}\n```\n\n```js\n// src/children/children.controller.ts\n\n@Controller('children')\nexport class ChildrenController {\n\n constructor(\n private childrenService: ChildrenService,\n private clientsService: ClientsService\n ) {}\n\n @Get('/:id')\n async getChild(id: number): Promise<Child> {\n return await this.childrenService.getChild(id);\n }\n}\n```\n\n```js\n// src/children/children.service.ts\n\n@Injectable()\nexport class ChildrenService {\n constructor(\n @InjectRepository(ChildRepository)\n private childRepository: ChildRepository,\n @InjectRepository(ClientRepository)\n private clientRepository: ClientRepository\n ) {}\n\n async getChild(id: number): Promise<Child> {\n return await this.childRepository.findOne(id)\n }\n}\n```\n\n```text\nChild\n```\n\n```text\nClient\n```\n\n```text\nclient\n```\n\n```text\nchild\n```\n\n```text\nclient\n```\n\n```text\nchildren\n```\n\n```text\nclient\n```\n\n```text\nchild\n```\n\n```text\nchildren.controller.ts\n```\n\n```text\nhttp://locahost:3000/children/1/parent\n```\n\n```text\nchildren.module.ts\n```\n\n```text\ntypeorm.config\n```\n\n```text\nchildren.controller.ts\n```\n\n```text\nchildren.service.ts\n```\n\n```js\n@Entity()\nexport class Child extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n firstname: string;\n\n @Column()\n lastname: string;\n\n @ManyToOne(type => Client, client => client.children, { eager: false })\n @JoinColumn()\n client: Client\n\n @Column()\n clientId: number;\n}\n```\n\n```js\nasync getChild(id: number): Promise<Child> {\n return await this.childRepository.findOne(id, {\n relations: ['client']\n })\n }\n```\n\n```js\n@ManyToOne(type => Client, client => client.children, { eager: true })\n @JoinColumn()\n client: Client\n```\n\n```text\n@JoinColumn()\n```\n\n```text\neager\n```\n\n```text\ntrue\n```\n\n```text\nchildren.service.ts\n```\n\n```text\neager\n```\n\n```text\nChild\n```\n\n```text\n@Entity()\nexport class Child extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n firstname: string;\n\n @Column()\n lastname: string;\n\n @ManyToOne(()=> Client, (client) => client.children, { eager: false })\n @JoinColumn([{ name: \"clientId\", referencedColumnName: \"id\" }])\n client: Client\n\n @Column()\n clientId: number;\n}\n```\n\n========================================\n\nComments:\n- what code contains your `getChild` method?\n- I have added the code for getChild to retrieve the child into the database.\n- thanks for your answer ! I still have the issue. I have a restart the server after the update. Not working + I have remove database tables and still not working.\n- after you changed database you need generate migration and apply it\n- I am sorry but I dont how to proceed it. I thought with `synchronize: true` everything will be auto-updated\n- You're right about `synchronize: true`. I've added one more advice to my answer, try it\n- adding `{ relations: ['client'] }` solved the issue ! Thanks a lot !\n- Thanks for you answer. The solution given by Yevhenii is working well.","metadata":{"transformedAt":"2026-08-18T18:33:44.701Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":450,"estimatedTokens":2050}}229{"id":"stack-57762386","source":"stackoverflow","questionId":57762386,"title":"Is there a way (or best practice) to my TypeORM models with the frontend of my code without complete duplication?","tags":["typeorm"],"text":"Title: Is there a way (or best practice) to my TypeORM models with the frontend of my code without complete duplication?\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI would like to use the entities I created with TypeORM in the front-end as well. Is there a clean way of doing this? Or should I keep proceeding as I am.\n\nAt this point, my file structure looks as so (Angular 8 on the front-end): \n\n```\n/server\n /entity\n ExampleEntity.ts\n/app\n /entity\n Example.ts\n```\n\nThey both have the same content, but the front-end one is lacking all TypeORM constructs.\n\n========================================\n\nCode:\n```text\n/server\n /entity\n ExampleEntity.ts\n/app\n /entity\n Example.ts\n```\n\n```text\n{\n ...\n \"compilerOptions\": {\n ...\n \"paths\": {\n \"typeorm\": [\"./node_modules/typeorm/typeorm-model-shim.js\"]\n }\n }\n}\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntypeorm\n```\n\n========================================\n\nComments:\n- This is interesting, do you have a project that you're implementing this in? Would love to see how its done","metadata":{"transformedAt":"2026-08-18T18:33:44.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":56,"estimatedTokens":262}}230{"id":"stack-71659168","source":"stackoverflow","questionId":71659168,"title":"why and when we should use `autoLoadEntities` in nestjs Typeorm","tags":["nestjs","typeorm"],"text":"Title: why and when we should use `autoLoadEntities` in nestjs Typeorm\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am curious to know that why and when we should use `autoLoadEntities` in nestjs Typeorm.\n\n========================================\n\nCode:\n```text\nautoLoadEntities\n```\n\n```text\nautoLoadEntities\n```\n\n```text\nforRoot()\n```\n\n```text\ntrue\n```\n\n```text\nglob\n```\n\n```text\nentity\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":33,"estimatedTokens":101}}231{"id":"stack-69235867","source":"stackoverflow","questionId":69235867,"title":"Typeorm migration not detecting changes properly","tags":["typescript","postgresql","nestjs","typeorm"],"text":"Title: Typeorm migration not detecting changes properly\nTags: typescript, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using typeorm in my nestjs application using a postgresql database. When I try to create a migration to synchronize my database to apply application changes the following query is always existed in generated migration file (I removed some unnecessary queries for extra readability):\n\n```\nexport class portal1631976435381 implements MigrationInterface {\n name = 'portal1631976435381'\n\n public async up(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`ALTER TABLE \"organization\" DROP COLUMN \"isTransporter\"`);\n await queryRunner.query(`ALTER TABLE \"organization\" DROP COLUMN \"crmId\"`);\n await queryRunner.query(`ALTER TABLE \"organization\" DROP COLUMN \"telephoneNumber\"`);\n await queryRunner.query(`ALTER TABLE \"organization\" ADD \"crmId\" character varying`);\n await queryRunner.query(`ALTER TABLE \"organization\" ADD \"telephoneNumber\" character varying`);\n await queryRunner.query(`ALTER TABLE \"organization\" ADD \"isTransporter\" boolean NOT NULL DEFAULT false`);\n await queryRunner.query(`CREATE VIEW \"inventory_based_on_receipt_item_view\" AS SELECT \"ri\".\"id\" AS \"receiptItemId\" from someTableC`);\n await queryRunner.query(`INSERT INTO \"typeorm_metadata\"(\"type\", \"schema\", \"name\", \"value\") VALUES ($1, $2, $3, $4)`, [\"VIEW\",\"public\",\"inventory_based_on_receipt_item_view\",]);\n await queryRunner.query(`CREATE VIEW \"inventory_based_on_receipt_item_view\" AS SELECT \"ri\".\"id\" AS \"receiptItemId\" from someTableB`);\n await queryRunner.query(`INSERT INTO \"typeorm_metadata\"(\"type\", \"schema\", \"name\", \"value\") VALUES ($1, $2, $3, $4)`, [\"VIEW\",\"public\",\"inventory_based_on_receipt_item_view\",]);\n await queryRunner.query(`CREATE VIEW \"receipt_item_transaction_view\" AS SELECT \"ri\".\"id\" AS \"receiptItemId\" from someTableA`)\n await queryRunner.query(`INSERT INTO \"typeorm_metadata\"(\"type\", \"schema\", \"name\", \"value\") VALUES ($1, $2, $3, $4)`, [\"VIEW\",\"public\",...]);\n }\n public async down(queryRunner: QueryRunner): Promise { ... }\n}\n```\n\nNo matter what changes are applied to the application all viewEntities are Dropped and recreated.\n\nAnother problem is that `inventory_based_on_receipt_item_view` is being created two times in the query with 2 slightly different queries although I only have one viewEntity with that name (I don't really know where it is coming from).\nAnother problem is that the 3 columns of organization table (`crmId`, `telephoneNumber` and `isTransporter`) are dropped and recreated with the same detail.\n\nI wanted to know that is there any better way for migrating database tables, maybe with another package (I couldn't find anything useful myself) or any workaround that can optimize my workflow? Cause I need to regenerate the migration file whenever any changes happen to the entities and make sure I remove every single wrong query that is generated.\n\n========================================\n\nCode:\n```js\nexport class portal1631976435381 implements MigrationInterface {\n name = 'portal1631976435381'\n\n public async up(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(`ALTER TABLE \"organization\" DROP COLUMN \"isTransporter\"`);\n await queryRunner.query(`ALTER TABLE \"organization\" DROP COLUMN \"crmId\"`);\n await queryRunner.query(`ALTER TABLE \"organization\" DROP COLUMN \"telephoneNumber\"`);\n await queryRunner.query(`ALTER TABLE \"organization\" ADD \"crmId\" character varying`);\n await queryRunner.query(`ALTER TABLE \"organization\" ADD \"telephoneNumber\" character varying`);\n await queryRunner.query(`ALTER TABLE \"organization\" ADD \"isTransporter\" boolean NOT NULL DEFAULT false`);\n await queryRunner.query(`CREATE VIEW \"inventory_based_on_receipt_item_view\" AS SELECT \"ri\".\"id\" AS \"receiptItemId\" from someTableC`);\n await queryRunner.query(`INSERT INTO \"typeorm_metadata\"(\"type\", \"schema\", \"name\", \"value\") VALUES ($1, $2, $3, $4)`, [\"VIEW\",\"public\",\"inventory_based_on_receipt_item_view\",]);\n await queryRunner.query(`CREATE VIEW \"inventory_based_on_receipt_item_view\" AS SELECT \"ri\".\"id\" AS \"receiptItemId\" from someTableB`);\n await queryRunner.query(`INSERT INTO \"typeorm_metadata\"(\"type\", \"schema\", \"name\", \"value\") VALUES ($1, $2, $3, $4)`, [\"VIEW\",\"public\",\"inventory_based_on_receipt_item_view\",]);\n await queryRunner.query(`CREATE VIEW \"receipt_item_transaction_view\" AS SELECT \"ri\".\"id\" AS \"receiptItemId\" from someTableA`)\n await queryRunner.query(`INSERT INTO \"typeorm_metadata\"(\"type\", \"schema\", \"name\", \"value\") VALUES ($1, $2, $3, $4)`, [\"VIEW\",\"public\",...]);\n }\n public async down(queryRunner: QueryRunner): Promise<void> { ... }\n}\n```\n\n```text\ninventory_based_on_receipt_item_view\n```\n\n```text\ncrmId\n```\n\n```text\ntelephoneNumber\n```\n\n```text\nisTransporter\n```\n\n```text\nmigration:generate\n```\n\n========================================\n\nComments:\n- That's not help. :(","metadata":{"transformedAt":"2026-08-18T18:33:44.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":85,"estimatedTokens":1242}}232{"id":"stack-58437564","source":"stackoverflow","questionId":58437564,"title":"npm run start:dev cannot find module","tags":["nestjs","typeorm"],"text":"Title: npm run start:dev cannot find module\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nnpm run start works fine, but npm run start: dev throws this error:\n\n```\n7:14:22 PM - Found 0 errors. Watching for file changes.\ninternal/modules/cjs/loader.js:638\nthrow err;\n^\nError: Cannot find module 'src/models/note.model'\nat Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)\nat Function.Module._load (internal/modules/cjs/loader.js:562:25)\nat Module.require (internal/modules/cjs/loader.js:692:17)\nat require (internal/modules/cjs/helpers.js:25:18)\nat Object. (C:\\Users\\Anuitex-169\\Desktop\\VersF\\nest\\server\\dist\\note\\note.service.js:17:22)\nat Module._compile (internal/modules/cjs/loader.js:778:30)\nat Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)\nat Module.load (internal/modules/cjs/loader.js:653:32)\nat tryModuleLoad (internal/modules/cjs/loader.js:593:12)\nat Function.Module._load (internal/modules/cjs/loader.js:585:3)\n```\n\nThis error appeared from the very beginning of my project, and I can’t understand why. I decided to forget about this problem since npm run start works well. But somehow uncomfortable (\n\nMy app.module.ts\nMy package.json file:\n\n```\n{\n \"name\": \"server\",\n \"version\": \"0.0.1\",\n \"description\": \"\",\n \"author\": \"\",\n \"license\": \"MIT\",\n \"scripts\": {\n \"build\": \"rimraf dist && tsc -p tsconfig.build.json\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\"\",\n \"start\": \"ts-node -r tsconfig-paths/register src/main.ts\",\n \"start:dev\": \"tsc-watch -p tsconfig.build.json --onSuccess \\\"node dist/main.js\\\"\",\n \"start:debug\": \"tsc-watch -p tsconfig.build.json --onSuccess \\\"node --inspect-brk dist/main.js\\\"\",\n \"start:prod\": \"node dist/main.js\",\n \"lint\": \"tslint -p tsconfig.json -c tslint.json\",\n \"test\": \"jest\",\n \"test:watch\": \"jest --watch\",\n \"test:cov\": \"jest --coverage\",\n \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n },\n \"dependencies\": {\n \"@nestjs/common\": \"^6.0.0\",\n \"@nestjs/core\": \"^6.0.0\",\n \"@nestjs/platform-express\": \"^6.0.0\",\n \"@nestjs/typeorm\": \"^6.1.3\",\n \"mongodb\": \"^3.3.2\",\n \"path\": \"^0.12.7\",\n \"reflect-metadata\": \"^0.1.12\",\n \"rimraf\": \"^2.6.2\",\n \"rxjs\": \"^6.3.3\",\n \"typeorm\": \"^0.2.19\"\n },\n \"devDependencies\": {\n \"@nestjs/testing\": \"^6.0.0\",\n \"@types/express\": \"4.16.1\",\n \"@types/jest\": \"24.0.11\",\n \"@types/multer\": \"^1.3.10\",\n \"@types/node\": \"11.13.4\",\n \"@types/supertest\": \"2.0.7\",\n \"jest\": \"24.7.1\",\n \"prettier\": \"1.17.0\",\n \"supertest\": \"4.0.2\",\n \"ts-jest\": \"24.0.2\",\n \"ts-node\": \"8.1.0\",\n \"tsc-watch\": \"2.2.1\",\n \"tsconfig-paths\": \"3.8.0\",\n \"tslint\": \"5.16.0\",\n \"typescript\": \"3.4.3\"\n },\n \"jest\": {\n \"moduleFileExtensions\": [\n \"js\",\n \"json\",\n \"ts\"\n ],\n \"rootDir\": \".\",\n \"roots\": [\n \"/src/\",\n \"/libs/\",\n \"/apps/\"\n ],\n \"testRegex\": \".spec.ts$\",\n \"transform\": {\n \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n },\n \"coverageDirectory\": \"./coverage\",\n \"testEnvironment\": \"node\"\n }\n }\n```\n\nPlease help me deal with this problem.\n\n========================================\n\nCode:\n```text\n7:14:22 PM - Found 0 errors. Watching for file changes.\ninternal/modules/cjs/loader.js:638\nthrow err;\n^\nError: Cannot find module 'src/models/note.model'\nat Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)\nat Function.Module._load (internal/modules/cjs/loader.js:562:25)\nat Module.require (internal/modules/cjs/loader.js:692:17)\nat require (internal/modules/cjs/helpers.js:25:18)\nat Object.<anonymous> (C:\\Users\\Anuitex-169\\Desktop\\VersF\\nest\\server\\dist\\note\\note.service.js:17:22)\nat Module._compile (internal/modules/cjs/loader.js:778:30)\nat Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)\nat Module.load (internal/modules/cjs/loader.js:653:32)\nat tryModuleLoad (internal/modules/cjs/loader.js:593:12)\nat Function.Module._load (internal/modules/cjs/loader.js:585:3)\n```\n\n```text\n{\n \"name\": \"server\",\n \"version\": \"0.0.1\",\n \"description\": \"\",\n \"author\": \"\",\n \"license\": \"MIT\",\n \"scripts\": {\n \"build\": \"rimraf dist && tsc -p tsconfig.build.json\",\n \"format\": \"prettier --write \\\"src/**/*.ts\\\"\",\n \"start\": \"ts-node -r tsconfig-paths/register src/main.ts\",\n \"start:dev\": \"tsc-watch -p tsconfig.build.json --onSuccess \\\"node dist/main.js\\\"\",\n \"start:debug\": \"tsc-watch -p tsconfig.build.json --onSuccess \\\"node --inspect-brk dist/main.js\\\"\",\n \"start:prod\": \"node dist/main.js\",\n \"lint\": \"tslint -p tsconfig.json -c tslint.json\",\n \"test\": \"jest\",\n \"test:watch\": \"jest --watch\",\n \"test:cov\": \"jest --coverage\",\n \"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\",\n \"test:e2e\": \"jest --config ./test/jest-e2e.json\"\n },\n \"dependencies\": {\n \"@nestjs/common\": \"^6.0.0\",\n \"@nestjs/core\": \"^6.0.0\",\n \"@nestjs/platform-express\": \"^6.0.0\",\n \"@nestjs/typeorm\": \"^6.1.3\",\n \"mongodb\": \"^3.3.2\",\n \"path\": \"^0.12.7\",\n \"reflect-metadata\": \"^0.1.12\",\n \"rimraf\": \"^2.6.2\",\n \"rxjs\": \"^6.3.3\",\n \"typeorm\": \"^0.2.19\"\n },\n \"devDependencies\": {\n \"@nestjs/testing\": \"^6.0.0\",\n \"@types/express\": \"4.16.1\",\n \"@types/jest\": \"24.0.11\",\n \"@types/multer\": \"^1.3.10\",\n \"@types/node\": \"11.13.4\",\n \"@types/supertest\": \"2.0.7\",\n \"jest\": \"24.7.1\",\n \"prettier\": \"1.17.0\",\n \"supertest\": \"4.0.2\",\n \"ts-jest\": \"24.0.2\",\n \"ts-node\": \"8.1.0\",\n \"tsc-watch\": \"2.2.1\",\n \"tsconfig-paths\": \"3.8.0\",\n \"tslint\": \"5.16.0\",\n \"typescript\": \"3.4.3\"\n },\n \"jest\": {\n \"moduleFileExtensions\": [\n \"js\",\n \"json\",\n \"ts\"\n ],\n \"rootDir\": \".\",\n \"roots\": [\n \"<rootDir>/src/\",\n \"<rootDir>/libs/\",\n \"<rootDir>/apps/\"\n ],\n \"testRegex\": \".spec.ts$\",\n \"transform\": {\n \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n },\n \"coverageDirectory\": \"./coverage\",\n \"testEnvironment\": \"node\"\n }\n }\n```\n\n```text\nat Object.<anonymous> (C:\\Users\\Anuitex-169\\Desktop\\VersF\\nest\\server\\dist\\note\\note.service.js:17:22)\n```\n\n```text\nsrc\n```\n\n```text\ndist\n```\n\n```text\nsrc/models/note.model\n```\n\n```text\n../models/note.model\n```\n\n========================================\n\nComments:\n- Jay is very close I believe. Most likely very similar issue: stackoverflow.com/a/57964735/4319037 (both are about dist/dev and correctly locating entities; please note a bit different regexp). Does your `build` run correctly?\n- The glob actually looks correct in this case, using dirname instead of a hardcoded src or dist, in just trying to the stack trace that says the note.service.js is trying to import from src/models/note.model","metadata":{"transformedAt":"2026-08-18T18:33:44.701Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":222,"estimatedTokens":1712}}233{"id":"stack-60733683","source":"stackoverflow","questionId":60733683,"title":"Typeorm deployment on Heroku","tags":["postgresql","heroku","deployment","backend","typeorm"],"text":"Title: Typeorm deployment on Heroku\nTags: postgresql, heroku, deployment, backend, typeorm\nSource: Stack Overflow\n\nQuestion:\n```\n{\n \"name\": \"default\",\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"PG_PASSWORD\",\n \"database\": \"postgres\",\n \"synchronize\": true,\n \"logging\": true,\n \"entities\": [\"src/entity/*.*\"]\n}\n```\n\nThis is my `ormconfig.json`. So Heroku is obviously giving me a connection refused error on my database. I have a Postgres addon set up and I have a DATABASE_URL env variable in my setting page now. If I add a `DATABASE_URL` env,\n\nmy question is how do I get my ormconfig to take that env variable? Because right now host and port and un/pw, etc are all separate and I need to consolidate them down to one config option in my ormconfig.\n\n========================================\n\nCode:\n```text\n{\n \"name\": \"default\",\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"PG_PASSWORD\",\n \"database\": \"postgres\",\n \"synchronize\": true,\n \"logging\": true,\n \"entities\": [\"src/entity/*.*\"]\n}\n```\n\n```text\normconfig.json\n```\n\n```text\nDATABASE_URL\n```\n\n```ts\nimport { getConnectionOptions, ConnectionOptions } from 'typeorm';\nimport dotenv from 'dotenv';\ndotenv.config();\n\nconst getOptions = async () => {\n let connectionOptions: ConnectionOptions;\n connectionOptions = {\n type: 'postgres',\n synchronize: false,\n logging: false,\n extra: {\n ssl: true,\n },\n entities: ['dist/entity/*.*'],\n };\n if (process.env.DATABASE_URL) {\n Object.assign(connectionOptions, { url: process.env.DATABASE_URL });\n } else {\n // gets your default configuration\n // you could get a specific config by name getConnectionOptions('production')\n // or getConnectionOptions(process.env.NODE_ENV)\n connectionOptions = await getConnectionOptions(); \n }\n\n return connectionOptions;\n};\n\nconst connect2Database = async (): Promise<void> => {\n const typeormconfig = await getOptions();\n await createConnection(typeormconfig);\n};\n\nconnect2Database().then(async () => {\n console.log('Connected to database');\n});\n```\n\n```text\n{\n \"name\": \"default\",\n \"type\": \"postgres\",\n \"url: \"postgres://username:password@hostname:5432/databasename\"\n \"synchronize\": false,\n \"logging\": true,\n \"entities\": [\"src/entity/*.*\"]\n}\n```\n\n========================================\n\nComments:\n- Could you try `\"my_url\": \"${DATABASE_URL}\"`?\n- @donquih0te it's a json file. Env vars don't work there. Furthermore his question is how to split the `$DATABASE_URL` into its components.\n- Can you specify which programming language you are using? Python? JavaScript? Bash?\n- TypeScript is the language I'm using\n- I am getting Error: self signed certificate when i am doing with option 2. Any idea ?","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":107,"estimatedTokens":700}}234{"id":"stack-65238655","source":"stackoverflow","questionId":65238655,"title":"Is good to use TypeORM entity models classes in conjuction with NestJS-GraphQL schema type?","tags":["typescript","graphql","nestjs","dry","typeorm"],"text":"Title: Is good to use TypeORM entity models classes in conjuction with NestJS-GraphQL schema type?\nTags: typescript, graphql, nestjs, dry, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm creating a GraphQL API using NestJS and TypeORM. Starting with the classic User entity I've created both the `user.type.ts` and the `user.entity.ts` as described by the Nestjs documentation.\n\nThis is an example of the content:\n\n- `user.entity.ts`\n\n```\n@Entity({ schema: 'mydb', name: 'userList' })\nexport class User {\n\n @Column('varchar', { name: 'guid', unique: true, length: 36 })\n guid: string;\n\n @Column('varchar', { name: 'firstName', length: 50 })\n firstName: string;\n\n @Column('varchar', { name: 'lastName', length: 100 })\n lastName: string;\n\n // ...\n```\n\n- `user.type.ts`\n\n```\n@ObjectType()\nexport class UserType {\n @Field({\n name: 'ID',\n description: 'Global Universal ID of the User',\n })\n guid: string;\n\n @Field()\n firstName: string;\n\n @Field()\n lastName: string;\n\n // ...\n```\n\nThe question is: since they use the same fields, can I create a single class that combines the decorators of both classes?\n\nFor instance:\n\n```\n@Entity({ schema: 'mydb', name: 'userList' })\n@ObjectType()\nexport class User {\n\n @Column('varchar', { name: 'guid', unique: true, length: 36 })\n @Field({\n name: 'ID',\n description: 'Global Universal ID of the User',\n })\n guid: string;\n\n @Field()\n @Column('varchar', { name: 'firstName', length: 50 })\n firstName: string;\n\n @Field()\n @Column('varchar', { name: 'lastName', length: 100 })\n lastName: string;\n```\n\nIs it an antipattern? are there any limitations or downsides in doing it?\n\nThanks in advance\n\n========================================\n\nTop Answer:\nI have the case where the Entities don't match the objects precisely.\nI have orders with products, but I only store the productId and resolve the product data fresh from a different system.\n\nHere I think it makes more sense to separate the two for type safety.\nI don't get the real product {} object back, only the productId, but typescript thinks I have both there.\n\n========================================\n\nCode:\n```js\n@Entity({ schema: 'mydb', name: 'userList' })\nexport class User {\n\n @Column('varchar', { name: 'guid', unique: true, length: 36 })\n guid: string;\n\n @Column('varchar', { name: 'firstName', length: 50 })\n firstName: string;\n\n @Column('varchar', { name: 'lastName', length: 100 })\n lastName: string;\n\n // ...\n```\n\n```js\n@ObjectType()\nexport class UserType {\n @Field({\n name: 'ID',\n description: 'Global Universal ID of the User',\n })\n guid: string;\n\n @Field()\n firstName: string;\n\n @Field()\n lastName: string;\n\n // ...\n```\n\n```js\n@Entity({ schema: 'mydb', name: 'userList' })\n@ObjectType()\nexport class User {\n\n @Column('varchar', { name: 'guid', unique: true, length: 36 })\n @Field({\n name: 'ID',\n description: 'Global Universal ID of the User',\n })\n guid: string;\n\n @Field()\n @Column('varchar', { name: 'firstName', length: 50 })\n firstName: string;\n\n @Field()\n @Column('varchar', { name: 'lastName', length: 100 })\n lastName: string;\n```\n\n```text\nuser.type.ts\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nuser.type.ts\n```\n\n========================================\n\nComments:\n- Hi! Thanks for the reply!\n- I've been using the DTO with REST, but in graphql I think they are useless since the field mapping and the validations are done by graphql. Moreover, for the arguments of the queries/mutations I'm using a separated class. The mixed class I'm referring above would be used only for the gql payload and I can easily hide/transform/extends fields with the graphl decorators. For now I really don't see the point of keeping them separated. Could you give me a real-world example?\n- @Joseph - One great example I can name is when your API field name should be different than your database's field name. If you build the entity and GraphQL object together, you are stuck with the api name and entity field names having to be the same. Might not seem like an issue, but it can be.\n- Thanks! Yes I was thinking the same but actually with the @Field decorator on Nestjs you can define the mapping of a field name. For instance: `@Field({name: ID}) guid: string;` it means that your db field is called guid but it's exposed as ID. Also you can @HideField and stuff like that. For now I don't see limitation but I'll try to spot them as well","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":166,"estimatedTokens":1109}}235{"id":"stack-54006757","source":"stackoverflow","questionId":54006757,"title":"How should I specify the DATABASE_URL in ormconfig.json?","tags":["typescript","heroku","typeorm"],"text":"Title: How should I specify the DATABASE_URL in ormconfig.json?\nTags: typescript, heroku, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to deploy my Vesper server to Heroku and Vesper requires an ormconfig.json file. \n\nThis works just fine when I use my local db because I can fill out all the fields that will combine into the connection string. However, when I add a db in Heroku I just get the full url and I can't find where to put it. \n\nThis is my ormconfig.json right now.\n\n```\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"password\",\n \"database\": \"test\",\n \"synchronize\": true,\n \"entities\": [\"target/entity/**/*.js\"],\n \"migrations\": [\"target/migrations/*.js\"],\n \"cli\": {\n \"migrationsDir\": \"src/migrations\"\n }\n}\n```\n\nI'm hoping I could replace most fields with just the database_url but I can't find any documentation stating under what name I should put it.\n\n========================================\n\nCode:\n```text\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"password\",\n \"database\": \"test\",\n \"synchronize\": true,\n \"entities\": [\"target/entity/**/*.js\"],\n \"migrations\": [\"target/migrations/*.js\"],\n \"cli\": {\n \"migrationsDir\": \"src/migrations\"\n }\n}\n```\n\n```text\nimport * as PostgressConnectionStringParser from \"pg-connection-string\";\n\nconst databaseUrl: string = process.env.DATABASE_URL;\nconst connectionOptions = PostgressConnectionStringParser.parse(databaseUrl);\nconst typeOrmOptions: PostgresConnectionOptions = {\n type: \"postgres\",\n name: connectionOptions.name,\n host: connectionOptions.host,\n port: connectionOptions.port,\n username: connectionOptions.username,\n password: connectionOptions.password,\n database: connectionOptions.database,\n synchronize: true,\n entities: [\"target/entity/**/*.js\"],\n extra: {\n ssl: true\n }\n};\nconst connection = createConnection(typeOrmOptions);\n...\n```\n\n```text\n...\nconst json = JSON.stringify(typeOrmOptions, null, 2);\nfs.writeFile(\"./target/ormconfig.json\", json, (err) => {\n if (err) {\n console.error(err);\n return;\n }\n console.log(\"File has been created\");\n});\n```\n\n```text\npg-connection-string\n```\n\n```text\ncreateConnection\n```\n\n========================================\n\nComments:\n- Works like a charm\n- At least as of version 0.2.25, `createConnection` accepts url paramaters, so the above can be simplified to: `const typeOrmOptions: ConnectionOptions = {type: \"postgres\", url: process.env.DATABASE_URL, ...};` No need for `pg-connection-string` dependency. `ConnectionOptions` can be imported directly from TypeORM.","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":98,"estimatedTokens":666}}236{"id":"stack-69062374","source":"stackoverflow","questionId":69062374,"title":"TypeORM insert row with foreign key","tags":["node.js","typescript","postgresql","typeorm"],"text":"Title: TypeORM insert row with foreign key\nTags: node.js, typescript, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a @OneToMany relation between\n\nChatroom Messages\n\nAnd the problem that I have is, whenever I try to insert a Message (or bulk of Messages),\nThe foreign key for ChatRoom is null.\n\nIn addition, I'm uploading my setup.\n\n```\n@Entity(\"messages\")\nexport class Message {\n\n @PrimaryColumn()\n id: string;\n\n @ManyToOne(() => ChatRoom, chatroom => chatroom.messages)\n chatRoom: ChatRoom | undefined\n\n @Column({nullable: false})\n message: string;\n\n @Column({nullable: false})\n receiver: string;\n\n @Column({nullable: false})\n created_utc: Date;\n}\n```\n\n```\n@Entity(\"chatrooms\")\nexport class ChatRoom {\n\n @PrimaryColumn()\n id: string;\n\n @OneToMany(() => Message, message => message.chatRoom, {\n cascade: [\"insert\", \"remove\"]\n })\n @JoinColumn({name: 'id'})\n messages: Message[];\n\n @Column()\n last_msg: string;\n\n @Column()\n last_msg_created_utc: Date;\n\n @Column()\n num_messages: number;\n\n @Column()\n num_replies: number;\n\n @Column()\n seen: boolean;\n\n}\n```\n\n### Problem:\n\nWhen trying to create a bulk insert on many messages, I can notice that the query is not setting the foreign key any value, but **NULL**.\n\nThe Message json that I'm trying to insert:\n\n```\n{\n id: '1',\n message: 'text',\n receiver: 'someone',\n created_utc: 'utc date...',\n chatRoomId: '123' -> chat room id exists \n}\n\nthe query looks like this :\n(this query is for single insert not bulk, but it goes the same for bulk)\nINSERT INTO \"messages\"(\"id\", \"message\", \"receiver\", \"created_utc\", \"chatRoomId\") VALUES ($1, $2, $3, $4, DEFAULT) -- PARAMETERS: [\" bJU7\",\"Zdravo test\",\"kompir_zomba\",\"2021-\n09-05T09:53:54.693Z\"]\n```\n\nThis tells me that chatRoomId is not even taken into consideration when inserting the rows.\nThe table looks as following\nhttps://i.sstatic.net/T68D3.png\n\nThe Typeorm insert query that I use to insert Messages\n\n```\n@InjectRepository(Message) private messageRepository: Repository\n.....\n\n this.messageRepository.save(message);\n```\n\nAnyone has any idea how to proceed with this ?\n\n========================================\n\nTop Answer:\n```\nconst test = await this.photosRepository.findOne(data.userId);\n if(!test){\n throw new NotFoundException(\"Exception message\");\n }\n const myPhoto = await this.photosRepository\n .createQueryBuilder()\n .insert()\n .into(Photo)\n .values({\n url: data.url,\n user:{\n id: data.userId\n }\n\n })\n .execute();\n\n console.log(myPhoto)\n```\n\nHello, I tried to do it this way and it works fine.\nForm 2 of the example above I did not understand well, could you upload an example? I am new at this\n\n========================================\n\nCode:\n```text\n@Entity(\"messages\")\nexport class Message {\n\n @PrimaryColumn()\n id: string;\n\n @ManyToOne(() => ChatRoom, chatroom => chatroom.messages)\n chatRoom: ChatRoom | undefined\n\n @Column({nullable: false})\n message: string;\n\n @Column({nullable: false})\n receiver: string;\n\n @Column({nullable: false})\n created_utc: Date;\n}\n```\n\n```text\n@Entity(\"chatrooms\")\nexport class ChatRoom {\n\n @PrimaryColumn()\n id: string;\n\n @OneToMany(() => Message, message => message.chatRoom, {\n cascade: [\"insert\", \"remove\"]\n })\n @JoinColumn({name: 'id'})\n messages: Message[];\n\n @Column()\n last_msg: string;\n\n @Column()\n last_msg_created_utc: Date;\n\n @Column()\n num_messages: number;\n\n @Column()\n num_replies: number;\n\n @Column()\n seen: boolean;\n\n}\n```\n\n```text\n{\n id: '1',\n message: 'text',\n receiver: 'someone',\n created_utc: 'utc date...',\n chatRoomId: '123' -> chat room id exists \n}\n\nthe query looks like this :\n(this query is for single insert not bulk, but it goes the same for bulk)\nINSERT INTO \"messages\"(\"id\", \"message\", \"receiver\", \"created_utc\", \"chatRoomId\") VALUES ($1, $2, $3, $4, DEFAULT) -- PARAMETERS: [\" bJU7\",\"Zdravo test\",\"kompir_zomba\",\"2021-\n09-05T09:53:54.693Z\"]\n```\n\n```text\n@InjectRepository(Message) private messageRepository: Repository<Message>\n.....\n\n this.messageRepository.save(message);\n```\n\n```text\n@Column({type: \"uuid\"}) // <- Assuming that your primary key type is UUID (OR you can have \"char\")\nchatRoomId: string;\n```\n\n```text\n{\n id: '1',\n message: 'text',\n receiver: 'someone',\n created_utc: 'utc date...',\n chatRoom: chatRoomData // <-- Assuming that chatRoomData contains the ChatRoom entity\n}\n```\n\n```text\nchatRoomId\n```\n\n```text\nclass Message\n```\n\n```text\nchatRoomId\n```\n\n```text\nchatRoomId\n```\n\n```text\nMessage\n```\n\n```text\nChatRoom\n```\n\n```text\nmessage\n```\n\n```text\nmessage\n```\n\n```text\nconst test = await this.photosRepository.findOne(data.userId);\n if(!test){\n throw new NotFoundException(\"Exception message\");\n }\n const myPhoto = await this.photosRepository\n .createQueryBuilder()\n .insert()\n .into(Photo)\n .values({\n url: data.url,\n user:{\n id: data.userId\n }\n\n })\n .execute();\n\n console.log(myPhoto)\n```\n\n```text\n@Column(\"uuid\", { name: \"parent_id\", nullable: true })\n parentId: string;\n\n @JoinColumn({ name: 'parent_id' }) <-- note the name here\n @OneToOne(() => MoveEntity)\n parent: MoveEntity | null;\n```\n\n```text\nOneToOne\n```\n\n```text\njoins\n```\n\n========================================\n\nComments:\n- Thanks !! After experimenting last night I got to your solution, but I didn't like it that much. Solution 1 is much cleaner and I like it. Thanks a lot!\n- @Liki Glad to hear that it worked out for you. Indeed, the 1st solution is much cleaner with less code and overhead. Also, I would really appreciate if you could mark it as the accepted answer to your question. :) Thanks!\n- Of course, forgot that. And for future readers, for Solution 2, you don't need to pass all of the data (if you don't have cascade update..), you can only pass the Entity with ID field (others null), it will still work.","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":297,"estimatedTokens":1474}}237{"id":"stack-65135069","source":"stackoverflow","questionId":65135069,"title":"TypeORM @OneToMany doesn't appear to try and execute when called","tags":["typescript","typeorm","typegraphql"],"text":"Title: TypeORM @OneToMany doesn't appear to try and execute when called\nTags: typescript, typeorm, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI have looked at the examples and as far as i can tell i followed them to the letter... my @ManyToOne join runs in query as expected but the @OneToMany doesn't seem to fire when included in my graphql playground call.. all other data for User comes back as expected with the exception of the device info\n\nThis is in my User.ts entity:\n\n```\n@Field(type => [Devices], { nullable: true })\n@OneToMany(() => Devices, devices => devices.user)\ndevices: Devices[];\n```\n\nThis is the entry in my Devices.ts Entity:\n\n```\nField(type => User)\n @ManyToOne(type => User, { lazy: true })\n @JoinColumn([{ name: \"userId\", referencedColumnName: \"userId\" }])\n user: User;\n```\n\nBefore i added the nullable: true above i was just getting an error saying can't return null for required blah blah... I thought maybe i had a device with no user but that was not the case.. In the terminal query output it only queries the user table and makes no attempt at getting devices...\n\nMy graphql call is super simple but just returns nulls for all devices:\n\n```\n{\n users{\n name\n phone\n devices{\n deviceId\n }\n }\n}\n```\n\nMy @ManyToOne also returned nulls for user until i set { lazy: true } and i am not sure why for that either.. There is obviously no setting like that for @OneToMany.. I am a sequelize, javascript baby and this is my first crack at TypeORM so any help would be appreciated. Or if there is relevant code i have not put in, let me know and i'll do it up.. Cheers in advance\n\n========================================\n\nCode:\n```text\n@Field(type => [Devices], { nullable: true })\n@OneToMany(() => Devices, devices => devices.user)\ndevices: Devices[];\n```\n\n```text\nField(type => User)\n @ManyToOne(type => User, { lazy: true })\n @JoinColumn([{ name: \"userId\", referencedColumnName: \"userId\" }])\n user: User;\n```\n\n```text\n{\n users{\n name\n phone\n devices{\n deviceId\n }\n }\n}\n```\n\n```text\n@Field(type => [Devices], { nullable: true, })\n@OneToMany(() => Devices, devices => devices.user, { lazy: true })\ndevices: Devices[];\n```\n\n```text\n{ lazy: true }\n```\n\n```text\n@OneToMany\n```\n\n========================================\n\nComments:\n- This can be a bit confusing unless you've learned the TypeORM documentation and some of the project issues by heart. Marking the relation as lazy is one way to go, but you could as well use the query builder pattern, or `find` attributes as suggested in this stellar answer. I believe specifying the relation where the query is issued would be idiomatic `TypeORM` code.\n- You can use lazy field to automatic resolve the relations (nested fields) on demand: github.com/MichalLytek/type-graphql/tree/master/examples/… Or just write the field resolvers manually, e.g. when you need to query the db using some parameter (field arg): github.com/MichalLytek/type-graphql/tree/master/examples/…","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":89,"estimatedTokens":744}}238{"id":"stack-75933034","source":"stackoverflow","questionId":75933034,"title":"TypeORM won't accept entity","tags":["typeorm"],"text":"Title: TypeORM won't accept entity\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nWhen creating a TypeORM entity in my express + typescript project I got hit with this error:\n\n```\nUnable to resolve signature of class decorator when called as an expression.\n The runtime will invoke the decorator with 2 arguments, but the decorator expects 1.\n```\n\nThis is the code (copy pasted from TypeORM docs)\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column } from \"typeorm\"\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column()\n firstName: string\n\n @Column()\n lastName: string\n\n @Column()\n age: number\n}\n```\n\nall the properties also get this error: `Property 'age' has no initializer and is not definitely assigned in the constructor`\n\nI have no clue what is going on since it's a clear paste and I have used typeorm with nestjs before without any issues\n\n========================================\n\nTop Answer:\nHere whats works for me:\n\ntsconfig.json\n\n```\n{\n \"compilerOptions\": {\n \"outDir\": \"./dist\",\n \"rootDir\": \"./src\",\n \"module\": \"CommonJS\",\n \"target\": \"ES6\",\n \"strict\": true,\n \"esModuleInterop\": true,\n \"experimentalDecorators\": true, # I had to add\n \"emitDecoratorMetadata\": true, # I had to add\n \"strictPropertyInitialization\": false # I had to add\n }\n}\n```\n\n========================================\n\nCode:\n```text\nUnable to resolve signature of class decorator when called as an expression.\n The runtime will invoke the decorator with 2 arguments, but the decorator expects 1.\n```\n\n```text\nimport { Entity, PrimaryGeneratedColumn, Column } from \"typeorm\"\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column()\n firstName: string\n\n @Column()\n lastName: string\n\n @Column()\n age: number\n}\n```\n\n```text\nProperty 'age' has no initializer and is not definitely assigned in the constructor\n```\n\n```text\n...\n\"experimentalDecorators\": true,\n\"strictPropertyInitialization\": false,\n...\n```\n\n```text\n{\n \"compilerOptions\": {\n \"outDir\": \"./dist\",\n \"rootDir\": \"./src\",\n \"module\": \"CommonJS\",\n \"target\": \"ES6\",\n \"strict\": true,\n \"esModuleInterop\": true,\n \"experimentalDecorators\": true, # I had to add\n \"emitDecoratorMetadata\": true, # I had to add\n \"strictPropertyInitialization\": false # I had to add\n }\n}\n```\n\n========================================\n\nComments:\n- have you enabled decorators in your typescript config? (if using before typescript v5)\n- @Samathingamajig ty man, that worked. I have forgot to check the tsconfig after working with nest for a long time.\n- This fixed it for me! You should mark as accepted answer :)","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":120,"estimatedTokens":657}}239{"id":"stack-70847785","source":"stackoverflow","questionId":70847785,"title":"How Typeorm define stored procedures, functions and triggers to DB. With migrations if possible","tags":["typescript","stored-procedures","nestjs","typeorm"],"text":"Title: How Typeorm define stored procedures, functions and triggers to DB. With migrations if possible\nTags: typescript, stored-procedures, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a stored function in a Postgress DB. The reason is that we might have several consumers from this DB, and we currently use the Migrations of typeorm to generate our tables from our entities.\n\nLooking into the documentation of typeorm and the source code of the library I find that there are some implementations of \"Listeners\" to certain events and \"Subscribers\" as well.\n\nThe problem with this approach is that it is tight to the technology or ORM itself...\n\nIs it possible to generate a raw query as a migration with a similar definition to this:\n\n```\nimport { MigrationInterface, QueryRunner } from \"typeorm\";\n\nexport class ProcedureCreation123123123 implements MigrationInterface {\n name = 'ProcedureCreation123123123'\n\n public async up(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`\n CREATE OR REPLACE FUNCTION validate_update() RETURNS TRIGGER\n BEGIN\n ...\n END;\n CREATE TRIGGER validate_update_value\n BEFORE UPDATE\n ON table\n FOR EACH ROW\n EXECUTE PROCEDURE validate_update();\n `);\n }\n\n public async down(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`DROP TRIGGER \"validate_update_value\"`);\n }\n\n}\n```\n\nI went through the generate of a migration documentation of typeorm to see how to generate such a migration, but the only way to generate it is by having differences in the entities in relation to the DB.\n\nAdding a listener to the entity to try to generate the trigger as part of the migration did not work either. And the generation stated there were no changes in database schema.\n\nOne more alternative would be to invoke on module init of my nestjs service to define a raw query that will do exactly this things, but it sounds wrong to run such a code everytime I start the service and may be add or not this function...\n\nIf there is any advice on how to do such a change to my DB in conjunction with the migrations of typeorm would be great.\n\n========================================\n\nCode:\n```text\nimport { MigrationInterface, QueryRunner } from \"typeorm\";\n\nexport class ProcedureCreation123123123 implements MigrationInterface {\n name = 'ProcedureCreation123123123'\n\n public async up(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(`\n CREATE OR REPLACE FUNCTION validate_update() RETURNS TRIGGER\n BEGIN\n ...\n END;\n CREATE TRIGGER validate_update_value\n BEFORE UPDATE\n ON table\n FOR EACH ROW\n EXECUTE PROCEDURE validate_update();\n `);\n }\n\n public async down(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(`DROP TRIGGER \"validate_update_value\"`);\n }\n\n}\n```\n\n```text\ntypeorm migration:create -n NameOfMigration\n```\n\n```text\nup\n```\n\n```text\ndown\n```\n\n========================================\n\nComments:\n- Thanks for showing me how to define custom PG function in TypeORM, I couldn't find this in their docs. Really helped!","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":94,"estimatedTokens":786}}240{"id":"stack-60531318","source":"stackoverflow","questionId":60531318,"title":"Deleting the columns from the typeorm entities","tags":["postgresql","nestjs","typeorm"],"text":"Title: Deleting the columns from the typeorm entities\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am pretty new to the NestJS/typeorm system. So while working, I created an `Episode` entity and added some fields. Then I updated the entity to remove and update some fields. But after running the application, it still has the deleted columns ( checked it on pgAdmin ). The migrations are not updated to delete the columns. Is there any way to do it?\n\n========================================\n\nCode:\n```text\nEpisode\n```\n\n```text\nrm -rf dist\n```\n\n========================================\n\nComments:\n- Do you have `synchronize:true` set in your TypeORM configuration?\n- Yes. It adds new columns added to the entity, but does not remove the deleted ones.\n- TypeORM has a really bad issue with caching columns and not deleting them. Usual remedy is `rm -rf dist` (or the windows equivalent) and start the server again\n- Thank You very much. It worked.\n- I'll just comment here that his works on NestJS, in case someone searches for it.","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":26,"estimatedTokens":264}}241{"id":"stack-51695868","source":"stackoverflow","questionId":51695868,"title":"How to return a 404 HTTP status code when promise resolve to undefined in Nest?","tags":["javascript","node.js","nestjs","typeorm"],"text":"Title: How to return a 404 HTTP status code when promise resolve to undefined in Nest?\nTags: javascript, node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn order to avoid boilerplate code (checking for undefined in every controller, over and over again), how can I automatically return a 404 error when the promise in `getOne` returns undefined?\n\n```\n@Controller('/customers')\nexport class CustomerController {\n constructor (\n @InjectRepository(Customer) private readonly repository: Repository\n ) { }\n\n @Get('/:id')\n async getOne(@Param('id') id): Promise {\n return this.repository.findOne(id)\n .then(result => {\n if (typeof result === 'undefined') {\n throw new NotFoundException();\n }\n\n return result;\n });\n }\n}\n```\n\nNestjs provides an integration with TypeORM and in the example repository is a TypeORM `Repository` instance.\n\n========================================\n\nCode:\n```text\n@Controller('/customers')\nexport class CustomerController {\n constructor (\n @InjectRepository(Customer) private readonly repository: Repository<Customer>\n ) { }\n\n @Get('/:id')\n async getOne(@Param('id') id): Promise<Customer|undefined> {\n return this.repository.findOne(id)\n .then(result => {\n if (typeof result === 'undefined') {\n throw new NotFoundException();\n }\n\n return result;\n });\n }\n}\n```\n\n```text\ngetOne\n```\n\n```text\nRepository\n```\n\n```text\n@Injectable()\nexport class NotFoundInterceptor implements NestInterceptor {\n intercept(context: ExecutionContext, next: CallHandler): Observable<any> { {\n // next.handle() is an Observable of the controller's result value\n return next.handle()\n .pipe(tap(data => {\n if (data === undefined) throw new NotFoundException();\n }));\n }\n}\n```\n\n```text\n// Apply the interceptor to *all* endpoints defined in this controller\n@Controller('user')\n@UseInterceptors(NotFoundInterceptor)\nexport class UserController {\n```\n\n```text\n// Apply the interceptor only to this endpoint\n@Get()\n@UseInterceptors(NotFoundInterceptor)\ngetUser() {\n return Promise.resolve(undefined);\n}\n```\n\n```text\nNotFoundException\n```\n\n```text\nundefined\n```\n\n========================================\n\nComments:\n- Thanks works very well! It would be great to define the interceptor as a factory, meaning passing arguments without the need to call `new NotFoundInterceptor()`. Do you have any idea how?\n- Great! :-) Have a look at `useFactory` in custom providers. You can inject the arguments of the factory as a provider itself. Depending on your use case, this might be what you need.","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":104,"estimatedTokens":650}}242{"id":"stack-55790897","source":"stackoverflow","questionId":55790897,"title":"Type is missing the following properties","tags":["typescript","typeorm"],"text":"Title: Type is missing the following properties\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI need some help. I create User entity by using typeorm and I want to overwrite toResponseObject\nat Customer class for change return attribute but when I write finished the error occurs as \"Type '{ userName: string; firstName: string; lastName: string; email: string; address: Address; token: string; }' is missing the following properties from type 'User': password, hasPassword, toResponObject, comparePassword\" I guess this means I should return all of User Property but I don't want to return all of the attributes. What should I do?\n\nuser.entity.ts\n\n```\nimport {PrimaryColumn, Column, BeforeInsert} from \"typeorm\";\nimport * as bcrypt from 'bcryptjs'\nimport * as jwt from 'jsonwebtoken'\n\nexport abstract class User {\n\n @PrimaryColumn()\n userName: string;\n\n @Column()\n password: string;\n\n @Column()\n firstName: string;\n\n @Column()\n lastName: string;\n\n @Column()\n email: string;\n\n @BeforeInsert()\n async hasPassword(){\n this.password = await bcrypt.hash(this.password,10)\n }\n\n async toResponObject(showToken:boolean = true){\n const {userName,firstName,lastName,email,token} = this\n const responseObject = {userName,firstName,lastName,email,token}\n if(showToken){\n responseObject.token = token\n }\n return responseObject\n }\n\n async comparePassword(attemp:string){\n return await bcrypt.compare(attemp,this.password)\n }\n\n protected get token(){\n const {userName,password} = this\n return jwt.sign({userName,password},process.env.SECRETKEY,{expiresIn:'7d'})\n }\n}\n```\n\ncustomer.entity.ts\n\n```\nimport { Pet } from \"../pet/pet.entity\";\nimport { Address } from \"../address/address.entity\";\nimport { Order } from \"../order/order.entity\";\nimport { Feedback } from \"../feedback/feedback.entity\";\nimport { User } from \"../user/user.entity\";\nimport { Entity, Column, ManyToOne, OneToMany } from \"typeorm\";\n\n@Entity()\nexport class Customer extends User {\n\n @Column()\n phoneNumber: string;\n\n @OneToMany(type => Pet,pet => pet.owner)\n pets: Pet[];\n\n @ManyToOne(type => Address)\n address: Address;\n\n @OneToMany(type => Order,order => order.customer)\n orders: Order[];\n\n @OneToMany(type => Feedback,feedbacks => feedbacks.customer)\n feedbacks: Feedback[];\n\n async toResponObject(showToken:boolean = true):Promise{\n const {userName,firstName,lastName,email,address,token} = this\n const responseObject = {userName,firstName,lastName,email,address,token}\n if(showToken){\n responseObject.token = token\n }\n return responseObject // error ocuurs at this line\n }\n\n}\n```\n\n========================================\n\nCode:\n```text\nimport {PrimaryColumn, Column, BeforeInsert} from \"typeorm\";\nimport * as bcrypt from 'bcryptjs'\nimport * as jwt from 'jsonwebtoken'\n\nexport abstract class User {\n\n @PrimaryColumn()\n userName: string;\n\n @Column()\n password: string;\n\n @Column()\n firstName: string;\n\n @Column()\n lastName: string;\n\n @Column()\n email: string;\n\n @BeforeInsert()\n async hasPassword(){\n this.password = await bcrypt.hash(this.password,10)\n }\n\n async toResponObject(showToken:boolean = true){\n const {userName,firstName,lastName,email,token} = this\n const responseObject = {userName,firstName,lastName,email,token}\n if(showToken){\n responseObject.token = token\n }\n return responseObject\n }\n\n async comparePassword(attemp:string){\n return await bcrypt.compare(attemp,this.password)\n }\n\n protected get token(){\n const {userName,password} = this\n return jwt.sign({userName,password},process.env.SECRETKEY,{expiresIn:'7d'})\n }\n}\n```\n\n```text\nimport { Pet } from \"../pet/pet.entity\";\nimport { Address } from \"../address/address.entity\";\nimport { Order } from \"../order/order.entity\";\nimport { Feedback } from \"../feedback/feedback.entity\";\nimport { User } from \"../user/user.entity\";\nimport { Entity, Column, ManyToOne, OneToMany } from \"typeorm\";\n\n@Entity()\nexport class Customer extends User {\n\n @Column()\n phoneNumber: string;\n\n @OneToMany(type => Pet,pet => pet.owner)\n pets: Pet[];\n\n @ManyToOne(type => Address)\n address: Address;\n\n @OneToMany(type => Order,order => order.customer)\n orders: Order[];\n\n @OneToMany(type => Feedback,feedbacks => feedbacks.customer)\n feedbacks: Feedback[];\n\n async toResponObject(showToken:boolean = true):Promise<User>{\n const {userName,firstName,lastName,email,address,token} = this\n const responseObject = {userName,firstName,lastName,email,address,token}\n if(showToken){\n responseObject.token = token\n }\n return responseObject // error ocuurs at this line\n }\n\n}\n```\n\n```js\nasync toResponObject(showToken:boolean = true):Promise<Partial<User>> {\n //...\n}\n```\n\n========================================\n\nComments:\n- See if this helps: typeorm.io/#/select-query-builder/hidden-columns\n- thank you for your suggestion :D this solution is not working for me because I figure out this problem is from types of object that I define to return in the method. I tried to define a new object that contains attributes that I want to return and It's work :D but you give me the knowledge that I never know from typeORM. Thank you very much\n- Cheers mate 👍!!","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":197,"estimatedTokens":1320}}243{"id":"stack-73778521","source":"stackoverflow","questionId":73778521,"title":"TypeORM migration gives Maximum call stack size exceeded error with Postgres","tags":["postgresql","typeorm"],"text":"Title: TypeORM migration gives Maximum call stack size exceeded error with Postgres\nTags: postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nWhen I run a migration, I get the following error. I initially had this in one project - now I've created a new blank project and still get the error. Here is the ormconfig.ts:\n\n```\nimport { DataSource } from 'typeorm';\n\nconst env = {\n \"DB_HOST\":\"localhost\",\n \"DB_PORT\":5432,\n \"DB_USERNAME\":\"postgres\",\n \"DB_PASSWORD\":\"postgres\",\n \"DB_DATABASE\":\"task-management\",\n}\n\nexport const connectionSource = new DataSource({\n migrationsTableName: 'migrations',\n type: 'postgres',\n host: env.DB_HOST,\n port: env.DB_PORT,\n username: env.DB_USERNAME,\n password: env.DB_PASSWORD,\n database: env.DB_DATABASE,\n logging: false,\n synchronize: false,\n name: 'default',\n migrations: ['migrations/**/*{.ts,.js}'],\n});\n```\n\nI run the migration with: typeorm-ts-node-esm migration:run -d migrations/ormconfig.ts\n\nwhich gives the following error:\n\n```\nError during migration run:\n RangeError: Maximum call stack size exceeded\n at /Users/christianayscue/Desktop/nestjsClass/nestjs-task-management/node_modules/src/util/DirectoryExportedClassesLoader.ts:29:43\n at Array.forEach ()\n at loadFileClasses (/Users/christianayscue/Desktop/nestjsClass/nestjs-task-management/node_modules/src/util/DirectoryExportedClassesLoader.ts:29:35)\n at /Users/christianayscue/Desktop/nestjsClass/nestjs-task-management/node_modules/src/util/DirectoryExportedClassesLoader.ts:27:42\n at Array.forEach ()\n at loadFileClasses (/Users/christianayscue/Desktop/nestjsClass/nestjs-task-management/node_modules/src/util/DirectoryExportedClassesLoader.ts:27:22)\n at /Users/christianayscue/Desktop/nestjsClass/nestjs-task-management/node_modules/src/util/DirectoryExportedClassesLoader.ts:30:17\n at Array.forEach ()\n at loadFileClasses (/Users/christianayscue/Desktop/nestjsClass/nestjs-task-management/node_modules/src/util/DirectoryExportedClassesLoader.ts:29:35)\n at /Users/christianayscue/Desktop/nestjsClass/nestjs-task-management/node_modules/src/util/DirectoryExportedClassesLoader.ts:30:17\n```\n\nI assume there is some circular dependency causing an infinite loop in DirectoryExportedClassesLoader.ts, so I put a console.log(JSON.stringify(exported)) on line 26 of DirectoryExportedClassesLoader.ts, and I now get:\n\n```\nTypeError: Converting circular structure to JSON\n --> starting at object with constructor 'DataSource'\n | property 'driver' -> object with constructor 'PostgresDriver'\n --- property 'connection' closes the circle\n at JSON.stringify ()\n at loadFileClasses (/Users/christianayscue/Desktop/nestjsClass/typeormTest/src/util/DirectoryExportedClassesLoader.ts:29:25)\n```\n\nIt seems DirectoryExportedClassLoader.js is guaranteed to get a Maximum call stack size exceeded error if there are circular dependencies, because it is self-recursive whenever it encounters an object property.\n\nA little help please!\n\n========================================\n\nTop Answer:\nIn my case I had the same error, I tried to generate a migration file with TypeORM CLI using `npx typeorm-ts-node-commonjs migration:generate src/migrations/ProductionMigration --dataSource src/dataSource.ts` command but it was throwing Maximum Call Stack exceeded. This happened because in my `dataSource.ts` file inside the `migrations` field I was pointing to `[\"migrations/*{.ts,.js}\"]` folder where I had another typescript file not related to migrations so TypeORM tried to use this file and crashed.\n\nOur migrations field in `dataSource.ts` will only accept files exporting a class that implements the `MigrationInterface` like so:\n\n```\nexport class MyMigrationClass_SomeId implements MigrationInterface {\n public async up(queryRunner: QueryRunner): Promise {\n }\n\n public async down(queryRunner: QueryRunner): Promise {\n }\n}\n```\n\nIn this question my `dataSource.ts` is equivalent to `ormconfig.ts`, if we leave the migrations array empty when we try to execute the run migrations command\n(`npx typeorm-ts-node-commonjs migration:run -- -d src/dataSource.ts`)\nit won't run any migration\n\n========================================\n\nCode:\n```text\nimport { DataSource } from 'typeorm';\n\nconst env = {\n \"DB_HOST\":\"localhost\",\n \"DB_PORT\":5432,\n \"DB_USERNAME\":\"postgres\",\n \"DB_PASSWORD\":\"postgres\",\n \"DB_DATABASE\":\"task-management\",\n}\n\nexport const connectionSource = new DataSource({\n migrationsTableName: 'migrations',\n type: 'postgres',\n host: env.DB_HOST,\n port: env.DB_PORT,\n username: env.DB_USERNAME,\n password: env.DB_PASSWORD,\n database: env.DB_DATABASE,\n logging: false,\n synchronize: false,\n name: 'default',\n migrations: ['migrations/**/*{.ts,.js}'],\n});\n```\n\n```text\nError during migration run:\n RangeError: Maximum call stack size exceeded\n at /Users/christianayscue/Desktop/nestjsClass/nestjs-task-management/node_modules/src/util/DirectoryExportedClassesLoader.ts:29:43\n at Array.forEach (<anonymous>)\n at loadFileClasses (/Users/christianayscue/Desktop/nestjsClass/nestjs-task-management/node_modules/src/util/DirectoryExportedClassesLoader.ts:29:35)\n at /Users/christianayscue/Desktop/nestjsClass/nestjs-task-management/node_modules/src/util/DirectoryExportedClassesLoader.ts:27:42\n at Array.forEach (<anonymous>)\n at loadFileClasses (/Users/christianayscue/Desktop/nestjsClass/nestjs-task-management/node_modules/src/util/DirectoryExportedClassesLoader.ts:27:22)\n at /Users/christianayscue/Desktop/nestjsClass/nestjs-task-management/node_modules/src/util/DirectoryExportedClassesLoader.ts:30:17\n at Array.forEach (<anonymous>)\n at loadFileClasses (/Users/christianayscue/Desktop/nestjsClass/nestjs-task-management/node_modules/src/util/DirectoryExportedClassesLoader.ts:29:35)\n at /Users/christianayscue/Desktop/nestjsClass/nestjs-task-management/node_modules/src/util/DirectoryExportedClassesLoader.ts:30:17\n```\n\n```text\nTypeError: Converting circular structure to JSON\n --> starting at object with constructor 'DataSource'\n | property 'driver' -> object with constructor 'PostgresDriver'\n --- property 'connection' closes the circle\n at JSON.stringify (<anonymous>)\n at loadFileClasses (/Users/christianayscue/Desktop/nestjsClass/typeormTest/src/util/DirectoryExportedClassesLoader.ts:29:25)\n```\n\n```text\nmigrations: []\n```\n\n```text\nexport class MyMigrationClass_SomeId implements MigrationInterface {\n public async up(queryRunner: QueryRunner): Promise<void> {\n }\n\n public async down(queryRunner: QueryRunner): Promise<void> {\n }\n}\n```\n\n```text\nnpx typeorm-ts-node-commonjs migration:generate src/migrations/ProductionMigration --dataSource src/dataSource.ts\n```\n\n```text\ndataSource.ts\n```\n\n```text\nmigrations\n```\n\n```text\n[\"migrations/*{.ts,.js}\"]\n```\n\n```text\ndataSource.ts\n```\n\n```text\nMigrationInterface\n```\n\n```text\ndataSource.ts\n```\n\n```text\normconfig.ts\n```\n\n```text\nnpx typeorm-ts-node-commonjs migration:run -- -d src/dataSource.ts\n```\n\n========================================\n\nComments:\n- I think its important to note that your dbconfig file cannot be in the same directory as your migrations - otherwise you'll have this recursive call.\n- If we leave this migrations array empty, when we try to run a migration with the typeorm cli it will not run any migration file","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":196,"estimatedTokens":1821}}244{"id":"stack-70789249","source":"stackoverflow","questionId":70789249,"title":"Can I abort DB operation / transaction in TypeORM using AbortSignal?","tags":["node.js","typeorm","abort"],"text":"Title: Can I abort DB operation / transaction in TypeORM using AbortSignal?\nTags: node.js, typeorm, abort\nSource: Stack Overflow\n\nQuestion:\nIs there a built-in TypeORM feature for aborting DB operation using AbortSignal?\n\n========================================\n\nCode:\n```text\nTypeORM#8552\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":13,"estimatedTokens":74}}245{"id":"stack-69581669","source":"stackoverflow","questionId":69581669,"title":"TypeORM in NestJS can not connect to MongoDB","tags":["mongodb","express","nestjs","typeorm"],"text":"Title: TypeORM in NestJS can not connect to MongoDB\nTags: mongodb, express, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI install the mongodb software on my own Ubuntu server and I get the mongo string just like this `mongodb://xxx:pass@42.212.159.109:27017`,when I type this string in my local terminal and use `mongosh mongodb://xxx:pass@42.212.159.109:27017`, it works fine and the connection is success. But when I use this mongodb string in my nestjs project, when I run `npm run start`, the terminal output `MongoServerError: Authentication failed.`\n\n### app.module.ts\n\n```\nTypeOrmModule.forRootAsync({\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: async (configService: ConfigService) => {\n const username = configService.get('MONGO_USER');\n const password = configService.get('MONGO_PASS');\n const database = configService.get('MONGO_DATABASE');\n const host = configService.get('MONGO_HOST');\n const port = configService.get('MONGO_PORT');\n return {\n type: 'mongodb',\n host,\n port,\n username,\n password,\n database,\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n };\n },\n```\n\nThe mongodb version is 4.1.3, TypeOrm version is 0.2.38.\nDoes anyone know what is the problem and how to solve it? Thank u.\n\n========================================\n\nTop Answer:\nMaybe you should try to use the Database URL connection string instead of host, port, username, password, ...\n\nSo instead of using this\n\n```\nreturn {\n type: 'mongodb',\n host,\n port,\n username,\n password,\n database,\n entities: ...\n ...\n}\n```\n\nyou should use this\n\n```\nreturn {\n type: \"mongodb\",\n url: configService.get(\"DATABASE_URL\"),\n entities: ...\n ...\n}\n```\n\n========================================\n\nCode:\n```text\nTypeOrmModule.forRootAsync({\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: async (configService: ConfigService) => {\n const username = configService.get('MONGO_USER');\n const password = configService.get('MONGO_PASS');\n const database = configService.get('MONGO_DATABASE');\n const host = configService.get('MONGO_HOST');\n const port = configService.get('MONGO_PORT');\n return {\n type: 'mongodb',\n host,\n port,\n username,\n password,\n database,\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n };\n },\n```\n\n```text\nmongodb://xxx:pass@42.212.159.109:27017\n```\n\n```text\nmongosh mongodb://xxx:pass@42.212.159.109:27017\n```\n\n```text\nnpm run start\n```\n\n```text\nMongoServerError: Authentication failed.\n```\n\n```text\nreturn {\n type: 'mongodb',\n host,\n port,\n username,\n password,\n database,\n authSource: 'admin',\n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n };\n```\n\n```text\nreturn {\n type: 'mongodb',\n host,\n port,\n username,\n password,\n database,\n entities: ...\n ...\n}\n```\n\n```text\nreturn {\n type: \"mongodb\",\n url: configService.get(\"DATABASE_URL\"),\n entities: ...\n ...\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":143,"estimatedTokens":772}}246{"id":"stack-47895612","source":"stackoverflow","questionId":47895612,"title":"Typical ormconfig.json file for Google Cloud SQL?","tags":["google-cloud-sql","typeorm"],"text":"Title: Typical ormconfig.json file for Google Cloud SQL?\nTags: google-cloud-sql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have been trying for hours. What should be the ormconfig.json file for Google Cloud SQL working with TypeORM? I managed to get it working with the IP of the DB locally (with mysql workbench and Google cloud proxy and whitelisting my ip) but I don't know what the connection details should be for app engine.\n\n```\n{\n \"name\": \"default\",\n \"type\": \"mysql\",\n \"host\": \"/cloudsql/[project:region:instance]\",\n \"port\": \"3306\",\n \"username\": \"root\",\n \"password\": \"xxxx\",\n \"database\": \"yyy\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"modules/**/*.entity.js\"\n ]\n}\n```\n\nor\n\n```\n{\n \"name\": \"default\",\n \"type\": \"mysql\",\n \"extra\": {\n \"socketPath\": \"/cloudsql/[project:region:instance]\"\n },\n \"username\": \"root\",\n \"password\": \"xxxx\",\n \"database\": \"yyy\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"modules/**/*.entity.js\"\n ]\n}\n```\n\nor anything else?\n\nThanks a lot!\n\n========================================\n\nTop Answer:\nIt didn't worked for me until I added the \"cloud_sql\" path also the the \"host\":\n\n```\n{\n \"name\": \"default\",\n \"host\": \"/cloudsql/[project:region:instance]\",\n \"type\": \"mysql\",\n \"extra\": {\n \"socketPath\": \"/cloudsql/[project:region:instance]\"\n },\n \"username\": \"root\",\n \"password\": \"xxxx\",\n \"database\": \"yyy\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"dist/**/*.entity.js\"\n ]\n}\n```\n\n========================================\n\nCode:\n```text\n{\n \"name\": \"default\",\n \"type\": \"mysql\",\n \"host\": \"/cloudsql/[project:region:instance]\",\n \"port\": \"3306\",\n \"username\": \"root\",\n \"password\": \"xxxx\",\n \"database\": \"yyy\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"modules/**/*.entity.js\"\n ]\n}\n```\n\n```text\n{\n \"name\": \"default\",\n \"type\": \"mysql\",\n \"extra\": {\n \"socketPath\": \"/cloudsql/[project:region:instance]\"\n },\n \"username\": \"root\",\n \"password\": \"xxxx\",\n \"database\": \"yyy\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"modules/**/*.entity.js\"\n ]\n}\n```\n\n```text\n{\n \"name\": \"default\",\n \"type\": \"mysql\",\n \"extra\": {\n \"socketPath\": \"/cloudsql/[project:region:instance]\"\n },\n \"username\": \"root\",\n \"password\": \"xxxx\",\n \"database\": \"yyy\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"dist/**/*.entity.js\"\n ]\n}\n```\n\n```text\nentities\n```\n\n```text\n{\n \"name\": \"default\",\n \"host\": \"/cloudsql/[project:region:instance]\",\n \"type\": \"mysql\",\n \"extra\": {\n \"socketPath\": \"/cloudsql/[project:region:instance]\"\n },\n \"username\": \"root\",\n \"password\": \"xxxx\",\n \"database\": \"yyy\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"dist/**/*.entity.js\"\n ]\n}\n```\n\n========================================\n\nComments:\n- How is `entities` path supposed to be correct? This way of connecting creates connection but doesn't create repositories. I tried `lib/entity/**/*.js` but without success.\n- It depends on the outDir option of your `tsconfig.json`. The point is that once you transpile your, the production code of the entities is no longer at the same place.","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":156,"estimatedTokens":790}}247{"id":"stack-50590068","source":"stackoverflow","questionId":50590068,"title":"Does NestJS comes with security practices already?","tags":["node.js","security","nestjs","typeorm","nodejs-server"],"text":"Title: Does NestJS comes with security practices already?\nTags: node.js, security, nestjs, typeorm, nodejs-server\nSource: Stack Overflow\n\nQuestion:\nDoes NestJS handles some security practices out of the box?. If not, what recommendations can you to secure a NestJS application besides helmet? I see in the NestJS middleware docs an example using the helmet dependency.\n\nWhen using TypeORM, SQL injection is covered?\n\n========================================\n\nTop Answer:\n**NestJS** follows mostly the same security rules as the **Node.js** server and **Express**.\n\n**NestJS has an dedicated security section** in its documentation that addresses these topics:\n\n- Authentication\n\n- Authorization\n\n- Encryption and Hashing\n\n- Helmet\n\n- CORS\n\n- CSRF Protection\n\n- Rate limiting\n\n**When it comes to protecting against SQL Injection, I think sanitize input and parameterized statements are the most important.**\n\nOverall, however, it is most important that **programmers do not cause security holes through code and architecture, but with good security practices and as administrators to expose to production hardened services with the least privileges**. It is important to educate ourselves in this area all the time.","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":0,"totalLines":33,"estimatedTokens":304}}248{"id":"stack-58713598","source":"stackoverflow","questionId":58713598,"title":"Relations don't work properly in TypeGraphQL (You need to provide explicit type for...)","tags":["javascript","graphql","typeorm","typegraphql"],"text":"Title: Relations don't work properly in TypeGraphQL (You need to provide explicit type for...)\nTags: javascript, graphql, typeorm, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI want to create a simple relation between a user and documents in TypeGraphQL. So a user can create unlimited documents and a document has only one creator. But I am receiving an error.\n\n### User\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column, BaseEntity, OneToMany } from \"typeorm\";\nimport { Field, ID, ObjectType } from \"type-graphql\";\n\nimport { Doc } from \"./Doc\";\n\n@ObjectType()\n@Entity()\nexport class User extends BaseEntity {\n @Field(() => ID)\n @PrimaryGeneratedColumn()\n id: number;\n\n @Field()\n @Column()\n firstName: string;\n\n @Field()\n @Column()\n lastName: string;\n\n @Field()\n @Column()\n nickname: string;\n\n @Field()\n @Column(\"text\", { unique: true })\n email: string;\n\n @Column()\n password: string;\n\n @Field({ nullable: true })\n @Column()\n created: Date;\n\n @Field()\n @Column()\n gender: string;\n\n @OneToMany(() => Doc, doc => doc.creator)\n createdDocs: Promise;\n}\n```\n\n### Doc\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column, BaseEntity, ManyToOne } from \"typeorm\";\nimport { Field, ID, ObjectType } from \"type-graphql\";\n\nimport { User } from \"./User\";\n\n@ObjectType()\n@Entity()\nexport class Doc extends BaseEntity {\n @Field(() => ID)\n @PrimaryGeneratedColumn()\n id: number;\n\n @Field({ nullable: true })\n @Column()\n created: Date;\n\n @Field()\n @Column()\n @ManyToOne(() => User, user => user.createdDocs)\n creator: Promise;\n}\n```\n\n### Error\n\n```\nthrow new errors_1.NoExplicitTypeError(prototype.constructor.name, propertyKey, parameterIndex);\n ^\nError: You need to provide explicit type for Doc#creator !\n```\n\nBut what is causing this to happen? Of couse the column creator in the table doc is not a real \"data-type\", because it shouldn't be \"static\". It needs to be a relation and this relation can't obviously has a \"data-type\".\n\n========================================\n\nTop Answer:\nError: You need to provide explicit type for Doc#creator !\n\nIt means that, when your property type is `Promise`, the reflected type is `Object`. TypeGraphQL in that case need explicit type in decorator, like `@Field(type => User)`.\n\n========================================\n\nCode:\n```text\nimport { Entity, PrimaryGeneratedColumn, Column, BaseEntity, OneToMany } from \"typeorm\";\nimport { Field, ID, ObjectType } from \"type-graphql\";\n\nimport { Doc } from \"./Doc\";\n\n@ObjectType()\n@Entity()\nexport class User extends BaseEntity {\n @Field(() => ID)\n @PrimaryGeneratedColumn()\n id: number;\n\n @Field()\n @Column()\n firstName: string;\n\n @Field()\n @Column()\n lastName: string;\n\n @Field()\n @Column()\n nickname: string;\n\n @Field()\n @Column(\"text\", { unique: true })\n email: string;\n\n @Column()\n password: string;\n\n @Field({ nullable: true })\n @Column()\n created: Date;\n\n @Field()\n @Column()\n gender: string;\n\n @OneToMany(() => Doc, doc => doc.creator)\n createdDocs: Promise<Doc[]>;\n}\n```\n\n```text\nimport { Entity, PrimaryGeneratedColumn, Column, BaseEntity, ManyToOne } from \"typeorm\";\nimport { Field, ID, ObjectType } from \"type-graphql\";\n\nimport { User } from \"./User\";\n\n@ObjectType()\n@Entity()\nexport class Doc extends BaseEntity {\n @Field(() => ID)\n @PrimaryGeneratedColumn()\n id: number;\n\n @Field({ nullable: true })\n @Column()\n created: Date;\n\n @Field()\n @Column()\n @ManyToOne(() => User, user => user.createdDocs)\n creator: Promise<User>;\n}\n```\n\n```text\nthrow new errors_1.NoExplicitTypeError(prototype.constructor.name, propertyKey, parameterIndex);\n ^\nError: You need to provide explicit type for Doc#creator !\n```\n\n```text\n@Field()\n```\n\n```text\n@Column()\n```\n\n```text\nPromise<User>\n```\n\n```text\nObject\n```\n\n```text\n@Field(type => User)\n```\n\n```text\n@Field(() => User) # Try this\n@ManyToOne(() => User, user => user.createdDocs)\ncreator: Promise<User>\n```\n\n========================================\n\nComments:\n- For me, there was a need to declare the relations with `@Field()`","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":205,"estimatedTokens":1018}}249{"id":"stack-63170241","source":"stackoverflow","questionId":63170241,"title":"Nestjs/TypeORM - How to implement custom search by column","tags":["node.js","nestjs","typeorm"],"text":"Title: Nestjs/TypeORM - How to implement custom search by column\nTags: node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am playing around with NestJs using TypeORM along with MySQL.\n\nI have went via documentation, and I have made basic CRUD app running locally.\nI have built in searches (via Repository) by id, but I would need to implement search by custom column as well.\n\nFor example I have this entity:\n\n```\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n username: string;\n\n @Column()\n first_name: string;\n\n @Column()\n last_Name: string;\n\n @Column()\n gender: string;\n```\n\nAnd in my repository, I have these built in methods:\n\n```\nasync findAll(): Promise {\n return this.usersRepository.find();\n }\n\n findOne(id: string): Promise {\n return this.usersRepository.findOne(id);\n }\n```\n\nAnd it works just fine, as expected. I would need another custom search, so I can search also by username, how can I achieve that?\nI would need something like this:\n\n```\nfindByUsername(username: string): Promise {\n return this.usersRepository.findByUsername(username);\n }\n```\n\nI assume I have to implement custom query, but I have no clue where to do it :(\n\n========================================\n\nTop Answer:\nYou can use this code\n\n```\nfindByName(user_name: string): Promise {\n return this.usersRepository.findOne({ user_name }); \n}\n```\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n username: string;\n\n @Column()\n first_name: string;\n\n @Column()\n last_Name: string;\n\n @Column()\n gender: string;\n```\n\n```text\nasync findAll(): Promise<User[]> {\n return this.usersRepository.find();\n }\n\n findOne(id: string): Promise<User> {\n return this.usersRepository.findOne(id);\n }\n```\n\n```text\nfindByUsername(username: string): Promise<User> {\n return this.usersRepository.findByUsername(username);\n }\n```\n\n```js\nfindByUsername(username: string): Promise<User | undefined> {\n return this.usersRepository.findOne({ username }); \n}\n```\n\n```text\nfindByUsername(username: string): Promise<User | undefined> {\n const user = getRepository(User)\n .createQueryBuilder(\"user\")\n .where(\"user.username = :username\", { username: username })\n .getOne();\n\n return user;\n }\n```\n\n```text\nconst firstUser = await connection\n .getRepository(User)\n .createQueryBuilder(\"user\")\n .where(\"user.id = :id\", { id: 1 })\n .getOne();\n```\n\n```text\nfindByName(user_name: string): Promise<User> {\n return this.usersRepository.findOne({ user_name }); \n}\n```\n\n```text\nasync getUserByName(username: string){\n return await this.userRepository.findOneBy({name: username });\n}\n```\n\n========================================\n\nComments:\n- How can we compare if string is non case sensitive?\n- Do you happen to know where is this documented? I would like to read about it a bit.\n- not sure where i read it before :) but you can check the typescript definition files of the TypeOrm.\n- Can you please provide at least some explanation","metadata":{"transformedAt":"2026-08-18T18:33:44.702Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":147,"estimatedTokens":768}}250{"id":"stack-59607560","source":"stackoverflow","questionId":59607560,"title":"NestJs - TypeORM configuration works but not with ConfigService","tags":["nestjs","typeorm"],"text":"Title: NestJs - TypeORM configuration works but not with ConfigService\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI would like to create a REST API with NestJs and TypeORM. In my **app.module.ts** I load the TypeORM module\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'postgres',\n database: 'api',\n entities: [`${__dirname}/**/*.entity.{ts,js}`],\n synchronize: true,\n }),\n ],\n})\nexport class AppModule {}\n```\n\nand it's working fine for now. I would like to load the configuration from an external .env file so from the docs\n\nhttps://docs.nestjs.com/techniques/database#async-configuration\n\nand from here\n\nNestJS Using ConfigService with TypeOrmModule\n\nI created a .env file in the root project directory with the following content\n\n```\nDATABASE_TYPE = postgres\nDATABASE_HOST = localhost\nDATABASE_PORT = 5432\nDATABASE_USERNAME = postgres\nDATABASE_PASSWORD = postgres\nDATABASE_NAME = api\nDATABASE_SYNCHRONIZE = true\n```\n\nNext I update my code to\n\n```\n@Module({\n imports: [\n ConfigModule.forRoot(),\n TypeOrmModule.forRootAsync({\n imports: [ConfigModule],\n useFactory: async (configService: ConfigService) => ({\n type: configService.get('DATABASE_TYPE'),\n host: configService.get('DATABASE_HOST'),\n port: configService.get('DATABASE_PORT'),\n username: configService.get('DATABASE_USERNAME'),\n password: configService.get('DATABASE_PASSWORD'),\n database: configService.get('DATABASE_NAME'),\n entities: [`${__dirname}/**/*.entity.{ts,js}`],\n synchronize: configService.get('DATABASE_SYNCHRONIZE'),\n }),\n inject: [ConfigService],\n }),\n ],\n})\nexport class AppModule {}\n```\n\nUnfortunately I get this error on startup\n\n```\n[Nest] 28257 - 01/06/2020, 7:19:20 AM [ExceptionHandler] Nest can't resolve dependencies of the TypeOrmModuleOptions (?). Please make sure that the argument ConfigService at index [0] is available in the TypeOrmCoreModule context.\n\nPotential solutions:\n- If ConfigService is a provider, is it part of the current TypeOrmCoreModule?\n- If ConfigService is exported from a separate @Module, is that module imported within TypeOrmCoreModule?\n @Module({\n imports: [ /* the Module containing ConfigService */ ]\n })\n +1ms\n```\n\nWhen I log the configuration in my **main.ts** within the **bootstrap** function I get a correct configuration from the .env file.\n\nHow can I fix the error?\n\n========================================\n\nTop Answer:\ncode translation of @ Jay McDoniel explanation\n\ntypeorm.config.ts\n\n```\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { TypeOrmModuleAsyncOptions, TypeOrmModuleOptions } from '@nestjs/typeorm';\nimport { LoggerOptions } from 'typeorm';\n\nexport default class TypeOrmConfig {\n static getOrmConfig(configService: ConfigService): TypeOrmModuleOptions {\n return {\n type: 'postgres',\n host: configService.get('DB_HOST') || 'localhost',\n port: configService.get('DB_PORT') || 5432,\n username: configService.get('DB_USERNAME'),\n password: configService.get('DB_PASSWORD'),\n database: configService.get('DB_NAME'),\n entities: [__dirname + '/../**/*.entity{.ts,.js}'],\n synchronize:configService.get('TYPEORM_SYNCHRONIZE') || false,\n logging: configService.get('TYPEORM_LOGGING') || false\n };\n }\n}\n\nexport const typeOrmConfigAsync: TypeOrmModuleAsyncOptions = {\n imports: [ConfigModule],\n useFactory: async (configService: ConfigService): Promise => TypeOrmConfig.getOrmConfig(configService),\n inject: [ConfigService]\n};\n```\n\napp.module.ts\n\n```\nimport { LoginModule } from './login/login.module';\nimport * as redisStore from 'cache-manager-redis-store';\nimport { ServiceModule } from './service/service.module';\nimport { UserModule } from './user/user.module';\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { RedisCacheModule } from './redis-cache/redis-cache.module';\nimport { typeOrmConfigAsync } from './config/typeorm.config';\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n TypeOrmModule.forRootAsync(typeOrmConfigAsync),\n UserModule,\n ServiceModule,\n LoginModule,\n RedisCacheModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\nnestjsconfigmoduletypeorm\n\nReference video\nReference code\n\n========================================\n\nCode:\n```text\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'postgres',\n database: 'api',\n entities: [`${__dirname}/**/*.entity.{ts,js}`],\n synchronize: true,\n }),\n ],\n})\nexport class AppModule {}\n```\n\n```text\nDATABASE_TYPE = postgres\nDATABASE_HOST = localhost\nDATABASE_PORT = 5432\nDATABASE_USERNAME = postgres\nDATABASE_PASSWORD = postgres\nDATABASE_NAME = api\nDATABASE_SYNCHRONIZE = true\n```\n\n```text\n@Module({\n imports: [\n ConfigModule.forRoot(),\n TypeOrmModule.forRootAsync({\n imports: [ConfigModule],\n useFactory: async (configService: ConfigService) => ({\n type: configService.get<any>('DATABASE_TYPE'),\n host: configService.get<string>('DATABASE_HOST'),\n port: configService.get<number>('DATABASE_PORT'),\n username: configService.get<string>('DATABASE_USERNAME'),\n password: configService.get<string>('DATABASE_PASSWORD'),\n database: configService.get<string>('DATABASE_NAME'),\n entities: [`${__dirname}/**/*.entity.{ts,js}`],\n synchronize: configService.get<boolean>('DATABASE_SYNCHRONIZE'),\n }),\n inject: [ConfigService],\n }),\n ],\n})\nexport class AppModule {}\n```\n\n```text\n[Nest] 28257 - 01/06/2020, 7:19:20 AM [ExceptionHandler] Nest can't resolve dependencies of the TypeOrmModuleOptions (?). Please make sure that the argument ConfigService at index [0] is available in the TypeOrmCoreModule context.\n\nPotential solutions:\n- If ConfigService is a provider, is it part of the current TypeOrmCoreModule?\n- If ConfigService is exported from a separate @Module, is that module imported within TypeOrmCoreModule?\n @Module({\n imports: [ /* the Module containing ConfigService */ ]\n })\n +1ms\n```\n\n```text\nConfigModule\n```\n\n```text\nisGlobal: true\n```\n\n```text\nConfigModule.forRoot()\n```\n\n```text\nTypeormModule.forRootAsync()\n```\n\n```text\nMyConfigModule\n```\n\n```text\nimports\n```\n\n```text\nConfigModule\n```\n\n```text\nexports\n```\n\n```text\nCofnigModule\n```\n\n```text\nConfigModule.forRoot()\n```\n\n```text\nMyConfigModule\n```\n\n```text\nAppModule\n```\n\n```text\nimports: [ConfigModule]\n```\n\n```text\nimports: [MyConfigModule]\n```\n\n```text\nTypeormModule.forRootAsync()\n```\n\n```js\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { TypeOrmModuleAsyncOptions, TypeOrmModuleOptions } from '@nestjs/typeorm';\nimport { LoggerOptions } from 'typeorm';\n\nexport default class TypeOrmConfig {\n static getOrmConfig(configService: ConfigService): TypeOrmModuleOptions {\n return {\n type: 'postgres',\n host: configService.get('DB_HOST') || 'localhost',\n port: configService.get('DB_PORT') || 5432,\n username: configService.get('DB_USERNAME'),\n password: configService.get('DB_PASSWORD'),\n database: configService.get('DB_NAME'),\n entities: [__dirname + '/../**/*.entity{.ts,.js}'],\n synchronize:configService.get<boolean>('TYPEORM_SYNCHRONIZE') || false,\n logging: configService.get<LoggerOptions>('TYPEORM_LOGGING') || false\n };\n }\n}\n\nexport const typeOrmConfigAsync: TypeOrmModuleAsyncOptions = {\n imports: [ConfigModule],\n useFactory: async (configService: ConfigService): Promise<TypeOrmModuleOptions> => TypeOrmConfig.getOrmConfig(configService),\n inject: [ConfigService]\n};\n```\n\n```js\nimport { LoginModule } from './login/login.module';\nimport * as redisStore from 'cache-manager-redis-store';\nimport { ServiceModule } from './service/service.module';\nimport { UserModule } from './user/user.module';\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { RedisCacheModule } from './redis-cache/redis-cache.module';\nimport { typeOrmConfigAsync } from './config/typeorm.config';\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n TypeOrmModule.forRootAsync(typeOrmConfigAsync),\n UserModule,\n ServiceModule,\n LoginModule,\n RedisCacheModule,\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n========================================\n\nComments:\n- add your configService file please\n- @ Selmi sorry, I don't have a ConfigService file. I just have to inject it, as you can see in the docs docs.nestjs.com/techniques/configuration","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":21,"totalLines":345,"estimatedTokens":2234}}251{"id":"stack-76959313","source":"stackoverflow","questionId":76959313,"title":"NestJS Repository gives error 'No metadata for \"TaskRepository\" was found.'","tags":["nestjs","typeorm","repository-pattern","nestjs-typeorm"],"text":"Title: NestJS Repository gives error 'No metadata for \"TaskRepository\" was found.'\nTags: nestjs, typeorm, repository-pattern, nestjs-typeorm\nSource: Stack Overflow\n\nQuestion:\nGitHub link to project:\nnestjs-task-management\n\nError Log:\n\n```\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [NestFactory] Starting Nest application...\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] AppModule dependencies initialized +115ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] TypeOrmCoreModule dependencies initialized +182ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] TasksModule dependencies initialized +2ms \n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [RoutesResolver] TasksController {/tasks}: +28ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [RouterExplorer] Mapped {/tasks/:id, GET} route +5ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [NestApplication] Nest application successfully started +4ms\n[Nest] 15824 - 23/08/2023, 12:03:53 ERROR [ExceptionsHandler] No metadata for \"TaskRepository\" was found.\nEntityMetadataNotFoundError: No metadata for \"TaskRepository\" was found.\n at DataSource.getMetadata (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\data-source\\DataSource.ts:444:30)\n at Repository.get metadata [as metadata] (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\repository\\Repository.ts:53:40)\n at Repository.findOne (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\repository\\Repository.ts:577:42)\n at TasksService.getTaskById (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\tasks\\tasks.service.ts:37:50)\n at TasksController.getTaskById (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\tasks\\tasks.controller.ts:24:30)\n at D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:38:29\n at processTicksAndRejections (node:internal/process/task_queues:95:5)\n at D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:46:28\n at D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17\n```\n\nModules:\n\n```\n\"@nestjs/common\": \"^9.0.0\",\n \"@nestjs/core\": \"^9.0.0\",\n \"@nestjs/typeorm\": \"^10.0.0\",\n \"typeorm\": \"^0.3.17\"\n```\n\ntypeorm.config.ts:\n\n```\nimport { TypeOrmModuleOptions } from \"@nestjs/typeorm\";\n\nexport const typeOrmConfig: TypeOrmModuleOptions = {\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'root',\n database: 'taskmanagement',\n entities: [__dirname + '/../**/*.entity.{js,ts}'],\n synchronize: true,\n};\n```\n\ntasks.module.ts:\n\n```\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Module } from '@nestjs/common';\nimport { TasksController } from './tasks.controller';\nimport { TasksService } from './tasks.service';\nimport { TaskRepository } from './task.repository';\n\n@Module({\n imports: [TypeOrmModule.forFeature([TaskRepository])],\n controllers: [TasksController],\n providers: [TasksService],\n})\nexport class TasksModule {}\n```\n\ntask.entity.ts:\n\n```\nimport { TaskStatus } from \"./task-status.enum\";\nimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';\n\n@Entity()\nexport class Task {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column()\n description: string;\n\n @Column()\n status: TaskStatus;\n}\n```\n\ntask.repository.ts:\n\n```\nimport { Repository } from 'typeorm';\nimport { Task } from './task.entity';\n\nexport class TaskRepository extends Repository {\n // Your custom repository methods can go here\n}\n```\n\ntasks.service.ts:\n\n```\nimport { TaskRepository } from './task.repository';\nimport { Injectable, NotFoundException } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Task } from './task.entity';\n\n@Injectable()\nexport class TasksService {\n constructor(\n @InjectRepository(TaskRepository)\n private taskRepository: TaskRepository,\n ) {};\n async getTaskById(id: number): Promise {\n const record = await this.taskRepository.findOne({ where: { id } });\n if (!record) {\n throw new NotFoundException();\n }\n return record;\n }\n}\n```\n\nI tried using an older version of TypeORM but that was introducing new errors and I want to learn doing this using the up-to-date methods.\n\nI only get this error when I hit the endpoint using Postman and I have been trying to fix this since yesterday and was unable to find any similar issues. One was to use `entities: [__dirname + '/../**/*.entity.{js,ts}'],` in the typeorm config file where I was using `autoLoadEntities: true` instead so I tried that too but didn't change anything.\n\nI don't understand where and how I have to provide metadata to the repository.\n\nI thank you guys in advance for any help here.\n\n========================================\n\nTop Answer:\nI resolved this by reverting @nestjs/typeorm to version 8.0.0 (`yarn upgrade @nestjs/typeorm@8.0.0`) and downgrading typeorm to version 0.2.32 (`yarn upgrade typeorm@0.2.32`).\n\n========================================\n\nCode:\n```text\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [NestFactory] Starting Nest application...\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] AppModule dependencies initialized +115ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] TypeOrmCoreModule dependencies initialized +182ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] TypeOrmModule dependencies initialized +1ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [InstanceLoader] TasksModule dependencies initialized +2ms \n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [RoutesResolver] TasksController {/tasks}: +28ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [RouterExplorer] Mapped {/tasks/:id, GET} route +5ms\n[Nest] 15824 - 23/08/2023, 11:22:29 LOG [NestApplication] Nest application successfully started +4ms\n[Nest] 15824 - 23/08/2023, 12:03:53 ERROR [ExceptionsHandler] No metadata for \"TaskRepository\" was found.\nEntityMetadataNotFoundError: No metadata for \"TaskRepository\" was found.\n at DataSource.getMetadata (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\data-source\\DataSource.ts:444:30)\n at Repository.get metadata [as metadata] (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\repository\\Repository.ts:53:40)\n at Repository.findOne (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\repository\\Repository.ts:577:42)\n at TasksService.getTaskById (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\tasks\\tasks.service.ts:37:50)\n at TasksController.getTaskById (D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\src\\tasks\\tasks.controller.ts:24:30)\n at D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:38:29\n at processTicksAndRejections (node:internal/process/task_queues:95:5)\n at D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:46:28\n at D:\\SaifAli\\NestJS Demo Projects\\nestjs-task-management\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17\n```\n\n```text\n\"@nestjs/common\": \"^9.0.0\",\n \"@nestjs/core\": \"^9.0.0\",\n \"@nestjs/typeorm\": \"^10.0.0\",\n \"typeorm\": \"^0.3.17\"\n```\n\n```text\nimport { TypeOrmModuleOptions } from \"@nestjs/typeorm\";\n\nexport const typeOrmConfig: TypeOrmModuleOptions = {\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'root',\n database: 'taskmanagement',\n entities: [__dirname + '/../**/*.entity.{js,ts}'],\n synchronize: true,\n};\n```\n\n```text\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { Module } from '@nestjs/common';\nimport { TasksController } from './tasks.controller';\nimport { TasksService } from './tasks.service';\nimport { TaskRepository } from './task.repository';\n\n@Module({\n imports: [TypeOrmModule.forFeature([TaskRepository])],\n controllers: [TasksController],\n providers: [TasksService],\n})\nexport class TasksModule {}\n```\n\n```text\nimport { TaskStatus } from \"./task-status.enum\";\nimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';\n\n@Entity()\nexport class Task {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @Column()\n description: string;\n\n @Column()\n status: TaskStatus;\n}\n```\n\n```text\nimport { Repository } from 'typeorm';\nimport { Task } from './task.entity';\n\nexport class TaskRepository extends Repository<Task> {\n // Your custom repository methods can go here\n}\n```\n\n```text\nimport { TaskRepository } from './task.repository';\nimport { Injectable, NotFoundException } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Task } from './task.entity';\n\n@Injectable()\nexport class TasksService {\n constructor(\n @InjectRepository(TaskRepository)\n private taskRepository: TaskRepository,\n ) {};\n async getTaskById(id: number): Promise<Task> {\n const record = await this.taskRepository.findOne({ where: { id } });\n if (!record) {\n throw new NotFoundException();\n }\n return record;\n }\n}\n```\n\n```text\nentities: [__dirname + '/../**/*.entity.{js,ts}'],\n```\n\n```text\nautoLoadEntities: true\n```\n\n```text\n@Module({\n imports: [TypeOrmModule.forFeature([TaskRepository])],\n controllers: [TasksController],\n providers: [TasksService],\n})\nexport class TasksModule {}\n```\n\n```text\nimport { Task } from './task.entity';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Task])],\n controllers: [TasksController],\n providers: [TasksService],\n})\nexport class TasksModule {}\n```\n\n```text\n@Injectable()\nexport class TasksService {\n constructor(\n @InjectRepository(TaskRepository)\n private taskRepository: TaskRepository,\n ) {};\n}\n```\n\n```text\nimport { MongoRepository } from 'typeorm'\n\nimport { Task } from './task.entity'\n\n@Injectable()\nexport class TasksService {\n constructor(\n @InjectRepository(Task)\n private taskRepository: MongoRepository<Task>,\n ) {};\n}\n```\n\n```text\nTaskRepository\n```\n\n```text\nTask\n```\n\n```text\ntask.entity.ts\n```\n\n```text\nTaskService\n```\n\n```text\nTask\n```\n\n```text\nTaskRepository\n```\n\n```text\nTaskRepository\n```\n\n```text\nyarn upgrade @nestjs/typeorm@8.0.0\n```\n\n```text\nyarn upgrade typeorm@0.2.32\n```\n\n========================================\n\nComments:\n- Found solutions here: stackoverflow.com/questions/72549668/… stackoverflow.com/questions/72957962/…\n- I tried that but it gives this error: `ERROR [ExceptionHandler] Nest can't resolve dependencies of the TasksService (?). Please make sure that the argument TaskRepository at index [0] is available in the TasksModule context.` and if I use `imports: [TypeOrmModule.forFeature([Task]), TypeOrmModule.forFeature([TaskRepository])],` instead, I get the same error as before.\n- @SAIFALI Updated my answer. Can you check?\n- thanks for the update, it works fine now but now I'm using MongoRepository instead of a custom built repository, I'll try using my custom repository later though and check how I can get it to work, thanks.\n- I actually got my custom repository working too, I just replaced: `private taskRepository: MongoRepository,` with: `private taskRepository: TaskRepository,` And in my repository file I replaced: `export class TasksRepository extends Repository {}` with: `export class TasksRepository extends Repository {}` Not sure if it's the right way but I got it working with my custom repository.","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":356,"estimatedTokens":2943}}252{"id":"stack-59087179","source":"stackoverflow","questionId":59087179,"title":"How update entity if exist or create if not exist entity","tags":["javascript","sql","nestjs","typeorm"],"text":"Title: How update entity if exist or create if not exist entity\nTags: javascript, sql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHere are my entities.\n\n```\n// user\n\n@PrimaryGeneratedColumn()\npublic id: number;\n\n@Column({ type: 'varchar', nullable: false })\npublic email: string;\n\n@Column({ type: 'varchar', nullable: false })\npublic password: string;\n\n@OneToOne(() => Token, (token: Token) => token.user)\npublic token: Token;\n```\n\n```\n// token\n\n@PrimaryGeneratedColumn()\npublic id: number;\n\n@Column({ type: 'varchar', nullable: false })\npublic uuid: string;\n\n@Column({ type: 'integer', nullable: false })\npublic userId: number;\n\n@OneToOne(() => User, (user: User) => user.hash, { cascade: ['insert', 'remove'] })\n@JoinColumn({ name: 'userId' })\npublic user: User;\n```\n\nThis is how I save current in my database.\n\n```\nprivate async savePayload(tokenDto: CreateTokenDto) {\n const token = this.tokenRepository.create(tokenDto);\n return await this.tokenRepository.save(token);\n}\n```\n\nWhen I first save my token to the database, all of it is saved.\n\nWhen I save a second time, I get an error.\n\nER_DUP_ENTRY: Duplicate entry '36' for key 'REL_d417e5d35f2434afc4bd48cb4d'\n\nI read in the documentation about the save method. But why I get the error, I can not understand. I expect the record to be updated. Why are my token details not updated?\n\nI understand how to do this using sql.\n\n```\nINSERT INTO \"Tokens\" (UUID, USERID)\n VALUES ('d93ab036-768c-420a-98d6-2f80c79e6ae7', 36)\n ON CONFLICT (USERID) \n DO UPDATE SET UUID = 'd93ab036-768c-420a-98d6-2f80c79e6ae7', \n USERID = 36'\n```\n\nAfter some experiments, I noticed that when I specify the token id, then saving or updating is successful.\n\n```\nprivate async savePayload(tokenDto: CreateTokenDto) {\n const a = {\n id: 15,\n uuid: '343443443444444444444444',\n userId: 36,\n };\n const token = this.tokenRepository.create(a);\n return await this.tokenRepository.save(token);\n}\n```\n\nBut if I didn’t indicate the id of the token, I get an error.\n\n```\nprivate async savePayload(tokenDto: CreateTokenDto) {\n const a = {\n // id: 15,\n uuid: '343443443444444444444444',\n userId: 36,\n };\n const token = this.tokenRepository.create(a);\n return await this.tokenRepository.save(token);\n}\n```\n\nER_DUP_ENTRY: Duplicate entry '36' for key 'REL_d417e5d35f2434afc4bd48cb4d'\n\nI searched and found some examples.\n\nTypeORM upsert - create if not exist\n\nhttps://github.com/typeorm/typeorm/issues/3342\n\nThey say that the value must be a primary key or a unique value. But my userId field is an index, and is also unique.\n\nhttps://i.sstatic.net/2oZ8r.png\n\nWhat options can be, why is my token not updated?\n\n========================================\n\nTop Answer:\nIt isn't saying that there is a duplicate entry in the table already, it is saying that there is already one entry in there with that value for the primary key and it is refusing to insert a second for that reason.\n\nYou will find one matching row, and that your code at the point of the error is trying to insert a second.\n\nDealing with duplicates on insert:\n\nIf you try INSERT a duplicate values for a primary key (or a unique index) you will always get that error. There are a couple of ways around it: check before you insert and either do an update (if something might have changed) or just don't do anything.\n\n========================================\n\nCode:\n```js\n// user\n\n@PrimaryGeneratedColumn()\npublic id: number;\n\n@Column({ type: 'varchar', nullable: false })\npublic email: string;\n\n@Column({ type: 'varchar', nullable: false })\npublic password: string;\n\n@OneToOne(() => Token, (token: Token) => token.user)\npublic token: Token;\n```\n\n```js\n// token\n\n@PrimaryGeneratedColumn()\npublic id: number;\n\n@Column({ type: 'varchar', nullable: false })\npublic uuid: string;\n\n@Column({ type: 'integer', nullable: false })\npublic userId: number;\n\n@OneToOne(() => User, (user: User) => user.hash, { cascade: ['insert', 'remove'] })\n@JoinColumn({ name: 'userId' })\npublic user: User;\n```\n\n```js\nprivate async savePayload(tokenDto: CreateTokenDto) {\n const token = this.tokenRepository.create(tokenDto);\n return await this.tokenRepository.save(token);\n}\n```\n\n```sql\nINSERT INTO \"Tokens\" (UUID, USERID)\n VALUES ('d93ab036-768c-420a-98d6-2f80c79e6ae7', 36)\n ON CONFLICT (USERID) \n DO UPDATE SET UUID = 'd93ab036-768c-420a-98d6-2f80c79e6ae7', \n USERID = 36'\n```\n\n```js\nprivate async savePayload(tokenDto: CreateTokenDto) {\n const a = {\n id: 15,\n uuid: '343443443444444444444444',\n userId: 36,\n };\n const token = this.tokenRepository.create(a);\n return await this.tokenRepository.save(token);\n}\n```\n\n```js\nprivate async savePayload(tokenDto: CreateTokenDto) {\n const a = {\n // id: 15,\n uuid: '343443443444444444444444',\n userId: 36,\n };\n const token = this.tokenRepository.create(a);\n return await this.tokenRepository.save(token);\n}\n```\n\n```js\nconst values = {\n uuid: '343443443444444444444444',\n userId: 36\n}\n\nawait connection.createQueryBuilder()\n .insert()\n .into(Tokens)\n .values(post2)\n .onConflict(`(\"userId\") DO UPDATE SET UUID = :uuid`)\n .setParameter(\"title\", values.uuid)\n .execute();\n```\n\n```js\n@Column({ type: 'varchar', nullable: false })\npublic uuid: string;\n\n@PrimaryColumn()\npublic userId: number;\n\n@OneToOne(() => User, (user: User) => user.hash, { cascade: ['insert', 'remove'] })\n@JoinColumn({ name: 'userId' })\npublic user: User;\n```\n\n```text\nRepository<T>.save()\n```\n\n```text\nsave()\n```\n\n```text\nid\n```\n\n```text\nsave()\n```\n\n```text\nid\n```\n\n```text\nsave()\n```\n\n```text\nuserId\n```\n\n```text\nsave()\n```\n\n```text\n@PrimaryGeneratedId\n```\n\n```text\n@PrimaryColumn\n```\n\n```js\nasync CreateNewRole(data: any): Promise<Role | any> {\n try {\n const entity = await this.roleRepository.create(data);\n const role = await this.roleRepository.save(entity);\n this.trackingService.create(data.user);\n return {\n success: true,\n role,\n };\n } catch (e) {\n // code == 23505 means duplication key\n if (parseInt(e.code) === 23505) {\n console.log('error : ', e.detail);\n return {\n success: false,\n message: ROLE_ERROR_MESSAGES.ROLE_IS_FOUND,\n };\n } else {\n return {\n success: false,\n };\n }\n }\n }\n\n async UpdateRole(data: any, id: number): Promise<Role | any> {\n try {\n await this.roleRepository.update(id, { ...data.payload });\n this.trackingService.create(data.user);\n // todo this need to be refactored !!\n // return back the updated entity\n const role = await this.roleRepository.find({ id });\n console.log('role updated ', role);\n return {\n role,\n success: true,\n };\n } catch (e) {\n if (parseInt(e.code) === 23505) {\n console.log('error : ', e.detail);\n return {\n success: false,\n message: ROLE_ERROR_MESSAGES.ROLE_IS_FOUND,\n };\n } else {\n return {\n success: false,\n };\n }\n }\n }\n```\n\n========================================\n\nComments:\n- Yes, the second option works as I expected. This is the most complete answer. thanks","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":320,"estimatedTokens":1812}}253{"id":"stack-63460693","source":"stackoverflow","questionId":63460693,"title":"Typescript: meaning of ? and ! in class properties","tags":["typescript","nestjs","typeorm"],"text":"Title: Typescript: meaning of ? and ! in class properties\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\n```\n@Column({ name: 'device_kind', type: 'int2', nullable: false })\ndeviceKind?: number;\n```\n\nCan anyone explain this code? I didn't understand why they added the '?' mark. and some of them has '!' instead of question mark.\nWhat do they mean?\n\n========================================\n\nCode:\n```text\n@Column({ name: 'device_kind', type: 'int2', nullable: false })\ndeviceKind?: number;\n```\n\n```js\ntype Foo = {\n prop1?: number\n}\n```\n\n```js\nclass Foo {\n // Typescript does not complain about `a` because we set it in the constructor\n public a: number;\n\n // Typescript will complain about `b` because we forgot it.\n public b: number;\n\n // Typescript will not complain about `c` because we told it not to.\n public c!: number;\n\n // Typescript will not complain about `d` because it's optional and is\n // allowed to be undefined.\n public d?: number;\n\n constructor() {\n this.a = 5;\n }\n\n}\n```\n\n```text\nprop1\n```\n\n```text\n!\n```\n\n```text\nc!\n```\n\n```text\nd?\n```\n\n```text\nd\n```\n\n```text\nnumber\n```\n\n```text\nundefined\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":76,"estimatedTokens":287}}254{"id":"stack-72810663","source":"stackoverflow","questionId":72810663,"title":"Argument of type '{ id: string; }' is not assignable to parameter of type 'FindOneOptions'","tags":["node.js","nestjs","typeorm","node-mongodb-native","node.js-typeorm"],"text":"Title: Argument of type '{ id: string; }' is not assignable to parameter of type 'FindOneOptions'\nTags: node.js, nestjs, typeorm, node-mongodb-native, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nUsing **mongodb** by **typeorm** with **nestjs** - create crud rest api\n\nWhen trying to get data by **findone()** with '**id**' . getting below error\n\nTS2345: Argument of type '{ id: string; }' is not assignable to parameter of type 'FindOneOptions'.\n\nObject literal may only specify known properties, and 'id' does not exist in type 'FindOneOptions'.\n\nCode:\n\n```\nconst result = await this.sellerRepository.findOne({ id });\n```\n\n**Entity**\n\n```\n@Entity('seller')\nexport class Seller {\n @ObjectIdColumn()\n id: ObjectID;\n @Column({\n type: 'string',\n nullable: false,\n name: 'product_name',\n })\n productName: string;\n @Column({\n name: 'short_desc',\n })\n}\n\nasync findOne(id: string): Promise {\n const result = await this.sellerRepository.findOne({ id });\n return result;\n }\n```\n\nhttps://i.sstatic.net/zyD5G.png\n\n========================================\n\nTop Answer:\nYou should use findOneBy\n\n```\nfindOne(id: number): Promise {\n return this.usersRepository.findOneBy({ id: id });\n}\n```\n\n========================================\n\nCode:\n```text\nconst result = await this.sellerRepository.findOne({ id });\n```\n\n```text\n@Entity('seller')\nexport class Seller {\n @ObjectIdColumn()\n id: ObjectID;\n @Column({\n type: 'string',\n nullable: false,\n name: 'product_name',\n })\n productName: string;\n @Column({\n name: 'short_desc',\n })\n}\n\nasync findOne(id: string): Promise<Seller> {\n const result = await this.sellerRepository.findOne({ id });\n return result;\n }\n```\n\n```text\nimport { ObjectID } from 'mongodb';\n async findOne(id: string): Promise<Seller> {\n const result = await this.sellerRepository.findOne(new ObjectID(id));\n return result;\n }\n```\n\n```text\nnew ObjectID(id)\n```\n\n```text\nimport { ObjectID } from 'mongodb';\n```\n\n```text\ndeclare module 'mongodb'\n```\n\n```text\nindex.d.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntypeRoots\n```\n\n```text\n\"typeRoots\": [ \"./typings\", \"./node_modules/@types/\" ]\n```\n\n```text\nfithOneBy({id})\n```\n\n```text\nfindOne(id)\n```\n\n```text\nfindOne(id: number): Promise<User> {\n return this.usersRepository.findOneBy({ id: id });\n}\n```\n\n```text\nimport { FindOptionsWhere } from 'typeorm';\n```\n\n```text\nconst result = await this.sellerRepository.findOne({ id: id as FindOptionsWhere<Seller> });\n```\n\n```js\nconst prodId = await this.productEntity.findOne({\n where: {\n column_name_in_Entity: defined initializer\n }\n})\n```\n\n========================================\n\nComments:\n- It's being discussed on github at github.com/typeorm/typeorm/issues/8939\n- Both tried but there is no use. I think typeorm gives this kind of error for mongodb\n- Are you sure the error remains the same?\n- yes..but got solution in another way..will post it...thank you for your response\n- Already tried with the above but did not work. It gives the same error message.","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":159,"estimatedTokens":749}}255{"id":"stack-72131909","source":"stackoverflow","questionId":72131909,"title":"NestJS TypeORM Optional Query not working","tags":["node.js","swagger","nestjs","typeorm"],"text":"Title: NestJS TypeORM Optional Query not working\nTags: node.js, swagger, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a problem that is I have set Query Params to optional, but it's not reflecting optional in swagger,\n\nHere is my code:\n\n```\n@Get('pagination')\n @ApiOperation({ summary: 'Get Activity Post Pagination Enabled' })\n public async getActivityPostPagination(\n @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,\n @Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit: number,\n @Query('user_id') user_id?: string,\n @Query('badge_id') badge_id?: string,\n @Query('title') title?: string,\n ) {\n //code here\n }\n```\n\nBut is swagger, it shows like this:\n\nhttps://i.sstatic.net/jNHAz.png\n\nThe page and limit and not optional, but for other query parameters must be optional, what Am I missing here?\n\nThank you\n\n========================================\n\nCode:\n```text\n@Get('pagination')\n @ApiOperation({ summary: 'Get Activity Post Pagination Enabled' })\n public async getActivityPostPagination(\n @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,\n @Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit: number,\n @Query('user_id') user_id?: string,\n @Query('badge_id') badge_id?: string,\n @Query('title') title?: string,\n ) {\n //code here\n }\n```\n\n```text\n@Get('pagination')\n @ApiOperation({ summary: 'Get Activity Post Pagination Enabled' })\n @ApiQuery({ name: 'user_id', required: false, type: String })\n @ApiQuery({ name: 'badge_id', required: false, type: String })\n public async getActivityPostPagination(\n @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,\n @Query('limit', new DefaultValuePipe(10), ParseIntPipe) limit: number,\n @Query('user_id') user_id?: string,\n @Query('badge_id') badge_id?: string,\n @Query('title') title?: string,\n ) {\n //code here\n }\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":63,"estimatedTokens":473}}256{"id":"stack-64722060","source":"stackoverflow","questionId":64722060,"title":"What is the correct way how to create relation in typeorm?","tags":["typescript","entity-relationship","typeorm"],"text":"Title: What is the correct way how to create relation in typeorm?\nTags: typescript, entity-relationship, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have two entities:\n\n```\n@Entity({ name: 'provider' })\nexport class ProviderEntity extends GenericEntity {\n\n @Column()\n name: string;\n\n @Column()\n description: string;\n\n @OneToMany(() => ItemEntity, item => item.provider)\n items: Promise;\n\n}\n\n@Entity({ name: 'item' })\nexport class ItemEntity extends GenericEntity {\n\n @Column()\n content: string;\n\n @ManyToOne(() => ProviderEntity, provider => provider.items)\n provider: Promise;\n\n}\n```\n\n`Provider` object already exist in database and I would like to create `item` with realtion to `provider`.\n\nMy code is:\n\n```\nconst content = 'mockContent';\n const providerId = '5be045b1-ef49-4818-b69f-a45c0b7e53';\n \n const item = new ItemEntity();\n item.content = content;\n item.provider = providerId; // ERROR\n\n await this.repository.save(item);\n return item;\n```\n\nThe code it works, but I am getting an typescript error `Type 'string' is not assignable to type 'Promise'.`. What is the correct way how to insert this?\n\nGeneric entity class contains only id\n\n```\n@PrimaryGeneratedColumn('uuid')\nid: string;\n```\n\n========================================\n\nTop Answer:\nThanks to @alex-wayne who pointed out this question to me. For Reference, the approach which he proposed most likely originated from this github issue. More precisely this answer from pleerock, the core contributor.\n\nMoreover, I personally prefer the first approach. In practice, with the addition to using the `create` method:\n\n```\nconst content = 'mockContent';\nconst providerId = '5be045b1-ef49-4818-b69f-a45c0b7e53';\n\nconst provider = new Provider();\nprovider.id = providerId;\n \nconst item = this.itemRepository.create({ content, provider })\n\nawait this.repository.save(item);\n```\n\n========================================\n\nCode:\n```text\n@Entity({ name: 'provider' })\nexport class ProviderEntity extends GenericEntity {\n\n @Column()\n name: string;\n\n @Column()\n description: string;\n\n @OneToMany(() => ItemEntity, item => item.provider)\n items: Promise<ItemEntity[]>;\n\n}\n\n@Entity({ name: 'item' })\nexport class ItemEntity extends GenericEntity {\n\n @Column()\n content: string;\n\n @ManyToOne(() => ProviderEntity, provider => provider.items)\n provider: Promise<ProviderEntity>;\n\n}\n```\n\n```text\nconst content = 'mockContent';\n const providerId = '5be045b1-ef49-4818-b69f-a45c0b7e53';\n \n const item = new ItemEntity();\n item.content = content;\n item.provider = providerId; // ERROR\n\n await this.repository.save(item);\n return item;\n```\n\n```text\n@PrimaryGeneratedColumn('uuid')\nid: string;\n```\n\n```text\nProvider\n```\n\n```text\nitem\n```\n\n```text\nprovider\n```\n\n```text\nType 'string' is not assignable to type 'Promise<ProviderEntity>'.\n```\n\n```text\n@ManyToOne(() => ProviderEntity, provider => provider.items)\nprovider: Promise<ProviderEntity>;\n\n@Column()\nproviderId: string\n```\n\n```text\nconst item = new ItemEntity();\nitem.content = content;\nitem.providerId = providerId; // set providerId column directly.\n\nawait this.repository.save(item);\n```\n\n```text\nproviderId\n```\n\n```text\nconst content = 'mockContent';\nconst providerId = '5be045b1-ef49-4818-b69f-a45c0b7e53';\n\nconst provider = new Provider();\nprovider.id = providerId;\n \nconst item = this.itemRepository.create({ content, provider })\n\nawait this.repository.save(item);\n```\n\n```text\ncreate\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":176,"estimatedTokens":870}}257{"id":"stack-54778197","source":"stackoverflow","questionId":54778197,"title":"How do I return an id string instead of a _bsontype with NestJS Serialization","tags":["node.js","typescript","nestjs","typeorm","class-transformer"],"text":"Title: How do I return an id string instead of a _bsontype with NestJS Serialization\nTags: node.js, typescript, nestjs, typeorm, class-transformer\nSource: Stack Overflow\n\nQuestion:\nWhen using\n\n```\n@UseInterceptors(ClassSerializerInterceptor)\n```\n\nlike it is explained in the Documentation here\n\nI get the desired filtered result, however while using mongodb the id is formatted in `_bsontype` instead of a normal `string` like it used to be without the interceptor like this:\n\n```\n{\n \"id\": {\n \"_bsontype\": \"ObjectID\",\n \"id\": {\n \"0\": 92,\n \"1\": 108,\n \"2\": 182,\n \"3\": 85,\n \"4\": 185,\n \"5\": 20,\n \"6\": 221,\n \"7\": 12,\n \"8\": 56,\n \"9\": 66,\n \"10\": 131,\n \"11\": 172\n }\n },\n \"createdAt\": \"2019-02-20T02:07:17.895Z\",\n \"updatedAt\": \"2019-02-20T02:07:17.895Z\",\n \"firstName\": \"The First Name\",\n \"lastName\": \"The Last Name\",\n \"email\": \"giberish@gmail.com\"\n}\n```\n\nHow can I convert it back to a normal id string like this?\n\n```\n{\n \"id\": \"5c6cb655b914dd0c384283ac\",\n \"createdAt\": \"2019-02-20T02:07:17.895Z\",\n \"updatedAt\": \"2019-02-20T02:07:17.895Z\",\n \"firstName\": \"The First Name\",\n \"lastName\": \"The Last Name\",\n \"email\": \"giberish@gmail.com\"\n \"password\": \"okthen\"\n}\n```\n\n========================================\n\nCode:\n```text\n@UseInterceptors(ClassSerializerInterceptor)\n```\n\n```text\n{\n \"id\": {\n \"_bsontype\": \"ObjectID\",\n \"id\": {\n \"0\": 92,\n \"1\": 108,\n \"2\": 182,\n \"3\": 85,\n \"4\": 185,\n \"5\": 20,\n \"6\": 221,\n \"7\": 12,\n \"8\": 56,\n \"9\": 66,\n \"10\": 131,\n \"11\": 172\n }\n },\n \"createdAt\": \"2019-02-20T02:07:17.895Z\",\n \"updatedAt\": \"2019-02-20T02:07:17.895Z\",\n \"firstName\": \"The First Name\",\n \"lastName\": \"The Last Name\",\n \"email\": \"giberish@gmail.com\"\n}\n```\n\n```text\n{\n \"id\": \"5c6cb655b914dd0c384283ac\",\n \"createdAt\": \"2019-02-20T02:07:17.895Z\",\n \"updatedAt\": \"2019-02-20T02:07:17.895Z\",\n \"firstName\": \"The First Name\",\n \"lastName\": \"The Last Name\",\n \"email\": \"giberish@gmail.com\"\n \"password\": \"okthen\"\n}\n```\n\n```text\n_bsontype\n```\n\n```text\nstring\n```\n\n```text\nimport { Transform } from 'class-transformer';\n\n@Entity()\nexport class User {\n @ObjectIdColumn()\n @Transform(({ value }) => value.toString(), { toPlainOnly: true })\n _id: ObjectID;\n```\n\n```text\n@Transform()\n```\n\n```text\ntoPlainOnly\n```\n\n```text\nClassSerializerInterceptor\n```\n\n```text\nclassToPlain()\n```\n\n========================================\n\nComments:\n- It might help to lift the relevant repro steps from the link into your question directly.\n- The answer returns [Object Object] for me. I have to use `@Transform(({value}) => value.toString(), { toPlainOnly: true })`\n- @webHasan Thanks for your comment, I have updated the answer. The signature has changed with version 0.3.2, see changelog: github.com/typestack/class-transformer/blob/v0.5.1/…","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":142,"estimatedTokens":723}}258{"id":"stack-73796643","source":"stackoverflow","questionId":73796643,"title":"TypeORM - Requirement nullable option in relationship for @OneToMany side","tags":["node.js","typeorm","node.js-typeorm"],"text":"Title: TypeORM - Requirement nullable option in relationship for @OneToMany side\nTags: node.js, typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nIn a project I need a nullable ManyToOne - OneToMany relation between two different entities. For now I solved it like this:\n\nL1Log Entity (ManyToOne side)\n\n```\n@Entity()\nexport class L1Log extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n uuid: string\n\n @Column({ type: 'varchar', nullable: true })\n dimonaCancelUuid?: string\n\n @ManyToOne(() => DimonaCancel, dimonaCancel => dimonaCancel.l1Logs, { nullable: true })\n @JoinColumn({ name: 'dimonaCancelUuid' })\n dimonaCancel?: DimonaCancel\n}\n```\n\nDimonaCancel Entity (OneToMany side)\n\n```\n@Entity()\nexport class DimonaCancel extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n uuid: string\n \n @OneToMany(() => L1Log, l1Log => l1Log.dimonaCancel, { nullable: true })\n l1Logs?: L1Log[]\n}\n```\n\nMy question is now whether or not the *{ nullable: true }* option is needed in the *@OneToMany* side of the relation because the *@OneToMany* will be an empty array when there are no relations setup?\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class L1Log extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n uuid: string\n\n @Column({ type: 'varchar', nullable: true })\n dimonaCancelUuid?: string\n\n @ManyToOne(() => DimonaCancel, dimonaCancel => dimonaCancel.l1Logs, { nullable: true })\n @JoinColumn({ name: 'dimonaCancelUuid' })\n dimonaCancel?: DimonaCancel\n}\n```\n\n```text\n@Entity()\nexport class DimonaCancel extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n uuid: string\n \n @OneToMany(() => L1Log, l1Log => l1Log.dimonaCancel, { nullable: true })\n l1Logs?: L1Log[]\n}\n```\n\n```text\n@OneToMany(() => L1Log, l1Log => l1Log.dimonaCancel)\n l1Logs?: L1Log[]\n```\n\n```text\n@ManyToOne(() => DimonaCancel, dimonaCancel => dimonaCancel.l1Logs, { nullable: true })\n @JoinColumn({ name: 'dimonaCancelUuid' })\n dimonaCancel?: DimonaCancel | null\n```\n\n```text\nnullable: true\n```\n\n```text\nL1Log\n```\n\n```text\nnullable: true\n```\n\n```text\nDimonaCancel | null\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":94,"estimatedTokens":525}}259{"id":"stack-40820195","source":"stackoverflow","questionId":40820195,"title":"Creating generic repository using TypeORM","tags":["node.js","generics","typescript","typeorm"],"text":"Title: Creating generic repository using TypeORM\nTags: node.js, generics, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using typeorm and I want to create a generic repository:\n\n```\nimport \"reflect-metadata\";\nimport { DBManager } from './db-manager';\nimport { Photo } from './entities/Photo';\nimport { createConnection, Connection } from \"typeorm\";\n\nclass GenericRepository {\nprivate connection: DBManager;\nconstructor(connection: DBManager) {\n this.connection = connection;\n}\n\npublic list(): T[] {\n let result: T[] = [];\n this.connection.connect().then(async connection => {\n result = await >(connection.entityManager.find(T));\n });\n return result;\n }\n}\n\nlet genericReposity = new GenericRepository(new DBManager());\ngenericReposity.list();\n```\n\nThis code of course doesn't woork and complains on `find` method that can not find name `T`\n\n`T` should be my entity but I don't know how to achieve this\n\n========================================\n\nCode:\n```text\nimport \"reflect-metadata\";\nimport { DBManager } from './db-manager';\nimport { Photo } from './entities/Photo';\nimport { createConnection, Connection } from \"typeorm\";\n\nclass GenericRepository<T> {\nprivate connection: DBManager;\nconstructor(connection: DBManager) {\n this.connection = connection;\n}\n\npublic list(): T[] {\n let result: T[] = [];\n this.connection.connect().then(async connection => {\n result = await <Promise<T[]>>(connection.entityManager.find(T));\n });\n return result;\n }\n}\n\nlet genericReposity = new GenericRepository<Photo>(new DBManager());\ngenericReposity.list();\n```\n\n```text\nfind\n```\n\n```text\nT\n```\n\n```text\nT\n```\n\n```text\nimport \"reflect-metadata\";\nimport { DBManager } from './db-manager';\nimport { Photo } from './entities/Photo';\nimport { createConnection, Connection } from \"typeorm\";\n\nexport type ObjectType<T> = { new (): T } | Function;\n\nclass GenericRepository<T> {\n private connection: DBManager;\n private type: ObjectType<T>;\n constructor(type: ObjectType<T>, connection: DBManager) {\n this.type = type; \n this.connection = connection;\n}\n\npublic list(): T[] {\n let result: T[] = [];\n this.connection.connect().then(async connection => {\n result = await <Promise<T[]>>(connection.entityManager.find(this.type));\n });\n return result;\n }\n}\n\nlet genericReposity = new GenericRepository(Photo, new DBManager());\ngenericReposity.list();\n```\n\n========================================\n\nComments:\n- what doesn't work? what is the actual problem?\n- I edited my example hope it is more clear now but basically .find(T) complains that can not fine name T T should be the Photo but since I want to my class be a generic class so I need somehow to pass the type to my generic method\n- Tried this solution too but still complains [ts] Argument of type 'T' is not assignable to parameter of type 'ObjectType'. Type 'T' is not assignable to type 'new () => {}'.\n- For the connection actually i'm using injectors but didn't bring it here\n- @user4092086 I made small changes, take a look on them. Also take a look on github.com/typeorm/typeorm-typedi-extensions this may help you to organize your code\n- Thanks this works But I'm wonder how can I bind ObjectType in my injector?","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":114,"estimatedTokens":809}}260{"id":"stack-72865932","source":"stackoverflow","questionId":72865932,"title":"How to create autoincrement integer field in TypeORM migration?","tags":["mysql","database","typeorm","node.js-typeorm"],"text":"Title: How to create autoincrement integer field in TypeORM migration?\nTags: mysql, database, typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nI design a table and want an integer autoincrement column for an ID.\nFor sure, I read the docs about `isGenerated` param for migrations.\n\nNow, my code looks like this:\n\n```\npublic async up(queryRunner: QueryRunner): Promise {\n\n await queryRunner.createTable(\n new Table({\n name: tableName,\n\n columns: [\n {\n name: \"id\",\n type: \"int\",\n isGenerated: true,\n isPrimary: true,\n },\n {\n name: \"seller_id\",\n type: \"int\"\n }\n ]\n })\n )\n}\n```\n\nBut as a result, I got: https://i.sstatic.net/qA9Mm.png\n\nAs you can see, `id` is not flagged as `AI`. What I'm doing wrong?\n\n========================================\n\nCode:\n```text\npublic async up(queryRunner: QueryRunner): Promise<void> {\n\n await queryRunner.createTable(\n new Table({\n name: tableName,\n\n columns: [\n {\n name: \"id\",\n type: \"int\",\n isGenerated: true,\n isPrimary: true,\n },\n {\n name: \"seller_id\",\n type: \"int\"\n }\n ]\n })\n )\n}\n```\n\n```text\nisGenerated\n```\n\n```text\nid\n```\n\n```text\nAI\n```\n\n```text\n{\n name: \"id\",\n type: \"int\",\n isPrimary: true,\n isGenerated: true,\n generationStrategy: \"increment\"\n },\n```\n\n```text\ngenerationStrategy?: \"uuid\" | \"increment\" | \"rowid\" | \"identity\";\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":90,"estimatedTokens":397}}261{"id":"stack-69103543","source":"stackoverflow","questionId":69103543,"title":"How to get distinct values from typeorm find \"query\"","tags":["nestjs","typeorm"],"text":"Title: How to get distinct values from typeorm find \"query\"\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to implement the following query on typeorm but unable to filter out the distinct values.\n\n```\nSELECT DISTINCT name, description, style, spec2, div FROM clothes WHERE name = 'CMD' and div in ('B01', 'B06', 'B07', 'B09')\n```\n\nMy existing code is like following.\n\n```\nthis._itemRepository.find({\n where: {\n \"name\" : \"values\",\n \"div\" : In([\"v1\",\"v2\"])\n },\n })\n```\n\nfind() method's parameter is `FindManyOptions` type but it doesn't have any attribute related to distinct values. Please help me to find a way\n\n========================================\n\nCode:\n```text\nSELECT DISTINCT name, description, style, spec2, div FROM clothes WHERE name = 'CMD' and div in ('B01', 'B06', 'B07', 'B09')\n```\n\n```text\nthis._itemRepository.find({\n where: {\n \"name\" : \"values\",\n \"div\" : In([\"v1\",\"v2\"])\n },\n })\n```\n\n```text\nFindManyOptions\n```\n\n```text\nthis._itemRepository.createQueryBuilder('clothes')\n.select(['name', 'description', 'style', 'spec2', 'div'])\n.where('name = CMD AND div IN (B01, B06, B07, B09)')\n.distinct()\n```\n\n```text\nthis._itemRepository.createQueryBuilder('clothes')\n.select('DISTINCT(name)')\n.where('name = CMD AND div IN (B01, B06, B07, B09)')\n```\n\n```text\nfind\n```\n\n```text\nqueryBuilder\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":64,"estimatedTokens":338}}262{"id":"stack-66306793","source":"stackoverflow","questionId":66306793,"title":"How to use @admin-bro/nestjs with @admin-bro/typeorm and postgres in a right way?","tags":["node.js","postgresql","nestjs","typeorm","admin-bro"],"text":"Title: How to use @admin-bro/nestjs with @admin-bro/typeorm and postgres in a right way?\nTags: node.js, postgresql, nestjs, typeorm, admin-bro\nSource: Stack Overflow\n\nQuestion:\nThe admin-bro-nestjs repository contains a comprehensive example with example with mongoose. But I need use it with typeorm and postgres.\n\nI tried to adapt this example for typeorm:\n\n```\n// main.ts\nimport AdminBro from 'admin-bro';\nimport { Database, Resource } from '@admin-bro/typeorm';\nimport { NestFactory } from '@nestjs/core';\n\nimport { AppModule } from './app.module';\n\nAdminBro.registerAdapter({ Database, Resource });\n\nconst bootstrap = async () => {\n const app = await NestFactory.create(AppModule);\n await app.listen(3000);\n}\nbootstrap();\n```\n\nand\n\n```\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { AdminModule } from '@admin-bro/nestjs';\nimport { TypeOrmModule, getRepositoryToken } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { UserEntity } from './user/user.entity';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'password',\n database: 'database_test',\n entities: [UserEntity],\n synchronize: true,\n logging: false,\n }),\n AdminModule.createAdminAsync({\n imports: [\n TypeOrmModule.forFeature([UserEntity]),\n ],\n inject: [\n getRepositoryToken(UserEntity),\n ],\n useFactory: (userRepository: Repository) => ({\n adminBroOptions: {\n rootPath: '/admin',\n resources: [\n { resource: userRepository },\n ],\n },\n auth: {\n authenticate: async (email, password) => Promise.resolve({ email: 'test' }),\n cookieName: 'test',\n cookiePassword: 'testPass',\n },\n }),\n }),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule { }\n```\n\nBut on application start I get the following error:\n\n```\nNoResourceAdapterError: There are no adapters supporting one of the resource you provided\n```\n\nDoes anyone have any experience putting all these libraries together?\n\n========================================\n\nCode:\n```text\n// main.ts\nimport AdminBro from 'admin-bro';\nimport { Database, Resource } from '@admin-bro/typeorm';\nimport { NestFactory } from '@nestjs/core';\n\nimport { AppModule } from './app.module';\n\nAdminBro.registerAdapter({ Database, Resource });\n\nconst bootstrap = async () => {\n const app = await NestFactory.create(AppModule);\n await app.listen(3000);\n}\nbootstrap();\n```\n\n```text\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { AdminModule } from '@admin-bro/nestjs';\nimport { TypeOrmModule, getRepositoryToken } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { UserEntity } from './user/user.entity';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: 'password',\n database: 'database_test',\n entities: [UserEntity],\n synchronize: true,\n logging: false,\n }),\n AdminModule.createAdminAsync({\n imports: [\n TypeOrmModule.forFeature([UserEntity]),\n ],\n inject: [\n getRepositoryToken(UserEntity),\n ],\n useFactory: (userRepository: Repository<UserEntity>) => ({\n adminBroOptions: {\n rootPath: '/admin',\n resources: [\n { resource: userRepository },\n ],\n },\n auth: {\n authenticate: async (email, password) => Promise.resolve({ email: 'test' }),\n cookieName: 'test',\n cookiePassword: 'testPass',\n },\n }),\n }),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule { }\n```\n\n```text\nNoResourceAdapterError: There are no adapters supporting one of the resource you provided\n```\n\n```text\n// user.entity\nimport { Entity, BaseEntity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class UserEntity extends BaseEntity{\n @PrimaryGeneratedColumn()\n id: number;\n @Column()\n name: string;\n}\n```\n\n```text\n// app.module.ts\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AdminModule } from '@admin-bro/nestjs';\n \nimport { Database, Resource } from '@admin-bro/typeorm';\nimport AdminBro from 'admin-bro'\nAdminBro.registerAdapter({ Database, Resource });\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n // ...\n }),\n AdminModule.createAdmin({\n adminBroOptions: {\n resources: [UserEntity],\n rootPath: '/admin',\n },\n })\n ],\n // ...\n})\n```\n\n```text\nNoResourceAdapterError: There are no adapters supporting one of the resource you provided\n```\n\n```text\nNoResourceAdapterError\n```\n\n```text\nUserEntity\n```\n\n```text\nBaseEntity\n```\n\n```text\nBaseEntity\n```\n\n========================================\n\nComments:\n- this answer worked for me, saved me hours of debugging and checking what's wrong\n- I didn't think this would do anything, but turns out it was the root cause for me also.\n- My entities extends to BaseEntity, still the problem continues","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":229,"estimatedTokens":1314}}263{"id":"stack-72753717","source":"stackoverflow","questionId":72753717,"title":"Select columns from sub-relation not working in typeorm","tags":["javascript","node.js","nestjs","typeorm"],"text":"Title: Select columns from sub-relation not working in typeorm\nTags: javascript, node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have an `Order` and `User` Entities\n\n### Order\n\n```\n@Entity('orders')\nexport class Order {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column('enum', {enum: OrderStatus, default: OrderStatus.NEW})\n status: OrderStatus\n \n @Column('float')\n amount: number\n\n @Column('float')\n fees: number\n\n @ManyToOne(() => User, (user) => user.orders)\n user: User;\n \n @OneToMany(() => OrderToProduct, orderToProduct => orderToProduct.order, {\n cascade: true,\n })\n products: OrderToProduct[]\n\n @CreateDateColumn()\n createdAt: Date = new Date();\n\n @UpdateDateColumn()\n updatedAt: Date;\n}\n```\n\n### User\n\n```\n@Entity('users')\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({length: 255})\n name: string;\n \n @Column({length: 255, unique: true})\n email: string;\n\n @Column({length: 255})\n password: string; \n\n @CreateDateColumn()\n createdAt: Date = new Date();\n \n @OneToMany(() => Order, (order) => order.user)\n orders: Order[];\n\n @UpdateDateColumn()\n updatedAt: Date;\n\n @OneToMany(() => Product, (product) => product.user)\n products: Product[]\n\n}\n```\n\nAll I want is to retrieve the orders with their user `name` only what I try is like this\n\n```\nthis.orderRepository.find({\n relations: {\n user: {\n id: true,\n name: true\n }\n },\n where: {\n user: {\n id: user.id\n }\n }\n})\n```\n\nbut it returns with an error\n\nEntityPropertyNotFoundError: Property \"id\" was not found in \"User\". Make sure your query is correct.\n\nBut if i try to get all the object of user like this it works fine\n\n```\nrelations: {\n user: true\n},\n```\n\n========================================\n\nTop Answer:\nThe error is that our queries have fields with the same name as the \"id\" so you have to add to the select these fields:\n\n```\nthis.userRepository.findOne({ \n where: { id: res.locals.user },\n select: { \n firstName: true,\n lastName: true,\n email: true,\n phone: true,\n createdAt: true,\n updatedAt: true,\n role: { name: true },\n }, \n relations: { role: true }, \n})\n.then(user => res.status(200).json(user))\n.catch(( error: MysqlError ) => res.status(500).json([{ message: error.message }]))\n```\n\n```\n[\n {\n \"message\": \"ER_BAD_FIELD_ERROR: Unknown column 'distinctAlias.User_id' in 'field list'\"\n }\n]\n```\n\nAnd the correct way to write it is:\n\n```\nthis.userRepository.findOne({ \n where: { id: res.locals.user },\n select: { \n id: true,\n firstName: true,\n lastName: true,\n email: true,\n phone: true,\n createdAt: true,\n updatedAt: true,\n role: { id: true, name: true },\n }, \n relations: { role: true }, \n})\n.then(user => res.status(200).json(user))\n.catch(( error:MysqlError ) => res.status(500).json([{ message: error.message }]))\n```\n\n```\n{\n \"id\": 1,\n \"email\": \"andres_rod24@hotmail.com\",\n \"phone\": \"3016224924\",\n \"firstName\": \"Juan Andres\",\n \"lastName\": \"Rodriguez Arenas\",\n \"createdAt\": \"2023-01-04T03:49:57.092Z\",\n \"updatedAt\": \"2023-01-04T03:49:57.092Z\",\n \"role\": {\n \"id\": 1,\n \"name\": \"Administrator\"\n }\n}\n```\n\n========================================\n\nCode:\n```js\n@Entity('orders')\nexport class Order {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column('enum', {enum: OrderStatus, default: OrderStatus.NEW})\n status: OrderStatus\n \n @Column('float')\n amount: number\n\n @Column('float')\n fees: number\n\n @ManyToOne(() => User, (user) => user.orders)\n user: User;\n \n @OneToMany(() => OrderToProduct, orderToProduct => orderToProduct.order, {\n cascade: true,\n })\n products: OrderToProduct[]\n\n @CreateDateColumn()\n createdAt: Date = new Date();\n\n @UpdateDateColumn()\n updatedAt: Date;\n}\n```\n\n```js\n@Entity('users')\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({length: 255})\n name: string;\n \n @Column({length: 255, unique: true})\n email: string;\n\n @Column({length: 255})\n password: string; \n\n @CreateDateColumn()\n createdAt: Date = new Date();\n \n @OneToMany(() => Order, (order) => order.user)\n orders: Order[];\n\n @UpdateDateColumn()\n updatedAt: Date;\n\n @OneToMany(() => Product, (product) => product.user)\n products: Product[]\n\n}\n```\n\n```js\nthis.orderRepository.find({\n relations: {\n user: {\n id: true,\n name: true\n }\n },\n where: {\n user: {\n id: user.id\n }\n }\n})\n```\n\n```text\nrelations: {\n user: true\n},\n```\n\n```text\nOrder\n```\n\n```text\nUser\n```\n\n```text\nname\n```\n\n```text\nrelations: {\n user:true\n},\nwhere: {\n user: {\n id: user.id\n }\n},\nselect: {\n user: {\n id:true,\n name: true\n }\n// your other columns from order entity.\n}\n```\n\n```js\nthis.userRepository.findOne({ \n where: { id: res.locals.user },\n select: { \n firstName: true,\n lastName: true,\n email: true,\n phone: true,\n createdAt: true,\n updatedAt: true,\n role: { name: true },\n }, \n relations: { role: true }, \n})\n.then(user => res.status(200).json(user))\n.catch(( error: MysqlError ) => res.status(500).json([{ message: error.message }]))\n```\n\n```json\n[\n {\n \"message\": \"ER_BAD_FIELD_ERROR: Unknown column 'distinctAlias.User_id' in 'field list'\"\n }\n]\n```\n\n```js\nthis.userRepository.findOne({ \n where: { id: res.locals.user },\n select: { \n id: true,\n firstName: true,\n lastName: true,\n email: true,\n phone: true,\n createdAt: true,\n updatedAt: true,\n role: { id: true, name: true },\n }, \n relations: { role: true }, \n})\n.then(user => res.status(200).json(user))\n.catch(( error:MysqlError ) => res.status(500).json([{ message: error.message }]))\n```\n\n```json\n{\n \"id\": 1,\n \"email\": \"andres_rod24@hotmail.com\",\n \"phone\": \"3016224924\",\n \"firstName\": \"Juan Andres\",\n \"lastName\": \"Rodriguez Arenas\",\n \"createdAt\": \"2023-01-04T03:49:57.092Z\",\n \"updatedAt\": \"2023-01-04T03:49:57.092Z\",\n \"role\": {\n \"id\": 1,\n \"name\": \"Administrator\"\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":346,"estimatedTokens":1484}}264{"id":"stack-64282183","source":"stackoverflow","questionId":64282183,"title":"NestJS. Can't inject a repository from a different module","tags":["nestjs","typeorm"],"text":"Title: NestJS. Can't inject a repository from a different module\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to use a *typeorm custom repository* defined in another module.\n\nFollowing the documentation:\n\nIf you want to use the repository outside of the module which imports TypeOrmModule.forFeature, you'll need to re-export the providers generated by it. You can do this by exporting the whole module, like this:\n\n```\n@Module({\n imports: [TypeOrmModule.forFeature([Role])],\n exports: [TypeOrmModule]\n})\nexport class RoleModule {}\n```\n\nNow if we import UsersModule in UserHttpModule, we can use @InjectRepository(User) in the providers of the latter module.\n\nIn my case i do:\n\n```\n@Module({\n imports: [RoleModule],\n providers: [UsersService],\n controllers: [UsersController]\n})\nexport class UserModule {}\n```\n\nNow when i inject the Role repository\n\n```\nexport class UserService {\n constructor(@InjectRepository(Role) private roleRepository: Repository) {}\n}\n```\n\ni've got an error:\n`Nest can't resolve dependencies of the UserService (?).`\n\nIs it me or is the documentation incorrect?\nCan someone suggest what is the error here or give a corrected example?\n\n========================================\n\nCode:\n```text\n@Module({\n imports: [TypeOrmModule.forFeature([Role])],\n exports: [TypeOrmModule]\n})\nexport class RoleModule {}\n```\n\n```text\n@Module({\n imports: [RoleModule],\n providers: [UsersService],\n controllers: [UsersController]\n})\nexport class UserModule {}\n```\n\n```text\nexport class UserService {\n constructor(@InjectRepository(Role) private roleRepository: Repository<Role>) {}\n}\n```\n\n```text\nNest can't resolve dependencies of the UserService (?).\n```\n\n```text\n@Module({\n imports: [TypeOrmModule.forFeature([Role]), RoleModule], // <-- here\n providers: [UsersService],\n controllers: [UsersController]\n})\nexport class UserModule {}\n```\n\n```text\nTypeOrmModule.forFeature([Role])\n```\n\n========================================\n\nComments:\n- I know you've already accepted an answer, but what was the full error you were getting?\n- `[ExceptionHandler] Nest can't resolve dependencies of the UserService (?). Please make sure that the argument RoleRepository at index [1] is available in the UserModule context. Potential solutions: - If RoleRepository is a provider, is it part of the current UserModule? - If RoleRepository is exported from a separate @Module, is that module imported within UserModule? @Module({ imports: [ /* the Module containing RoleRepository */ ] })`\n- do we need to import RoleModule as well? If i omit RoleModule in import and only import `TypeOrmModule.forFeature([Role])` it doesn't work?\n- Why do we have to import the entities again although we already import the whole module which contains the corresponding entity?","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":96,"estimatedTokens":698}}265{"id":"stack-69291211","source":"stackoverflow","questionId":69291211,"title":"TypeORM error with MongoDB: .find() does not work, error: TypeError: Cannot read property 'prototype' of undefined","tags":["mongodb","nestjs","typeorm"],"text":"Title: TypeORM error with MongoDB: .find() does not work, error: TypeError: Cannot read property 'prototype' of undefined\nTags: mongodb, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI set up a Nest.Js / TypeORM / MongoDB stack as described here.\n\nIt works to create an object user in MongoDB using the `create()` function, the object is recorded into the right database into the `User` collection.\n\nHowever, when I attempt to get it using the `find({id})` or the `findAll()` function I get an error and I cannot get the item from the database even though it's there.\n\nHere is my `user.service.ts` file:\n\n```\nimport { Injectable, HttpException, HttpStatus } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { MongoRepository } from 'typeorm';\nimport { validate } from 'class-validator';\nimport { CreateUserDto } from './user.dto';\nimport { User } from '../model/user.entity';\nimport { UserRO } from './user.interface';\n\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(User)\n private readonly userRepository: MongoRepository,\n ) {}\n\n // abstracting access to the model via service\n public async getAll() {\n // getting data from database\n return await this.userRepository.find();\n }\n\n // abstracting access to the model via service\n public async get(id: string) {\n const user = await this.userRepository.findOne({ _id: id });\n if (!user) {\n const errors = { User: ' not found' };\n throw new HttpException({ errors }, 401);\n }\n\n return this.buildUserRO(user);\n }\n\n async create(dto: CreateUserDto): Promise {\n // check uniqueness of username/email\n const { username } = dto;\n const newUser = new User();\n newUser.username = username;\n // newUser.contexts = [];\n\n const errors = await validate(newUser);\n if (errors.length > 0) {\n const _errors = { username: 'Userinput is not valid.' };\n throw new HttpException(\n { message: 'Input data validation failed', _errors },\n HttpStatus.BAD_REQUEST,\n );\n } else {\n const savedUser = await this.userRepository.save(newUser);\n return this.buildUserRO(savedUser);\n }\n }\n\n}\n```\n\nand also the `user.interface.ts`:\n\n```\nexport interface UserData {\n username: string;\n _id: string;\n}\n\n// user response object\nexport interface UserRO {\n user: UserData;\n}\n```\n\nand a part of the `user.controller.ts`:\n\n```\n@Get(':id')\n findOne(@Param('id') id: string): Promise {\n console.log(`getting user with id: ${id}`);\n const user = this.serv.get(id);\n return user;\n }\n```\n\nand finally the `model/user.entity.ts`:\n\n```\n@Entity({ name: 'User' })\nexport class User {\n @ObjectIdColumn()\n _id: string;\n\n @Column({ type: 'varchar', length: 50 })\n username: string;\n\n @OneToMany((type) => Context, (context) => context.user)\n contexts: Context[];\n}\n```\n\nThe error I get when I try to find the saved context:\n\n```\n[Nest] 75671 - 09/22/2021, 9:22:18 PM ERROR [ExceptionsHandler] Cannot read property 'prototype' of undefined\nTypeError: Cannot read property 'prototype' of undefined\n at FindCursor.cursor.toArray (/Users/deemeetree/Documents/Root/benchmark-sql-graph/src/entity-manager/MongoEntityManager.ts:707:37)\n at MongoEntityManager. (/Users/deemeetree/Documents/Root/benchmark-sql-graph/src/entity-manager/MongoEntityManager.ts:190:46)\n at step (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:143:27)\n at Object.next (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:124:57)\n at fulfilled (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:114:62)\n at processTicksAndRejections (internal/process/task_queues.js:97:5)\n```\n\nI tried with MongoDB 4. and 3. versions and it's the same problem.\n\nWhat am I doing wrong and how to get pass this error and be able to query the records well in MongoDB?\n\nThanks!\n\n========================================\n\nTop Answer:\nThis is a version issue.\nTo fix this try to use **version 3** by downgrading\n\nFirst remove existing mongodb package\n\n```\nnpm uninstall mongodb\n// Or\nyarn remove mongodb\n```\n\nThen install again with version 3.\n\n```\nnpm install mongodb@3\n// Or\nyarn add mongodb@3\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable, HttpException, HttpStatus } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { MongoRepository } from 'typeorm';\nimport { validate } from 'class-validator';\nimport { CreateUserDto } from './user.dto';\nimport { User } from '../model/user.entity';\nimport { UserRO } from './user.interface';\n\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(User)\n private readonly userRepository: MongoRepository<User>,\n ) {}\n\n // abstracting access to the model via service\n public async getAll() {\n // getting data from database\n return await this.userRepository.find();\n }\n\n // abstracting access to the model via service\n public async get(id: string) {\n const user = await this.userRepository.findOne({ _id: id });\n if (!user) {\n const errors = { User: ' not found' };\n throw new HttpException({ errors }, 401);\n }\n\n return this.buildUserRO(user);\n }\n\n\n\n async create(dto: CreateUserDto): Promise<UserRO> {\n // check uniqueness of username/email\n const { username } = dto;\n const newUser = new User();\n newUser.username = username;\n // newUser.contexts = [];\n\n const errors = await validate(newUser);\n if (errors.length > 0) {\n const _errors = { username: 'Userinput is not valid.' };\n throw new HttpException(\n { message: 'Input data validation failed', _errors },\n HttpStatus.BAD_REQUEST,\n );\n } else {\n const savedUser = await this.userRepository.save(newUser);\n return this.buildUserRO(savedUser);\n }\n }\n\n\n}\n```\n\n```text\nexport interface UserData {\n username: string;\n _id: string;\n}\n\n// user response object\nexport interface UserRO {\n user: UserData;\n}\n```\n\n```text\n@Get(':id')\n findOne(@Param('id') id: string): Promise<UserRO> {\n console.log(`getting user with id: ${id}`);\n const user = this.serv.get(id);\n return user;\n }\n```\n\n```text\n@Entity({ name: 'User' })\nexport class User {\n @ObjectIdColumn()\n _id: string;\n\n @Column({ type: 'varchar', length: 50 })\n username: string;\n\n @OneToMany((type) => Context, (context) => context.user)\n contexts: Context[];\n}\n```\n\n```text\n[Nest] 75671 - 09/22/2021, 9:22:18 PM ERROR [ExceptionsHandler] Cannot read property 'prototype' of undefined\nTypeError: Cannot read property 'prototype' of undefined\n at FindCursor.cursor.toArray (/Users/deemeetree/Documents/Root/benchmark-sql-graph/src/entity-manager/MongoEntityManager.ts:707:37)\n at MongoEntityManager.<anonymous> (/Users/deemeetree/Documents/Root/benchmark-sql-graph/src/entity-manager/MongoEntityManager.ts:190:46)\n at step (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:143:27)\n at Object.next (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:124:57)\n at fulfilled (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:114:62)\n at processTicksAndRejections (internal/process/task_queues.js:97:5)\n```\n\n```text\ncreate()\n```\n\n```text\nUser\n```\n\n```text\nfind({id})\n```\n\n```text\nfindAll()\n```\n\n```text\nuser.service.ts\n```\n\n```text\nuser.interface.ts\n```\n\n```text\nuser.controller.ts\n```\n\n```text\nmodel/user.entity.ts\n```\n\n```text\nnpm uninstall mongodb\n// Or\nyarn remove mongodb\n```\n\n```text\nnpm install mongodb@3\n// Or\nyarn add mongodb@3\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.703Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":302,"estimatedTokens":1909}}266{"id":"stack-63716756","source":"stackoverflow","questionId":63716756,"title":"TypeORM: How to partialy update given entity with query runner?","tags":["typescript","nestjs","typeorm"],"text":"Title: TypeORM: How to partialy update given entity with query runner?\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIf I want to partially update my user's name I can easily do this:\n\n```\nawait this.repository.save({ id: 1, name: 'john' });\n```\n\nBut when I do it with queryrunner, It requires all field to exist and throws `missing following properties from type 'User'`\n\n```\nawait queryRunner.manager.save({ id: 1, name: 'john' }); // Error: Missing property\n```\n\n========================================\n\nCode:\n```js\nawait this.repository.save({ id: 1, name: 'john' });\n```\n\n```js\nawait queryRunner.manager.save({ id: 1, name: 'john' }); // Error: Missing property\n```\n\n```text\nmissing following properties from type 'User'\n```\n\n```js\nawait queryRunner.manager.update(User, 1, { name: \"john\" });\n```\n\n```text\nsave\n```\n\n```text\ninsert\n```\n\n========================================\n\nComments:\n- @omidh referenced from github.com/typeorm/typeorm/issues/3772, I can not believe `missing following properties from type 'User'` is occured in `update` operation.Can u show sql transformed? And I think use `save` is a bad idea for `update`, because typeorm always check the correspond record whether exist and then do `update` or `insert`, that is costed.","metadata":{"transformedAt":"2026-08-18T18:33:44.704Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":48,"estimatedTokens":319}}267{"id":"stack-67212239","source":"stackoverflow","questionId":67212239,"title":"TypeORM: update entity column with relation (@joinColumn) via Repository","tags":["node.js","typescript","postgresql","nestjs","typeorm"],"text":"Title: TypeORM: update entity column with relation (@joinColumn) via Repository\nTags: node.js, typescript, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have the following entities:\n\n```\n@Entity({ name: 'user' })\nexport class UserEntity extends BasicEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({\n nullable: false,\n unique: true,\n })\n login: string;\n}\n```\n\n```\n@Entity({ name: 'wallet' })\nexport class WalletEntity extends BasicEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(() => UserEntity)\n @JoinColumn({ name: 'user_id' })\n user: UserEntity;\n\n @Column({\n name: 'address',\n type: 'text',\n })\n address: string;\n}\n```\n\nSo, the wallet table is looks like this:\n\n```\n-------------------------\n id | user_id | address\n-------------------------\n 1 | 1 | 0x12 \n-------------------------\n 2 | 43 | 0x10\n```\n\nAnd I like to update the `wallet` entity via Repository api. But the problem is, that I can't just:\n\n```\nWalletRepository.save({ address: '0x12', userId: 2 })\n```\n\nBecause Typescript give me an error, that `userId` should be `userEntity`, but not number. But I want to update a relation column. So is there any option to update it?\n\n========================================\n\nCode:\n```text\n@Entity({ name: 'user' })\nexport class UserEntity extends BasicEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({\n nullable: false,\n unique: true,\n })\n login: string;\n}\n```\n\n```text\n@Entity({ name: 'wallet' })\nexport class WalletEntity extends BasicEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(() => UserEntity)\n @JoinColumn({ name: 'user_id' })\n user: UserEntity;\n\n @Column({\n name: 'address',\n type: 'text',\n })\n address: string;\n}\n```\n\n```text\n-------------------------\n id | user_id | address\n-------------------------\n 1 | 1 | 0x12 \n-------------------------\n 2 | 43 | 0x10\n```\n\n```text\nWalletRepository.save({ address: '0x12', userId: 2 })\n```\n\n```text\nwallet\n```\n\n```text\nuserId\n```\n\n```text\nuserEntity\n```\n\n```text\n@Entity({ name: 'wallet' })\nexport class WalletEntity extends BasicEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(() => UserEntity, (entity: UserEntity) => entity.id)\n @JoinColumn({ name: 'user_id' })\n user: UserEntity;\n\n @Column({ name: 'user_id', type: 'int' })\n userId: number;\n\n @Column({\n name: 'address',\n type: 'text',\n })\n address: string;\n}\n```\n\n```text\n{name: user_id}\n```\n\n```text\nuserID\n```\n\n```text\njoin\n```\n\n```text\nrelations[]\n```\n\n```text\nuser\n```\n\n========================================\n\nComments:\n- Thank you for posting your findings, could find very little docs on this\n- I think you also need make sure `userId` field can be set to null right? since there will be only one `user_id` field in db, from the many to one relation, a wallet can have user as null, but with the manually defined `userId` field in WalletEntity it insist that user should not be null","metadata":{"transformedAt":"2026-08-18T18:33:44.704Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":164,"estimatedTokens":737}}268{"id":"stack-62990134","source":"stackoverflow","questionId":62990134,"title":"Nestjs, How to get entity table name?","tags":["node.js","nestjs","typeorm"],"text":"Title: Nestjs, How to get entity table name?\nTags: node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHow to get entity table name ? (ex: member-pre-sale-detail)\nI want to set table comment\n\n```\n// Seeder: Clear & set Comment\nexport default class ClearAllSeed implements Seeder {\n public async run(factory: Factory, connection: Connection): Promise {\n\n const deleteEntities = [\n {table: OrderHead, comment: '訂單/主表'},\n ]\n\n for(const entity of deleteEntities){\n await connection\n .createQueryBuilder()\n .delete()\n .from(entity.table)\n .execute();\n\n await connection\n // >>>> but table name is MemberPreSaleDetail not member-pre-sale-detail\n .query(`alter table ${entity.table.name} comment '${entity.comment}'`);\n }\n }\n}\n\n// Sampel Entity\n@Entity('member-pre-sale-detail')\nexport class MemberPreSaleDetail {\n @PrimaryGeneratedColumn({unsigned: true})\n id?: number;\n\n @Column({comment: '幾批(整批)', type: 'mediumint', default: 0})\n batchQty: number;\n}\n```\n\n### Expected behavior\n\nget the 'member-pre-sale-detail' string\n\n### Environment\n\nNest version: 7.0.7\n \nFor Tooling issues:\n- Node version: v14.5.0\n- Platform: Mac\n\n========================================\n\nTop Answer:\nyou got to easy way\n\n`getManager().getRepository(User).metadata.tableName`\n\nOR\n\nextends the User class with the BaseEntity from typeorm and do\n\n`user.getRepository().metadata.tableName`\n\n========================================\n\nCode:\n```text\n// Seeder: Clear & set Comment\nexport default class ClearAllSeed implements Seeder {\n public async run(factory: Factory, connection: Connection): Promise<void> {\n\n\n const deleteEntities = [\n {table: OrderHead, comment: '訂單/主表'},\n ]\n\n for(const entity of deleteEntities){\n await connection\n .createQueryBuilder()\n .delete()\n .from(entity.table)\n .execute();\n\n await connection\n // >>>> but table name is MemberPreSaleDetail not member-pre-sale-detail\n .query(`alter table ${entity.table.name} comment '${entity.comment}'`);\n }\n }\n}\n\n// Sampel Entity\n@Entity('member-pre-sale-detail')\nexport class MemberPreSaleDetail {\n @PrimaryGeneratedColumn({unsigned: true})\n id?: number;\n\n @Column({comment: '幾批(整批)', type: 'mediumint', default: 0})\n batchQty: number;\n}\n```\n\n```text\nconnection.getMetadata(MemberPreSaleDetail)\n```\n\n```text\nname\n```\n\n```text\ntableName\n```\n\n```text\ngivenTableName\n```\n\n```text\ngivenTableName\n```\n\n```text\ngetManager().getRepository(User).metadata.tableName\n```\n\n```text\nuser.getRepository().metadata.tableName\n```\n\n========================================\n\nComments:\n- hmm I am not sure how this `@Entity` decorator works but I think that you can try sth like this :`entity.constructor.name`","metadata":{"transformedAt":"2026-08-18T18:33:44.704Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":137,"estimatedTokens":698}}269{"id":"stack-70521273","source":"stackoverflow","questionId":70521273,"title":"How to unit test a custom repository of TypeORM in NestJS?","tags":["typescript","unit-testing","jestjs","nestjs","typeorm"],"text":"Title: How to unit test a custom repository of TypeORM in NestJS?\nTags: typescript, unit-testing, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\n### Class to test\n\nMy TypeORM repository `extends` AbstractRepository:\n\n```\n@EntityRepository(User)\nexport class UsersRepository extends AbstractRepository {\n\n async findByEmail(email: string): Promise {\n return await this.repository.findOne({ email })\n }\n}\n```\n\n### Unit test\n\n```\ndescribe('UsersRepository', () => {\n let usersRepository: UsersRepository\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [UsersRepository]\n }).compile()\n\n usersRepository = module.get(UsersRepository)\n })\n\n describe('findByEmail', () => {\n it(`should return the user when the user exists in database.`, async () => {\n const fetchedUser = await usersRepository.findByEmail('test1@test.com')\n })\n })\n})\n```\n\nHere, I get the error:\n\n```\nTypeError: Cannot read property 'getRepository' of undefined\n\n at UsersRepository.get (repository/AbstractRepository.ts:43:29)\n at UsersRepository.findByEmail (users/users.repository.ts:11:23)\n at Object. (users/users.repository.spec.ts:55:49)\n```\n\nSo, my question is, how do I mock the `repository` or `repository.findOne`?\n\nIn other words, how do I mock the fields that are inherited from the `AbstractRepository` which are `protected` and cannot be accessed from `UsersRepository` instance?\n\nThere is a similar question here but it is for extending from `Repository` instead of `AbstractRepository`. They are able to mock `findOne` because it's `public`.\n\n### What I tried\n\nI tried to mock it in a NestJS recommended way, but this is for non-custom repositories and doesn't work in my case:\n\n```\n{\n provide: getRepositoryToken(User),\n useValue: {\n findOne: jest.fn().mockResolvedValue(new User())\n }\n}\n```\n\n========================================\n\nTop Answer:\nAlthough your solution works, it causes repetition of db initialization code in all the repositories. I'd like to propose an alternate solution that works for me.\n\n**Step 1. Create a global configuration file `jest.config.ts` in your project root folder.**\n\n```\n// project-root/jest.config.ts\n\nimport type { Config } from '@jest/types';\n\nconst config: Config.InitialOptions = {\n moduleFileExtensions: ['js', 'json', 'ts'],\n rootDir: 'src',\n testRegex: '.*\\\\.spec\\\\.ts$',\n testEnvironment: 'node',\n preset: 'ts-jest',\n setupFilesAfterEnv: ['/jest.setup.ts'], // [!code focus]\n};\n\nexport default config;\n```\n\n**Step 2. create global setup file `src/jest.setup.ts` that contains global initialization code.**\n\n```\n// src/jest.setup.ts\n\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nexport const testDbConfig: TypeOrmModuleOptions = {\n type: 'sqlite',\n database: ':memory:',\n dropSchema: true,\n synchronize: true,\n autoLoadEntities: true,\n};\n\n// assign the testDbConfig to a global variable\nglobal.testDbConfig = testDbConfig;\n```\n\n**Step 3: Create your repositories and inject the entity manager into the constructor.**\n\n```\nimport { EntityManager, Repository } from 'typeorm';\nimport { User } from './entities/user.entity';\n\nexport class UserRepository extends Repository {\n constructor(private readonly entityManager: EntityManager) {\n super(Movie, entityManager);\n }\n\n // my custom method that I need to unit test\n async findByEmail(title: string): Promise {\n return this.findOne({ where: { email } });\n }\n}\n```\n\n**Step 4. Unit test your repositories by making entries into the in-memory database via the `entityManager` and then try reading the entries with your custom repository methods.**\n\n```\ndescribe('UsersRepository', () => {\n let usersRepository: UsersRepository;\n let entityManager: EntityManager;\n\n beforeAll(async () => {\n const module: TestingModule = await Test.createTestingModule({\n imports: [TypeOrmModule.forRoot(global.testDbConfig), TypeOrmModule.forFeature([User])],\n providers: [\n {\n provide: UsersRepository,\n useFactory: (entityManager: EntityManager) => new UsersRepository(entityManager),\n inject: [EntityManager],\n },\n ],\n }).compile();\n\n const repositoryToken = getRepositoryToken(UsersRepository);\n usersRepository = module.get(repositoryToken);\n entityManager = module.get(EntityManager);\n });\n\n // clear the user table to avoid clash with other test cases\n beforeEach(async () => {\n await entityManager.clear(User);\n });\n\n it('Should find the user by his email-id correctly', async () => {\n const testUser = new User();\n testUser.email = \"johndoe@example.com\"\n\n await entityManager.save(User, testUser);\n\n const fetchedUser = await usersRepository.findByEmail(testUser.email);\n expect(fetchedUser).toBeDefined();\n expect(fetchedUser.email).toEqual(testUser.email)\n });\n})\n```\n\nOnce complete, just run the test suite. That's all!\n\n========================================\n\nCode:\n```text\n@EntityRepository(User)\nexport class UsersRepository extends AbstractRepository<User> {\n\n async findByEmail(email: string): Promise<User> {\n return await this.repository.findOne({ email })\n }\n}\n```\n\n```text\ndescribe('UsersRepository', () => {\n let usersRepository: UsersRepository\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [UsersRepository]\n }).compile()\n\n usersRepository = module.get<UsersRepository>(UsersRepository)\n })\n\n describe('findByEmail', () => {\n it(`should return the user when the user exists in database.`, async () => {\n const fetchedUser = await usersRepository.findByEmail('test1@test.com')\n })\n })\n})\n```\n\n```text\nTypeError: Cannot read property 'getRepository' of undefined\n\n at UsersRepository.get (repository/AbstractRepository.ts:43:29)\n at UsersRepository.findByEmail (users/users.repository.ts:11:23)\n at Object.<anonymous> (users/users.repository.spec.ts:55:49)\n```\n\n```text\n{\n provide: getRepositoryToken(User),\n useValue: {\n findOne: jest.fn().mockResolvedValue(new User())\n }\n}\n```\n\n```text\nextends\n```\n\n```text\nrepository\n```\n\n```text\nrepository.findOne\n```\n\n```text\nAbstractRepository\n```\n\n```text\nprotected\n```\n\n```text\nUsersRepository\n```\n\n```text\nRepository<Entity>\n```\n\n```text\nAbstractRepository<Entity>\n```\n\n```text\nfindOne\n```\n\n```text\npublic\n```\n\n```text\nconst testConnection = 'testConnection'\n\ndescribe('UsersRepository', () => {\n let usersRepository: UsersRepository\n\n beforeEach(async () => {\n const connection = await createConnection({\n type: 'sqlite',\n database: ':memory:',\n dropSchema: true,\n entities: [User],\n synchronize: true,\n logging: false,\n name: testConnection\n })\n\n usersRepository = connection.getCustomRepository(UsersRepository)\n })\n\n afterEach(async () => {\n await getConnection(testConnection).close()\n })\n\n describe('findByEmail', () => {\n it(`should return the user when the user exists in database.`, async () => {\n await usersRepository.createAndSave(testUser)\n const fetchedUser = await usersRepository.findByEmail(testUser.email)\n expect(fetchedUser.email).toEqual(testUser.email)\n })\n })\n})\n```\n\n```js\n// project-root/jest.config.ts\n\nimport type { Config } from '@jest/types';\n\nconst config: Config.InitialOptions = {\n moduleFileExtensions: ['js', 'json', 'ts'],\n rootDir: 'src',\n testRegex: '.*\\\\.spec\\\\.ts$',\n testEnvironment: 'node',\n preset: 'ts-jest',\n setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'], // [!code focus]\n};\n\nexport default config;\n```\n\n```js\n// src/jest.setup.ts\n\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\nexport const testDbConfig: TypeOrmModuleOptions = {\n type: 'sqlite',\n database: ':memory:',\n dropSchema: true,\n synchronize: true,\n autoLoadEntities: true,\n};\n\n// assign the testDbConfig to a global variable\nglobal.testDbConfig = testDbConfig;\n```\n\n```js\nimport { EntityManager, Repository } from 'typeorm';\nimport { User } from './entities/user.entity';\n\nexport class UserRepository extends Repository<User> {\n constructor(private readonly entityManager: EntityManager) {\n super(Movie, entityManager);\n }\n\n\n // my custom method that I need to unit test\n async findByEmail(title: string): Promise<User | undefined> {\n return this.findOne({ where: { email } });\n }\n}\n```\n\n```js\ndescribe('UsersRepository', () => {\n let usersRepository: UsersRepository;\n let entityManager: EntityManager;\n\n beforeAll(async () => {\n const module: TestingModule = await Test.createTestingModule({\n imports: [TypeOrmModule.forRoot(global.testDbConfig), TypeOrmModule.forFeature([User])],\n providers: [\n {\n provide: UsersRepository,\n useFactory: (entityManager: EntityManager) => new UsersRepository(entityManager),\n inject: [EntityManager],\n },\n ],\n }).compile();\n\n const repositoryToken = getRepositoryToken(UsersRepository);\n usersRepository = module.get<UsersRepository>(repositoryToken);\n entityManager = module.get<EntityManager>(EntityManager);\n });\n\n // clear the user table to avoid clash with other test cases\n beforeEach(async () => {\n await entityManager.clear(User);\n });\n\n it('Should find the user by his email-id correctly', async () => {\n const testUser = new User();\n testUser.email = \"johndoe@example.com\"\n\n await entityManager.save(User, testUser);\n\n const fetchedUser = await usersRepository.findByEmail(testUser.email);\n expect(fetchedUser).toBeDefined();\n expect(fetchedUser.email).toEqual(testUser.email)\n });\n})\n```\n\n```text\njest.config.ts\n```\n\n```text\nsrc/jest.setup.ts\n```\n\n```text\nentityManager\n```\n\n========================================\n\nComments:\n- Does it fit to the column type you declare for the entity? i am asking since i am using also postgres and one of the column is json type, also i have enum's\n- @MatanTubul, if you are using the TypeORM over the postgres, it should work although I haven't tested it. TypeORM queries eventually get converted to postgres or SQLite queries behind the scenes, depending on the database.","metadata":{"transformedAt":"2026-08-18T18:33:44.704Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":407,"estimatedTokens":2497}}270{"id":"stack-54507039","source":"stackoverflow","questionId":54507039,"title":"DRY principles in NestJS entities with typeorm and class-validator","tags":["nestjs","typeorm"],"text":"Title: DRY principles in NestJS entities with typeorm and class-validator\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIs there a way to turn this code \n\n```\nexport class person {\n @IsString()\n @Column('text')\n name: string\n\n @IsOptional()\n @IsString()\n @Column('text')\n description?: string\n}\n```\n\nInto something that resembles this\n\n```\nexport class person {\n name: string\n description?: string\n}\n```\n\nI'm aware that decorators are needed, but SSOT seems lost when property type has to be declared three times or more per property.\n\nIs there an easier way around this? JOI? Schema generation?\n\n========================================\n\nCode:\n```text\nexport class person {\n @IsString()\n @Column('text')\n name: string\n\n @IsOptional()\n @IsString()\n @Column('text')\n description?: string\n}\n```\n\n```text\nexport class person {\n name: string\n description?: string\n}\n```\n\n```js\nconst CombinedDecorator = (target, property, descriptor) => {\n IsOptional(target, property, descriptor);\n IsString(target, property, descriptor);\n Column('text')(target, property, descriptor);\n}\n\nclass Person {\n @CombinedDecorator()\n name: string;\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.704Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":68,"estimatedTokens":289}}271{"id":"stack-67070712","source":"stackoverflow","questionId":67070712,"title":"Serverless-webpack not including `pg` package","tags":["node.js","typescript","webpack","typeorm","serverless"],"text":"Title: Serverless-webpack not including `pg` package\nTags: node.js, typescript, webpack, typeorm, serverless\nSource: Stack Overflow\n\nQuestion:\nI'm trying to modify a code generated from `aws-nodejs-typescript` template. I've installed `typeorm`, `reflect-metadata` and `pg` to work with PostgreSQL.\n\nThey are in `dependencies` in `package.json`\nhttps://i.sstatic.net/bhVWe.png\n\nThe webpack config is the default one\n\n```\nconst path = require('path');\nconst slsw = require('serverless-webpack');\nconst nodeExternals = require('webpack-node-externals');\nconst TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');\n\n/*\nThis line is only required if you are specifying `TS_NODE_PROJECT` for whatever reason.\n */\n// delete process.env.TS_NODE_PROJECT;\n\nmodule.exports = {\n context: __dirname,\n mode: slsw.lib.webpack.isLocal ? 'development' : 'production',\n entry: slsw.lib.entries,\n devtool: slsw.lib.webpack.isLocal ? 'eval-cheap-module-source-map' : 'source-map',\n resolve: {\n extensions: ['.mjs', '.json', '.ts'],\n symlinks: false,\n cacheWithContext: false,\n plugins: [\n new TsconfigPathsPlugin({\n configFile: './tsconfig.paths.json',\n }),\n ],\n },\n output: {\n libraryTarget: 'commonjs',\n path: path.join(__dirname, '.webpack'),\n filename: '[name].js',\n },\n optimization: {\n concatenateModules: false,\n },\n target: 'node',\n externals: [nodeExternals()],\n module: {\n rules: [\n // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`\n {\n test: /\\.(tsx?)$/,\n loader: 'ts-loader',\n exclude: [\n [\n path.resolve(__dirname, 'node_modules'),\n path.resolve(__dirname, '.serverless'),\n path.resolve(__dirname, '.webpack'),\n ],\n ],\n options: {\n transpileOnly: true,\n experimentalWatchApi: true,\n },\n },\n ],\n },\n plugins: [],\n};\n```\n\n**The problem:** after `sls deploy` the `zip` archive does not contain the `pg` package and hence requests fail as `Postgres package has not been found installed. Try to install it: npm install pg --save`. How do I fix this?\n\nI suspect this might be happening because of a dynamic dependency resolution or whatever as there is no direct dependency in my code and `typeorm` decides which driver to use based on string in connection configuration.\n\nP.S. `sls offline` works so the code should be correct and the problem is around this not included package to zip archive.\n\n========================================\n\nCode:\n```js\nconst path = require('path');\nconst slsw = require('serverless-webpack');\nconst nodeExternals = require('webpack-node-externals');\nconst TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');\n\n/*\nThis line is only required if you are specifying `TS_NODE_PROJECT` for whatever reason.\n */\n// delete process.env.TS_NODE_PROJECT;\n\nmodule.exports = {\n context: __dirname,\n mode: slsw.lib.webpack.isLocal ? 'development' : 'production',\n entry: slsw.lib.entries,\n devtool: slsw.lib.webpack.isLocal ? 'eval-cheap-module-source-map' : 'source-map',\n resolve: {\n extensions: ['.mjs', '.json', '.ts'],\n symlinks: false,\n cacheWithContext: false,\n plugins: [\n new TsconfigPathsPlugin({\n configFile: './tsconfig.paths.json',\n }),\n ],\n },\n output: {\n libraryTarget: 'commonjs',\n path: path.join(__dirname, '.webpack'),\n filename: '[name].js',\n },\n optimization: {\n concatenateModules: false,\n },\n target: 'node',\n externals: [nodeExternals()],\n module: {\n rules: [\n // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`\n {\n test: /\\.(tsx?)$/,\n loader: 'ts-loader',\n exclude: [\n [\n path.resolve(__dirname, 'node_modules'),\n path.resolve(__dirname, '.serverless'),\n path.resolve(__dirname, '.webpack'),\n ],\n ],\n options: {\n transpileOnly: true,\n experimentalWatchApi: true,\n },\n },\n ],\n },\n plugins: [],\n};\n```\n\n```text\naws-nodejs-typescript\n```\n\n```text\ntypeorm\n```\n\n```text\nreflect-metadata\n```\n\n```text\npg\n```\n\n```text\ndependencies\n```\n\n```text\npackage.json\n```\n\n```text\nsls deploy\n```\n\n```text\nzip\n```\n\n```text\npg\n```\n\n```text\nPostgres package has not been found installed. Try to install it: npm install pg --save\n```\n\n```text\ntypeorm\n```\n\n```text\nsls offline\n```\n\n```text\ncustom:\n webpack:\n includeModules:\n forceInclude:\n - pg\n```\n\n========================================\n\nComments:\n- I already have `includeModules: true` how do I extend it?\n- Tried this code as is. Seems to be working and not including Node's packages which is exactly what I wanted. Thanks!\n- Yes it's working fine.. Thanks. & For typescript project you need to write `custom: {webpack: {webpackConfig: './webpack.config.js',includeModules:{ forceInclude: [\"pg\"] }},}`","metadata":{"transformedAt":"2026-08-18T18:33:44.704Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":203,"estimatedTokens":1189}}272{"id":"stack-72879395","source":"stackoverflow","questionId":72879395,"title":"TypeORM @JoinTable() how to specify custom join columns?","tags":["typeorm"],"text":"Title: TypeORM @JoinTable() how to specify custom join columns?\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nthis is my sample data model\n\nhttps://i.sstatic.net/9DyQy.png\n\nI have declared the following classes:\n\n```\n@Entity({\n name: 'user'\n})\nexport class User {\n @Column({ type: 'int4' })\n @PrimaryColumn()\n userid: number\n \n @Column({name: 'name', type: 'varchar', length: 30})\n name: string\n \n @Column({name: 'age', type: 'int2'})\n age: number\n \n @ManyToMany(() => Department, (department)=> department.users)\n @JoinTable({\n name: 'department_user'\n })\n departments: Department[]\n}\n\n@Entity({ name: 'department' })\nexport class Department {\n \n @Column({ type: 'int2' })\n @PrimaryColumn()\n departmentid: number\n \n @Column({type: 'varchar', length: 50})\n title: string\n \n @Column({type:'text'})\n notes: string\n \n @ManyToMany(() => User, (user)=> user.departments)\n @JoinTable({ name: 'department_user' })\n users: User[] \n}\n```\n\nwhenever I run the app, it creates the **departmentDepartmentId** & **userUserId** columns and not utilize the columns in the corresponding join table. How can I tell typeorm to only use the predefined join column in join table?\n\n### Update 2 (as mentioned by @suvantorw)\n\nI recreated the join table with the statement below:\n\n```\ncreate table department_user(\ndepartmentid integer not null, \nuserid integer not null);\n\nalter table department_user add constraint fk_dept_dept foreign key (departmentid) references department(departmentid);\nalter table department_user add constraint fk_dept_user foreign key (userid) references \"user\"(userid);\nalter table department_user add constraint pk_dept_user primary key (departmentid, userid);\n```\n\nand modified the entities like this:\n\n**user**\n\n```\n@ManyToMany(() => Department, (department)=> department.users)\n @JoinTable({ \n name: 'department_user',\n joinColumn: { name: 'userid' },\n inverseJoinColumn: { name: 'departmentid' }\n })\n departments: Department[]\n}\n```\n\n**department**\n\n```\n@ManyToMany(() => User, (user)=> user.departments)\n @JoinTable({\n name: 'department_user',\n joinColumn: { name: 'departmentid' },\n inverseJoinColumn: { referencedColumnName: 'userid' }\n })\n users: User[] \n}\n```\n\nit does run without errors but when it runs the table structure is modified to this\nhttps://i.sstatic.net/rSrQD.png\n\nAs you can see, ,y foreign key constraints are gone and new ones are created. Any clue what I'm doing wrong here?\n\n### Update 3\n\nFinally I modified the classes as below and now the TypeORM accepts the relationships and does not create its own. it was a very painful experience to solve this and documentation about this decorator doesn't say much either.\n\n**user**\n\n```\n@ManyToMany(() => Department, (department)=> department.users)\n @JoinTable({ \n name: 'department_user',\n joinColumn: {\n name: 'userid',\n foreignKeyConstraintName: 'fk_dept_user'\n },\n inverseJoinColumn: {\n referencedColumnName: 'departmentid',\n name: 'departmentid',\n foreignKeyConstraintName: 'fk_dept_dept'\n }\n })\n departments: Department[]\n}\n```\n\n**department**\n\n```\n@ManyToMany(() => User, (user)=> user.departments)\n @JoinTable({\n name: 'department_user',\n joinColumn: {\n name: 'departmentid',\n foreignKeyConstraintName: 'fk_dept_dept'\n },\n inverseJoinColumn: {\n referencedColumnName: 'userid',\n name: 'userid',\n foreignKeyConstraintName: 'fk_dept_user'\n }\n })\n users: User[] \n}\n```\n\n========================================\n\nCode:\n```js\n@Entity({\n name: 'user'\n})\nexport class User {\n @Column({ type: 'int4' })\n @PrimaryColumn()\n userid: number\n \n @Column({name: 'name', type: 'varchar', length: 30})\n name: string\n \n @Column({name: 'age', type: 'int2'})\n age: number\n \n @ManyToMany(() => Department, (department)=> department.users)\n @JoinTable({\n name: 'department_user'\n })\n departments: Department[]\n}\n\n@Entity({ name: 'department' })\nexport class Department {\n \n @Column({ type: 'int2' })\n @PrimaryColumn()\n departmentid: number\n \n @Column({type: 'varchar', length: 50})\n title: string\n \n @Column({type:'text'})\n notes: string\n \n @ManyToMany(() => User, (user)=> user.departments)\n @JoinTable({ name: 'department_user' })\n users: User[] \n}\n```\n\n```text\ncreate table department_user(\ndepartmentid integer not null, \nuserid integer not null);\n\nalter table department_user add constraint fk_dept_dept foreign key (departmentid) references department(departmentid);\nalter table department_user add constraint fk_dept_user foreign key (userid) references \"user\"(userid);\nalter table department_user add constraint pk_dept_user primary key (departmentid, userid);\n```\n\n```js\n@ManyToMany(() => Department, (department)=> department.users)\n @JoinTable({ \n name: 'department_user',\n joinColumn: { name: 'userid' },\n inverseJoinColumn: { name: 'departmentid' }\n })\n departments: Department[]\n}\n```\n\n```js\n@ManyToMany(() => User, (user)=> user.departments)\n @JoinTable({\n name: 'department_user',\n joinColumn: { name: 'departmentid' },\n inverseJoinColumn: { referencedColumnName: 'userid' }\n })\n users: User[] \n}\n```\n\n```js\n@ManyToMany(() => Department, (department)=> department.users)\n @JoinTable({ \n name: 'department_user',\n joinColumn: {\n name: 'userid',\n foreignKeyConstraintName: 'fk_dept_user'\n },\n inverseJoinColumn: {\n referencedColumnName: 'departmentid',\n name: 'departmentid',\n foreignKeyConstraintName: 'fk_dept_dept'\n }\n })\n departments: Department[]\n}\n```\n\n```js\n@ManyToMany(() => User, (user)=> user.departments)\n @JoinTable({\n name: 'department_user',\n joinColumn: {\n name: 'departmentid',\n foreignKeyConstraintName: 'fk_dept_dept'\n },\n inverseJoinColumn: {\n referencedColumnName: 'userid',\n name: 'userid',\n foreignKeyConstraintName: 'fk_dept_user'\n }\n })\n users: User[] \n}\n```\n\n```text\n@ManyToMany(() => Department, (department)=> department.users)\n@JoinTable({ \n name: 'department_user',\n joinColumn: { name: 'userid' },\n inverseJoinColumn: { name: 'departmentid' }\n})\ndepartments: Department[]\n```\n\n========================================\n\nComments:\n- I have updated my question with the changes as you suggested. Can you please have a look?\n- Update 2 looks good. I was actually unaware of the ability to set foreignKeyConstraintName in join relationships from your update 3 so thanks for posting that.","metadata":{"transformedAt":"2026-08-18T18:33:44.704Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":272,"estimatedTokens":1590}}273{"id":"stack-62904873","source":"stackoverflow","questionId":62904873,"title":"Search item in array at postgres using typeorm","tags":["node.js","postgresql","typescript","express","typeorm"],"text":"Title: Search item in array at postgres using typeorm\nTags: node.js, postgresql, typescript, express, typeorm\nSource: Stack Overflow\n\nQuestion:\n**Database**: postgres\n\n**ORM**: Typeorm\n\n**Framework**: express.js\n\nI have a Table in which one of the fields, named `projects` is an array of strings. The type is set to `\"varchar\"` in the migration and the de decorator is set to `\"simple-array\"`.\n\nIn my get route if I receive a query `?project=name_of_the_project` it should try to find the project in the simple-array.\n\nFor the search my get route is like this:\n\n```\nstudentsRouter.get(\"/\", async (request, response) => {\n const { project } = request.query;\n const studentRepository = getCustomRepository(StudentRepository);\n const students = project\n ? await studentRepository\n .createQueryBuilder(\"students\")\n .where(\":project = ANY (students.projects)\", { project: project })\n .getMany()\n : await studentRepository.find();\n // const students = await studentRepository.find();\n return response.json(students);\n});\n```\n\nThe problem is that I´m getting an error saying that the right side should be an array.\n\n```\n(node:38971) UnhandledPromiseRejectionWarning: QueryFailedError: op ANY/ALL (array) requires array on right side\n at new QueryFailedError (/Users/Wblech/Desktop/42_vaga/src/error/QueryFailedError.ts:9:9)\n at Query.callback (/Users/Wblech/Desktop/42_vaga/src/driver/postgres/PostgresQueryRunner.ts:178:30)\n at Query.handleError (/Users/Wblech/Desktop/42_vaga/node_modules/pg/lib/query.js:146:19)\n at Connection.connectedErrorMessageHandler (/Users/Wblech/Desktop/42_vaga/node_modules/pg/lib/client.js:233:17)\n at Connection.emit (events.js:200:13)\n at /Users/Wblech/Desktop/42_vaga/node_modules/pg/lib/connection.js:109:10\n at Parser.parse (/Users/Wblech/Desktop/42_vaga/node_modules/pg-protocol/src/parser.ts:102:9)\n at Socket. (/Users/Wblech/Desktop/42_vaga/node_modules/pg-protocol/src/index.ts:7:48)\n at Socket.emit (events.js:200:13)\n at addChunk (_stream_readable.js:294:12)\n(node:38971) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)\n(node:38971) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\nIt has to be an array of string in this field and I can´t use an foreignKey.\n\nPlease find bellow my migration and model related to this issue:\n\n**Migration**:\n\n```\nimport { MigrationInterface, QueryRunner, Table } from \"typeorm\";\n\nexport class CreateStudents1594744103410 implements MigrationInterface {\n public async up(queryRunner: QueryRunner): Promise {\n await queryRunner.createTable(\n new Table({\n name: \"students\",\n columns: [\n {\n name: \"id\",\n type: \"uuid\",\n isPrimary: true,\n generationStrategy: \"uuid\",\n default: \"uuid_generate_v4()\",\n },\n {\n name: \"name\",\n type: \"varchar\",\n },\n {\n name: \"intra_id\",\n type: \"varchar\",\n isUnique: true,\n },\n {\n name: \"projects\",\n type: \"varchar\",\n isNullable: true,\n },\n ],\n })\n );\n }\n\n public async down(queryRunner: QueryRunner): Promise {\n await queryRunner.dropTable(\"students\");\n }\n}\n```\n\n**Model**:\n\n```\nimport { Entity, Column, PrimaryGeneratedColumn } from \"typeorm\";\n\n@Entity(\"students\")\nclass Student {\n @PrimaryGeneratedColumn(\"uuid\")\n id: string;\n\n @Column()\n name: string;\n\n @Column()\n intra_id: string;\n\n @Column(\"simple-array\")\n projects: string[];\n}\n\nexport default Student;\n```\n\n**EDIT - 01**\n\nIn the docs I found out that the `simple-array` stores the strings separated by a comma. I thing this means it is a string with words separated by a comma. In this case is there a way to find the which row has the string in the projects field?\n\nLink - https://gitee.com/mirrors/TypeORM/blob/master/docs/entities.md#column-types-for-postgres\n\n**Edit 02**\n\nThe field projects stores the projects that the students are doing, so the database returns this json:\n\n```\n{\n \"id\": \"e586d1d8-ec03-4d29-a823-375068de23aa\",\n \"name\": \"First Lastname\",\n \"intra_id\": \"flastname\",\n \"projects\": [\n \"42cursus_libft\",\n \"42cursus_get-next-line\",\n \"42cursus_ft-printf\"\n ]\n },\n```\n\n========================================\n\nCode:\n```text\nstudentsRouter.get(\"/\", async (request, response) => {\n const { project } = request.query;\n const studentRepository = getCustomRepository(StudentRepository);\n const students = project\n ? await studentRepository\n .createQueryBuilder(\"students\")\n .where(\":project = ANY (students.projects)\", { project: project })\n .getMany()\n : await studentRepository.find();\n // const students = await studentRepository.find();\n return response.json(students);\n});\n```\n\n```text\n(node:38971) UnhandledPromiseRejectionWarning: QueryFailedError: op ANY/ALL (array) requires array on right side\n at new QueryFailedError (/Users/Wblech/Desktop/42_vaga/src/error/QueryFailedError.ts:9:9)\n at Query.callback (/Users/Wblech/Desktop/42_vaga/src/driver/postgres/PostgresQueryRunner.ts:178:30)\n at Query.handleError (/Users/Wblech/Desktop/42_vaga/node_modules/pg/lib/query.js:146:19)\n at Connection.connectedErrorMessageHandler (/Users/Wblech/Desktop/42_vaga/node_modules/pg/lib/client.js:233:17)\n at Connection.emit (events.js:200:13)\n at /Users/Wblech/Desktop/42_vaga/node_modules/pg/lib/connection.js:109:10\n at Parser.parse (/Users/Wblech/Desktop/42_vaga/node_modules/pg-protocol/src/parser.ts:102:9)\n at Socket.<anonymous> (/Users/Wblech/Desktop/42_vaga/node_modules/pg-protocol/src/index.ts:7:48)\n at Socket.emit (events.js:200:13)\n at addChunk (_stream_readable.js:294:12)\n(node:38971) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)\n(node:38971) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n```text\nimport { MigrationInterface, QueryRunner, Table } from \"typeorm\";\n\nexport class CreateStudents1594744103410 implements MigrationInterface {\n public async up(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.createTable(\n new Table({\n name: \"students\",\n columns: [\n {\n name: \"id\",\n type: \"uuid\",\n isPrimary: true,\n generationStrategy: \"uuid\",\n default: \"uuid_generate_v4()\",\n },\n {\n name: \"name\",\n type: \"varchar\",\n },\n {\n name: \"intra_id\",\n type: \"varchar\",\n isUnique: true,\n },\n {\n name: \"projects\",\n type: \"varchar\",\n isNullable: true,\n },\n ],\n })\n );\n }\n\n public async down(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.dropTable(\"students\");\n }\n}\n```\n\n```text\nimport { Entity, Column, PrimaryGeneratedColumn } from \"typeorm\";\n\n@Entity(\"students\")\nclass Student {\n @PrimaryGeneratedColumn(\"uuid\")\n id: string;\n\n @Column()\n name: string;\n\n @Column()\n intra_id: string;\n\n @Column(\"simple-array\")\n projects: string[];\n}\n\nexport default Student;\n```\n\n```text\n{\n \"id\": \"e586d1d8-ec03-4d29-a823-375068de23aa\",\n \"name\": \"First Lastname\",\n \"intra_id\": \"flastname\",\n \"projects\": [\n \"42cursus_libft\",\n \"42cursus_get-next-line\",\n \"42cursus_ft-printf\"\n ]\n },\n```\n\n```text\nprojects\n```\n\n```text\n\"varchar\"\n```\n\n```text\n\"simple-array\"\n```\n\n```text\n?project=name_of_the_project\n```\n\n```text\nsimple-array\n```\n\n```text\n.where(\":project = ANY ( string_to_array(students.projects, ','))\", { project: project })\n```\n\n```text\nprojects\n```\n\n```text\nstudents.projects\n```\n\n```text\nstring_to_array()\n```\n\n```text\nwhere\n```\n\n========================================\n\nComments:\n- It looks like column `projects` should have datatype `varchar[]` (or `text[]`) rather than just `varchar`.\n- @GMB , I tryied this and I got the same error.\n- What is actually stored in `projects`? Can you provide a sample?\n- Can you query the database directly? What your ORM is producing is not helpful because it is formatted. There is a function you can try: `.where(\":project = ANY ( string_to_array(students.projects, ','))\", { project: project })` You may need to adjust the delimiter to what the ORM is using.\n- @MikeOrganek , it worked! Please give an answer so I can check.\n- Thank you! Good luck with the rest of your project!","metadata":{"transformedAt":"2026-08-18T18:33:44.704Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":301,"estimatedTokens":2268}}274{"id":"stack-56924509","source":"stackoverflow","questionId":56924509,"title":"TypeORM generates an empty migration","tags":["node.js","json","typescript","typeorm"],"text":"Title: TypeORM generates an empty migration\nTags: node.js, json, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nWhenever I run `typeorm migration:generate -n NAME`, all I get is an error stating I that no changes to the database were made. Whenever I run `typeorm migration:create -n NAME`, I get an empty migration file. All of my entities are in the folder specified in the `ormconfig.json` file, and are in the .ts format. When running a migration:generate command, I get an error that is related to the syntax in my entities (specifically where I have my imports on top of the file).\n\nThis is my `ormconfig.json`:\n\n```\n{\n \"name\": \"default\",\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"admin\",\n \"database\": \"classmarker\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"src/entity/*.ts\"\n ],\n \"subscribers\": [\n \"src/subscriber/*.ts\"\n ],\n \"migrations\": [\n \"src/migration/*.ts\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\nMy package.json contains the following packages:\n\n```\n\"dependencies\": {\n \"@tsed/common\": \"^5.21.0\",\n \"@tsed/core\": \"^5.21.0\",\n \"@tsed/di\": \"^5.21.0\",\n \"@types/mssql\": \"^4.0.15\",\n \"@types/node\": \"^12.0.12\",\n \"body-parser\": \"^1.19.0\",\n \"compression\": \"^1.7.4\",\n \"concurrently\": \"^4.1.1\",\n \"cookie-parser\": \"^1.4.4\",\n \"cors\": \"^2.8.5\",\n \"express\": \"^4.17.1\",\n \"express-handlebars\": \"^3.1.0\",\n \"method-override\": \"^3.0.0\",\n \"reflect-metadata\": \"^0.1.12\",\n \"pg\": \"^7.11.0\",\n \"typeorm\": \"^0.2.15\"\n },\n \"devDependencies\": {\n \"@types/express\": \"^4.17.0\",\n \"@types/node\": \"^9.6.5\",\n \"dotenv\": \"^8.0.0\",\n \"nodemon\": \"^1.19.1\",\n \"ts-node\": \"^3.3.0\",\n \"typescript\": \"^3.3.3333\"\n }\n```\n\nAnd my `tsconfig.json` looks like this:\n\n```\n{\n \"version\": \"2.4.2\",\n \"compilerOptions\": {\n \"lib\": [\"es5\", \"es6\"],\n \"target\": \"es6\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"sourceMap\": true\n },\n \"exclude\": [\n \"node_modules\"\n ]\n}\n```\n\nThe error I get when running `typeorm migration:generate -n Name`:\n\n```\nSyntaxError: Unexpected token import\n at createScript (vm.js:80:10)\n at Object.runInThisContext (vm.js:139:10)\n at Module._compile (module.js:616:28)\n at Object.Module._extensions..js (module.js:663:10)\n at Module.load (module.js:565:32)\n at tryModuleLoad (module.js:505:12)\n at Function.Module._load (module.js:497:3)\n at Module.require (module.js:596:17)\n at require (internal/module.js:11:18)\n at Function.PlatformTools.load (%AppData%\\nvm\\v8.11.2\\node_modules\\typeorm\\platform\\PlatformTools.js:107:28\n```\n\n========================================\n\nCode:\n```text\n{\n \"name\": \"default\",\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"postgres\",\n \"password\": \"admin\",\n \"database\": \"classmarker\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"src/entity/*.ts\"\n ],\n \"subscribers\": [\n \"src/subscriber/*.ts\"\n ],\n \"migrations\": [\n \"src/migration/*.ts\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\n```text\n\"dependencies\": {\n \"@tsed/common\": \"^5.21.0\",\n \"@tsed/core\": \"^5.21.0\",\n \"@tsed/di\": \"^5.21.0\",\n \"@types/mssql\": \"^4.0.15\",\n \"@types/node\": \"^12.0.12\",\n \"body-parser\": \"^1.19.0\",\n \"compression\": \"^1.7.4\",\n \"concurrently\": \"^4.1.1\",\n \"cookie-parser\": \"^1.4.4\",\n \"cors\": \"^2.8.5\",\n \"express\": \"^4.17.1\",\n \"express-handlebars\": \"^3.1.0\",\n \"method-override\": \"^3.0.0\",\n \"reflect-metadata\": \"^0.1.12\",\n \"pg\": \"^7.11.0\",\n \"typeorm\": \"^0.2.15\"\n },\n \"devDependencies\": {\n \"@types/express\": \"^4.17.0\",\n \"@types/node\": \"^9.6.5\",\n \"dotenv\": \"^8.0.0\",\n \"nodemon\": \"^1.19.1\",\n \"ts-node\": \"^3.3.0\",\n \"typescript\": \"^3.3.3333\"\n }\n```\n\n```text\n{\n \"version\": \"2.4.2\",\n \"compilerOptions\": {\n \"lib\": [\"es5\", \"es6\"],\n \"target\": \"es6\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"sourceMap\": true\n },\n \"exclude\": [\n \"node_modules\"\n ]\n}\n```\n\n```text\nSyntaxError: Unexpected token import\n at createScript (vm.js:80:10)\n at Object.runInThisContext (vm.js:139:10)\n at Module._compile (module.js:616:28)\n at Object.Module._extensions..js (module.js:663:10)\n at Module.load (module.js:565:32)\n at tryModuleLoad (module.js:505:12)\n at Function.Module._load (module.js:497:3)\n at Module.require (module.js:596:17)\n at require (internal/module.js:11:18)\n at Function.PlatformTools.load (%AppData%\\nvm\\v8.11.2\\node_modules\\typeorm\\platform\\PlatformTools.js:107:28\n```\n\n```text\ntypeorm migration:generate -n NAME\n```\n\n```text\ntypeorm migration:create -n NAME\n```\n\n```text\normconfig.json\n```\n\n```text\normconfig.json\n```\n\n```text\ntsconfig.json\n```\n\n```text\ntypeorm migration:generate -n Name\n```\n\n```text\n\"add-migration\": \"ts-node ./node_modules/typeorm/cli.js migration:generate -n\",\n \"update-database\": \"ts-node ./node_modules/typeorm/cli.js migration:run\"\n```\n\n```text\nUnexpected token import\n```\n\n```text\nimport\n```\n\n```text\n.ts\n```\n\n```text\nts-node ./node_modules/typeorm/cli.js migration:generate -n NAME\n```\n\n```text\nts-node ./node_modules/typeorm/cli.js migration:run\n```\n\n```text\npackage.json\n```\n\n```text\nnpm run add-migration -n NAME\n```\n\n```text\nnpm run update-database\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.704Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":256,"estimatedTokens":1371}}275{"id":"stack-73696949","source":"stackoverflow","questionId":73696949,"title":"Why is TypeORM DataSource initialization seemingly setting my host to localhost instead of my public IP?","tags":["node.js","typescript","typeorm","google-cloud-sql","fastify"],"text":"Title: Why is TypeORM DataSource initialization seemingly setting my host to localhost instead of my public IP?\nTags: node.js, typescript, typeorm, google-cloud-sql, fastify\nSource: Stack Overflow\n\nQuestion:\nI'm not sure if this is possible, but I don't see why it wouldn't be, so I'm a little stumped. I've been trying to connect to a remote SQL DB hosted on google cloud through a locally running instance of my Node application, but it keeps failing with the given setup for my DB:\n\n```\n//dbConnectorPlugin.ts\n...\nimport typeormConfig from '../../ormconfig';\n\ndeclare module 'fastify' {\n interface FastifyInstance {\n psqlDB: {\n messages: Repository;\n users: Repository;\n };\n }\n}\n\nasync function dbConnector(fastify: FastifyInstance) {\n try {\n const AppDataSource = await new DataSource(typeormConfig).initialize(); \n fastify.decorate('psqlDB', {\n messages: AppDataSource.getRepository(messages),\n users: AppDataSource.getRepository(users),\n });\n } catch (e) {\n console.error(`Something went dreadfully wrong: ${e}`);\n }\n}\n\nexport default fp(dbConnector);\n```\n\nIt throws the error:\n\n```\nError [ERR_TLS_CERT_ALTNAME_INVALID]: Hostname/IP does not match certificate's altnames: Host: localhost. is not cert's CN: \n```\n\nWhere the typeOrmConfig variable in the dbConnector file holds the content:\n\n```\n//ormconfig.ts\n\nexport default {\n type: 'postgres',\n port: 5432,\n host: process.env.DB_HOST,\n username: process.env.DB_USER,\n password: process.env.DB_PASS,\n database: process.env.DB_NAME,\n logging: true,\n synchronize: false,\n ssl: { ...getSSLConfig() },\n entities: ['dist/src/modules/**/entity.js'],\n migrations: ['dist/src/migration/**/*.ts'],\n subscribers: ['src/subscriber/**/*.ts'],\n} as DataSourceOptions;\n\nfunction getSSLConfig() {\n if (process.env.SSL_CA && process.env.SSL_CERT && process.env.SSL_KEY) {\n return {\n sslmode: 'verify-full',\n ca: process.env.SSL_CA.replace(/\\\\n/g, '\\n'),\n cert: process.env.SSL_CERT.replace(/\\\\n/g, '\\n'),\n key: process.env.SSL_KEY.replace(/\\\\n/g, '\\n'),\n };\n }\n\n return {};\n}\n```\n\nWhere I'm currently storing the SSL details I got from GCloud in my .env file for the time being.\n\nAnd just for further context, a reduced version of my index file where I register my DB plugin is as follows:\n\n```\n//index.ts\n\nimport dbConnector from './plugins/PSQLDbConnector';\n\nconst server: FastifyInstance = fastify();\nconst port: number = parseInt(`${process.env.PORT}`, 10) || 8080;\n\nserver.register(dbConnector);\n\nserver.listen({ port: port }, (err, address) => {\n if (err) {\n console.error(err);\n process.exit(1);\n }\n console.log(`Server listening at ${address}`);\n});\n```\n\nI've read through various other postings but can't find any solution that applies to my issue here. Is there something that I should be doing revolving around TypeORM to alter the *Host*? Or could it be something related to Node itself? Just to try and deduce the issue, I've added 0.0.0.0/0 to my authorized networks on the google cloud side, but that's also done nothing. What am I missing?\n\n========================================\n\nTop Answer:\nThe error says that `host` param provided in `ormconfig.ts` fetched from the env variable `process.env.DB_HOST` doesn't match the CN against which the certificate is issued.\n\nCheck the domain name of the SSL cert either in the GCloud or if you have cert file with you, you can get the same using `openssl` (if you have it installed in your system).\n\nopenssl x509 -noout -subject -in server.pem\n\nMore examples here.\n\nMake sure that the CN that you get from above is pointing to the correct IP address of the database and in this case use this endpoint to connect to the database setting it in `process.env.DB_HOST`.\n\nIf the CN from the cert comes out to be a malformed domain like `locahost`, you need to generate a fresh certificate in the GCloud console. I'm not a GCloud expert but there should be an option to tell which hostname you want to generate the SSL cert for. You can specify the public address that you have or the FQDN url pointing to that ip address.\n\n========================================\n\nCode:\n```text\n//dbConnectorPlugin.ts\n...\nimport typeormConfig from '../../ormconfig';\n\ndeclare module 'fastify' {\n interface FastifyInstance {\n psqlDB: {\n messages: Repository<messages>;\n users: Repository<users>;\n };\n }\n}\n\nasync function dbConnector(fastify: FastifyInstance) {\n try {\n const AppDataSource = await new DataSource(typeormConfig).initialize(); \n fastify.decorate('psqlDB', {\n messages: AppDataSource.getRepository(messages),\n users: AppDataSource.getRepository(users),\n });\n } catch (e) {\n console.error(`Something went dreadfully wrong: ${e}`);\n }\n}\n\nexport default fp(dbConnector);\n```\n\n```text\nError [ERR_TLS_CERT_ALTNAME_INVALID]: Hostname/IP does not match certificate's altnames: Host: localhost. is not cert's CN: <google-cloud-db-project-connection-name>\n```\n\n```text\n//ormconfig.ts\n\nexport default {\n type: 'postgres',\n port: 5432,\n host: process.env.DB_HOST,\n username: process.env.DB_USER,\n password: process.env.DB_PASS,\n database: process.env.DB_NAME,\n logging: true,\n synchronize: false,\n ssl: { ...getSSLConfig() },\n entities: ['dist/src/modules/**/entity.js'],\n migrations: ['dist/src/migration/**/*.ts'],\n subscribers: ['src/subscriber/**/*.ts'],\n} as DataSourceOptions;\n\nfunction getSSLConfig() {\n if (process.env.SSL_CA && process.env.SSL_CERT && process.env.SSL_KEY) {\n return {\n sslmode: 'verify-full',\n ca: process.env.SSL_CA.replace(/\\\\n/g, '\\n'),\n cert: process.env.SSL_CERT.replace(/\\\\n/g, '\\n'),\n key: process.env.SSL_KEY.replace(/\\\\n/g, '\\n'),\n };\n }\n\n return {};\n}\n```\n\n```text\n//index.ts\n\nimport dbConnector from './plugins/PSQLDbConnector';\n\nconst server: FastifyInstance = fastify();\nconst port: number = parseInt(`${process.env.PORT}`, 10) || 8080;\n\nserver.register(dbConnector);\n\nserver.listen({ port: port }, (err, address) => {\n if (err) {\n console.error(err);\n process.exit(1);\n }\n console.log(`Server listening at ${address}`);\n});\n```\n\n```text\nimport tls from 'node:tls'\n\nfunction getSSLConfig() {\n if (process.env.SSL_CA && process.env.SSL_CERT && process.env.SSL_KEY) {\n const pg_cn = process.env.DB_CN\n return {\n checkServerIdentity: (nohost, cert) => {\n return tls.checkServerIdentity(pg_cn, cert)\n },\n sslmode: 'verify-full',\n ca: process.env.SSL_CA.replace(/\\\\n/g, '\\n'),\n cert: process.env.SSL_CERT.replace(/\\\\n/g, '\\n'),\n key: process.env.SSL_KEY.replace(/\\\\n/g, '\\n'),\n };\n```\n\n```text\nhost\n```\n\n```text\nsslmode\n```\n\n```text\nverify-ca\n```\n\n```text\ncheckServerIdentity\n```\n\n```text\ncheckServerIdentity\n```\n\n```text\nlocalhost\n```\n\n```text\nhost\n```\n\n```text\normconfig.ts\n```\n\n```text\nprocess.env.DB_HOST\n```\n\n```text\nopenssl\n```\n\n```text\nprocess.env.DB_HOST\n```\n\n```text\nlocahost\n```\n\n========================================\n\nComments:\n- The error looks like you have `process.env.DB_HOST` set to localhost to connect to the remote DB, but it is connecting to the remote DB. Are you mapping a port to the gcloud db somehow?\n- @Matt sorry I should clarify, the DB_HOST env variable is the public IP address of the sql cloud instance.","metadata":{"transformedAt":"2026-08-18T18:33:44.704Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":273,"estimatedTokens":1799}}276{"id":"stack-69083859","source":"stackoverflow","questionId":69083859,"title":"Can't mock Paginate function in jest unit tests","tags":["typescript","unit-testing","jestjs","nestjs","typeorm"],"text":"Title: Can't mock Paginate function in jest unit tests\nTags: typescript, unit-testing, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to mock my service's findAll function. For this I either need to mock the repository function `findAndCount` myEntityRepository or the `paginate` function of of nestjs-typeorm-paginate node module. `findAll` function fetches list of records from table and is paginated using NodeModule nestjs-typeorm-paginate.\n\n**Try-1:** Mocking myEntityRepository\nBut it fails with error and traceback:\n\n```\nTypeError: queryBuilder.limit is not a function\n\n at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:119:28\n at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:8:71\n at Object..__awaiter (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:4:12)\n at paginateQueryBuilder (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:115:12)\n at Object. (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:22:15)\n at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:8:71\n```\n\nmy.service.ts\n\n```\nimport { IPaginationOptions, paginate, Pagination } from 'nestjs-typeorm-paginate'\n\nexport class MyService {\n constructor(@InjectRepository(MyEntity) private myEntityRepository: Repository) { }\n\n async findAll(options: IPaginationOptions): Promise> {\n try {\n return await paginate(this.myEntityRepository, options)\n } catch (error) {\n throw error\n }\n }\n}\n```\n\nmy.service.spec.ts\n\n```\ndescribe('MyService Basic GET findAll test cases', () => {\n let service: MyService\n let repositoryMock: MockType>\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [MyService,\n {\n provide: getRepositoryToken(MyEntity), useFactory: repositoryMockFactory\n }\n ],\n }).compile()\n\n service = module.get(MyService)\n repositoryMock = module.get(getRepositoryToken(MyEntity))\n\n const itemList = [{\n id: 1,\n my_field: 'a1',\n }, {\n id: 2,\n my_field: 'a2',\n }, ]\n\n it('should findAll() the MyEntity', async () => {\n expect((await service.findAll(options)).items.length).toBe(itemsList.length)\n })\n})\n\nconst repositoryMockFactory: () => MockType> = jest.fn(() => ({\n find: jest.fn(entity => entity),\n findAndCount: jest.fn(entity => entity),\n}))\n```\n\n**Try-2:** Mocking paginate\nThen I tried mocking paginate method but still it returns error:\n\n`TypeError: Cannot redefine property: paginate at Function.defineProperty ()`\n\nmy.service.spec.ts with Pagination mock changes)\n\n```\nimport * as nestjsTypeormPaginate from 'nestjs-typeorm-paginate' // imported at top\n ....\n ....\n it('should findAll() the MyEntity', async () => {\n const queryDto: QueryMyEntityDto = { customerId: 1 }\n const options: IPaginationOptions = { page: 1, limit: 10 }\n let paginationMock = jest.spyOn(nestjsTypeormPaginate, 'paginate')\n paginationMock.mockImplementation((dto, options) => Promise.resolve({\n items: itemList.slice(0, 2),\n meta: {\n itemCount: 2,\n totalItems: 2,\n totalPages: 1,\n currentPage: 1,\n }\n }))\n repositoryMock.find.mockReturnValue(itemList)\n expect((await service.findAll(options)).items.length).toBe(itemsList.length)\n })\n ...\n```\n\nBefore writing this question:\nI tried following posts:\n\n- Use `jest.spyOn` on an exported function from a Node module\n\n- How to mock imported named function in Jest when module is unmocked\n\n- https://github.com/nestjsx/nestjs-typeorm-paginate/issues/143\n\n========================================\n\nCode:\n```text\nTypeError: queryBuilder.limit is not a function\n\n at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:119:28\n at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:8:71\n at Object.<anonymous>.__awaiter (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:4:12)\n at paginateQueryBuilder (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:115:12)\n at Object.<anonymous> (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:22:15)\n at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:8:71\n```\n\n```text\nimport { IPaginationOptions, paginate, Pagination } from 'nestjs-typeorm-paginate'\n\nexport class MyService {\n constructor(@InjectRepository(MyEntity) private myEntityRepository: Repository<MyEntity>) { }\n\n async findAll(options: IPaginationOptions): Promise<Pagination<MyEntity>> {\n try {\n return await paginate<MyEntity>(this.myEntityRepository, options)\n } catch (error) {\n throw error\n }\n }\n}\n```\n\n```text\ndescribe('MyService Basic GET findAll test cases', () => {\n let service: MyService\n let repositoryMock: MockType<Repository<MyEntity>>\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [MyService,\n {\n provide: getRepositoryToken(MyEntity), useFactory: repositoryMockFactory\n }\n ],\n }).compile()\n\n service = module.get<MyService>(MyService)\n repositoryMock = module.get(getRepositoryToken(MyEntity))\n\n const itemList = [{\n id: 1,\n my_field: 'a1',\n }, {\n id: 2,\n my_field: 'a2',\n }, ]\n\n it('should findAll() the MyEntity', async () => {\n expect((await service.findAll(options)).items.length).toBe(itemsList.length)\n })\n})\n\nconst repositoryMockFactory: () => MockType<Repository<MyEntity>> = jest.fn(() => ({\n find: jest.fn(entity => entity),\n findAndCount: jest.fn(entity => entity),\n}))\n```\n\n```text\nimport * as nestjsTypeormPaginate from 'nestjs-typeorm-paginate' // imported at top\n ....\n ....\n it('should findAll() the MyEntity', async () => {\n const queryDto: QueryMyEntityDto = { customerId: 1 }\n const options: IPaginationOptions = { page: 1, limit: 10 }\n let paginationMock = jest.spyOn(nestjsTypeormPaginate, 'paginate')\n paginationMock.mockImplementation((dto, options) => Promise.resolve({\n items: itemList.slice(0, 2),\n meta: {\n itemCount: 2,\n totalItems: 2,\n totalPages: 1,\n currentPage: 1,\n }\n }))\n repositoryMock.find.mockReturnValue(itemList)\n expect((await service.findAll(options)).items.length).toBe(itemsList.length)\n })\n ...\n```\n\n```text\nfindAndCount\n```\n\n```text\npaginate\n```\n\n```text\nfindAll\n```\n\n```text\nTypeError: Cannot redefine property: paginate at Function.defineProperty (<anonymous>)\n```\n\n```js\n// At the top level of your unit test file, before the import of the service\n\n// Declare your itemList\nconst itemList = ['item1', 'item2', 'item3', 'item4'];\n\n// Mock the external module and the paginate function\njest.mock('nestjs-typeorm-paginate', () => ({\n paginate: jest.fn().mockResolvedValue({\n items: itemList.slice(0, 2),\n meta: {\n itemCount: 2,\n totalItems: 2,\n totalPages: 1,\n currentPage: 1,\n }\n }),\n}));\n\n// ... unit tests\n```\n\n========================================\n\nComments:\n- can you show me how do you call this inside the test?it would be really help full","metadata":{"transformedAt":"2026-08-18T18:33:44.704Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":247,"estimatedTokens":1725}}277{"id":"stack-63807650","source":"stackoverflow","questionId":63807650,"title":"TypeORM why is my relationship column undefined? foreign-key is undefined","tags":["foreign-keys","typeorm","typeorm-datamapper"],"text":"Title: TypeORM why is my relationship column undefined? foreign-key is undefined\nTags: foreign-keys, typeorm, typeorm-datamapper\nSource: Stack Overflow\n\nQuestion:\nI just use TypeORM and find the relationship column is undefined\n\n```\n@Entity({name: 'person'})\nexport class Person {\n @PrimaryGeneratedColumn('uuid')\n id!: string;\n\n @OneToOne( () => User)\n @JoinColumn()\n user!: User;\n\n @Column({\n type: \"enum\",\n enum: PersonTitle,\n default: PersonTitle.Blank\n })\n title?: string;\n\n @Column({type: 'varchar', default: ''})\n first_name!: string;\n\n @Column('varchar')\n last_name!: string;\n\n @ManyToOne(() => Organization, org => org.people, { nullable: true})\n belong_organization!: Organization;\n```\n\nand I also have `Organization` entity:\n\n```\nexport class Organization {\n @PrimaryGeneratedColumn('uuid')\n id!: string;\n...\n}\n```\n\nwhen I use `Repository` like:\n\n```\nconst db = await getDatabaseConnection()\n const prep = db.getRepository('person')\n presult = await prep.findOne({where: {id}})\n console.log(result)\n```\n\nmy result is:\n\n```\nPerson {\n id: '75c37eb9-1d88-4d0c-a927-1f9e3d909aef',\n user: undefined,\n title: 'Mr.',\n first_name: 'ss',\n last_name: 'ls',\n belong_organization: undefined, // I just want to know why is undefined? even I can find in database the column\n expertise: [],\n introduction: 'input introduction',\n COVID_19: false,\n contact: undefined\n}\n```\n\nthe database table like:\n\n```\n\"id\" \"title\" \"first_name\" \"last_name\" \"expertise\" \"COVID_19\" \"userId\" \"belongOrganizationId\" \"introduction\"\n\"75c37eb9-1d88-4d0c-a927-1f9e3d909aef\" \"Mr.\" \"test\" \"tester\" \"nothing\" \"0\" \"be426167-f471-4092-80dc-7aef67f13bac\" \"8fc50c9e-b598-483e-a00b-1d401c1b3d61\" \"input introduction\"\n```\n\nI want to show organization id, how typeORM do it? Foreign-Key is present undefined?\n\n========================================\n\nCode:\n```text\n@Entity({name: 'person'})\nexport class Person {\n @PrimaryGeneratedColumn('uuid')\n id!: string;\n\n @OneToOne( () => User)\n @JoinColumn()\n user!: User;\n\n @Column({\n type: \"enum\",\n enum: PersonTitle,\n default: PersonTitle.Blank\n })\n title?: string;\n\n @Column({type: 'varchar', default: ''})\n first_name!: string;\n\n @Column('varchar')\n last_name!: string;\n\n @ManyToOne(() => Organization, org => org.people, { nullable: true})\n belong_organization!: Organization;\n```\n\n```text\nexport class Organization {\n @PrimaryGeneratedColumn('uuid')\n id!: string;\n...\n}\n```\n\n```text\nconst db = await getDatabaseConnection()\n const prep = db.getRepository<Person>('person')\n presult = await prep.findOne({where: {id}})\n console.log(result)\n```\n\n```text\nPerson {\n id: '75c37eb9-1d88-4d0c-a927-1f9e3d909aef',\n user: undefined,\n title: 'Mr.',\n first_name: 'ss',\n last_name: 'ls',\n belong_organization: undefined, // I just want to know why is undefined? even I can find in database the column\n expertise: [],\n introduction: 'input introduction',\n COVID_19: false,\n contact: undefined\n}\n```\n\n```text\n\"id\" \"title\" \"first_name\" \"last_name\" \"expertise\" \"COVID_19\" \"userId\" \"belongOrganizationId\" \"introduction\"\n\"75c37eb9-1d88-4d0c-a927-1f9e3d909aef\" \"Mr.\" \"test\" \"tester\" \"nothing\" \"0\" \"be426167-f471-4092-80dc-7aef67f13bac\" \"8fc50c9e-b598-483e-a00b-1d401c1b3d61\" \"input introduction\"\n```\n\n```text\nOrganization\n```\n\n```text\nRepository\n```\n\n```text\n@Entity({name: 'person'})\nclass Person {\n ...\n @ManyToOne(() => Organization, org => org.people, { nullable: true})\n belong_organization!: Organization;\n ...\n}\n\n...\n\nasync logOrganization() {\n const db = await getDatabaseConnection()\n const prep = db.getRepository<Person>('person')\n presult = await prep.findOne({where: {id}})\n console.log(await result.belong_organization)\n}\n```\n\n```text\nconst prep = db.getRepository<Person>('person')\npresult = await prep.findOne({\n where: { id },\n relations: [\"belong_organization\"]\n})\n```\n\n```text\n@Entity({name: 'person'})\nclass Person {\n ...\n @Column()\n belongOrganizationId:number\n\n @ManyToOne(() => Organization, org => org.people, { nullable: true})\n belong_organization!: Organization;\n ...\n}\n```\n\n```text\nconst findOptions: {\n where :{\n id,\n 'belong_organization.id': belong_organizationId\n }\n}\n```\n\n```text\nbelong_organizationId\n```\n\n```text\nperson\n```\n\n```text\nbelongOrganizationId\n```\n\n========================================\n\nComments:\n- if I want select belong_organization.id =\"111\", how to do it?\n- @user504909 Here is one of the many discussions about your question about how to `select belong_organization.id =\"111\"`, Hopefully they will fix this proper soon but it seems for now you have to use `{ belong_organization.id: belong_id, id }`\n- @user504909 I updated the last part of the awnser to make it human readable","metadata":{"transformedAt":"2026-08-18T18:33:44.704Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":219,"estimatedTokens":1200}}278{"id":"stack-60791014","source":"stackoverflow","questionId":60791014,"title":"Nestjs with Typeorm Transaction in custom repository","tags":["typescript","nestjs","typeorm"],"text":"Title: Nestjs with Typeorm Transaction in custom repository\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a custom repository class like this with NestJS/Typeorm:\n\n```\nimport { Repository, EntityRepository, getConnection } from 'typeorm';\nimport { RefreshToken } from './refresh-token.entity';\nimport { User } from './user.entity';\nimport { InternalServerErrorException } from '@nestjs/common';\n\n@EntityRepository(RefreshToken)\nexport class RefreshTokenRepository extends Repository {\n\n async refreshToken({ token, user }: RefreshToken): Promise {\n const connection = getConnection();\n const queryRunner = connection.createQueryRunner();\n\n // establish real database connection using our new query runner\n await queryRunner.connect();\n\n // lets now open a new transaction:\n await queryRunner.startTransaction();\n\n try {\n // execute some operations on this transaction:\n await queryRunner.manager.delete(RefreshToken, { token });\n\n const refreshToken = await queryRunner.manager.save(\n this.buildToken(user),\n );\n\n // commit transaction now:\n await queryRunner.commitTransaction();\n\n return refreshToken;\n } catch (err) {\n // since we have errors lets rollback changes we made\n await queryRunner.rollbackTransaction();\n } finally {\n // you need to release query runner which is manually created:\n await queryRunner.release();\n }\n }\n}\n```\n\nIs there a different way to make/build a transaction than the one I did in `refreshToken()` method please? Because getting a connection feels broken and not appropriate with the way NestJS works.\n\nThanks.\n\n========================================\n\nCode:\n```text\nimport { Repository, EntityRepository, getConnection } from 'typeorm';\nimport { RefreshToken } from './refresh-token.entity';\nimport { User } from './user.entity';\nimport { InternalServerErrorException } from '@nestjs/common';\n\n@EntityRepository(RefreshToken)\nexport class RefreshTokenRepository extends Repository<RefreshToken> {\n\n async refreshToken({ token, user }: RefreshToken): Promise<RefreshToken> {\n const connection = getConnection();\n const queryRunner = connection.createQueryRunner();\n\n // establish real database connection using our new query runner\n await queryRunner.connect();\n\n // lets now open a new transaction:\n await queryRunner.startTransaction();\n\n try {\n // execute some operations on this transaction:\n await queryRunner.manager.delete(RefreshToken, { token });\n\n const refreshToken = await queryRunner.manager.save(\n this.buildToken(user),\n );\n\n // commit transaction now:\n await queryRunner.commitTransaction();\n\n return refreshToken;\n } catch (err) {\n // since we have errors lets rollback changes we made\n await queryRunner.rollbackTransaction();\n } finally {\n // you need to release query runner which is manually created:\n await queryRunner.release();\n }\n }\n}\n```\n\n```text\nrefreshToken()\n```\n\n```js\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mysql',\n host: 'localhost',\n port: 3306,\n username: 'root',\n password: 'root',\n database: 'test',\n entities: [],\n synchronize: true,\n }),\n ],\n})\nexport class AppModule {}\n```\n\n```js\ntry {\n const refreshToken = await this.manager.transaction(async entityManager => {\n await entityManager.delete(RefreshToken, { token });\n return entityManager.save(RefreshToken, this.buildToken(user));\n });\n\n // commit done: use refreshToken here\n} catch (error) {\n // rollback done: handle error here\n}\n```\n\n```text\n@nestjs/typeorm\n```\n\n```text\nTypeOrmModule\n```\n\n```text\n@nestjs/typeorm\n```\n\n```text\nRepository\n```\n\n========================================\n\nComments:\n- Thanks a lot; I tried these before and the manager was returning `null`, I retried today and now it works :)","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":153,"estimatedTokens":958}}279{"id":"stack-72738730","source":"stackoverflow","questionId":72738730,"title":"migrating down your latest migrations","tags":["migration","typeorm"],"text":"Title: migrating down your latest migrations\nTags: migration, typeorm\nSource: Stack Overflow\n\nQuestion:\nFirst a theoritical background:\n\nIf I create 3 new migration files that would change 3 tables after I `migrate up` , should `migrate down` revert all 3 tables effected by the latest migration or just the last table that was effected?\n\n(*my guess the former should happen*)\n\nThe problem:\n\nIn `typeorm` when I `typeorm migrate:revert` , it only effects the last table that was effected by the latest migration, so I'm wondering if my guess was correct or not. What is the usual behaviour for `migrate down` in general(irrespective of the ORM used).\n\nIs this an expected behaviour or there a possible solution for `typeorm` to keep track of the latest migration changes to revert all the changes in latest migration?\n\nI have found this in their documentation:\n\nIf for some reason you want to revert the changes, you can run:\ntypeorm migration:revert\nThis command will execute down in the latest executed migration. If you need to revert multiple migrations you must call this command multiple times.\n\nBut, if what I expect is true, then an orm should already have the tools to do so.\n\n========================================\n\nCode:\n```text\nmigrate up\n```\n\n```text\nmigrate down\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeorm migrate:revert\n```\n\n```text\nmigrate down\n```\n\n```text\ntypeorm\n```\n\n========================================\n\nComments:\n- Slight correction: You don't migrate down table by table, but you migrate down migration by migration. If you have created a separate migration for each table, then each migration will only affect one table, but it will always run the `down` function in the migration and affect all the tables that were created with that migration.","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":56,"estimatedTokens":444}}280{"id":"stack-68817253","source":"stackoverflow","questionId":68817253,"title":"typeorm: what is the difference between getRepository() and getConnection()?","tags":["typescript","typeorm"],"text":"Title: typeorm: what is the difference between getRepository() and getConnection()?\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nhttps://typeorm.io/#/select-query-builder/how-to-create-and-use-a-querybuilder\n\nThere are several ways how you can create a Query Builder:\n\nUsing connection:\n\n```\nimport {getConnection} from \"typeorm\";\n\nconst user = await getConnection()\n .createQueryBuilder()\n .select(\"user\")\n .from(User, \"user\")\n .where(\"user.id = :id\", { id: 1 })\n .getOne();\n```\n\nUsing entity manager:\n\n```\nimport {getManager} from \"typeorm\";\n\nconst user = await getManager()\n .createQueryBuilder(User, \"user\")\n .where(\"user.id = :id\", { id: 1 })\n .getOne();\n```\n\nUsing repository:\n\n```\nimport {getRepository} from \"typeorm\";\n\nconst user = await getRepository(User)\n .createQueryBuilder(\"user\")\n .where(\"user.id = :id\", { id: 1 })\n .getOne();\n```\n\nThe documentation never explains the difference among these methods.\nWhen to use each method?\n\n========================================\n\nTop Answer:\nThere are no meaningful differences between creating a query builder by connection, manager, or repository.\n\nAccording to one of the typeorm lead devs:\n\nthey all are same, just aliases for the same functionality. Use what is convenient for you.\n\n========================================\n\nCode:\n```text\nimport {getConnection} from \"typeorm\";\n\nconst user = await getConnection()\n .createQueryBuilder()\n .select(\"user\")\n .from(User, \"user\")\n .where(\"user.id = :id\", { id: 1 })\n .getOne();\n```\n\n```text\nimport {getManager} from \"typeorm\";\n\nconst user = await getManager()\n .createQueryBuilder(User, \"user\")\n .where(\"user.id = :id\", { id: 1 })\n .getOne();\n```\n\n```text\nimport {getRepository} from \"typeorm\";\n\nconst user = await getRepository(User)\n .createQueryBuilder(\"user\")\n .where(\"user.id = :id\", { id: 1 })\n .getOne();\n```\n\n```text\n/**\n * Gets connection from the connection manager.\n * If connection name wasn't specified, then \"default\" connection will be retrieved.\n *\n * @deprecated\n */\nexport function getConnection(connectionName: string = \"default\"): DataSource {\n return getConnectionManager().get(connectionName)\n}\n```\n\n```text\n/**\n * Gets repository for the given entity class.\n *\n * @deprecated\n */\nexport function getRepository<Entity extends ObjectLiteral>(\n entityClass: EntityTarget<Entity>,\n connectionName: string = \"default\",\n): Repository<Entity> {\n return getConnectionManager()\n .get(connectionName)\n .getRepository<Entity>(entityClass)\n}\n```\n\n```text\n/**\n * Gets entity manager from the connection.\n * If connection name wasn't specified, then \"default\" connection will be retrieved.\n *\n * @deprecated\n */\nexport function getManager(connectionName: string = \"default\"): EntityManager {\n return getConnectionManager().get(connectionName).manager\n}\n```\n\n```text\ngetConnection()\n```\n\n```text\ngetRepository()\n```\n\n```text\ngetManager()\n```\n\n```text\ngetConnection()\n```\n\n```text\nDataSource\n```\n\n```text\ngetRepository()\n```\n\n```text\nRepository\n```\n\n```text\ngetManager()\n```\n\n```text\nEntityManager\n```\n\n```text\ncreateQueryBuilder()\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":167,"estimatedTokens":782}}281{"id":"stack-57692838","source":"stackoverflow","questionId":57692838,"title":"TypeOrm doesn't save entity with it's relation on update","tags":["postgresql","typescript","nestjs","typeorm"],"text":"Title: TypeOrm doesn't save entity with it's relation on update\nTags: postgresql, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nGiven the following relation:\n\n```\n@Entity({name: 'accounts'})\nexport class Account {\n\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @OneToOne(type => Address, address => address.id)\n @JoinColumn({name: 'address_id'})\n address: Address;\n\n @Column()\n name: string;\n}\n```\n\nAnd the addres relation:\n\n```\n@Entity({name: 'addresses'})\nexport class Address {\n\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column({length: 45})\n country: string;\n}\n```\n\nWhen I get the `account` entity by this:\n\n```\n/**\n * Gets account by haccount ID with ALL relations\n * @param accountId The account ID\n */\n public async getAccountByAccountIdWithRelations(accountId: string): Promise {\n return await this.findOneOrFail({id: accountId}, {relations: ['address']});\n }\n```\n\nI get the full `Account` entity with the `Address` relation in it.\n\nAnd then when I do the following:\n\n```\naccount.address.country = 'newcountry';\n```\n\nand do `this.save(account)` in `accountRepository` the address won't update at all!\n\n*When I do console log before the save, I see the `account` entity with the updated address, so this is something really strange!*\n\nWhy is it happening?\n\n**Note: All queries are done in a transaction; I dont know if it matters**\n\n========================================\n\nTop Answer:\nDoing that kind of update on sql is quite complicated and even with queryBuilder TypeORM doesn't support join updates (you can see it here). The relation selector is quite helpfull but I would advise you to use it when its really necesary and add a nullable field to get the Ids of the address and obtain the address on separate it makes the things a lot easier in cases you need to change that relation lets say when you want to change the whole address object. this would be the result in the relations:\n\n```\n@Entity({name: 'accounts'})\nexport class Account {\n\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column({ nullable: true })\n address_id: string;\n\n @OneToOne(type => Address, address => address.id)\n @JoinColumn({name: 'address_id'})\n address: Address;\n\n @Column()\n name: string;\n}\n```\n\nAnd you can keep calling the relation as you did before with:\n\n```\npublic async getAccountByAccountIdWithRelations(accountId: string): Promise {\n return await this.findOneOrFail({id: accountId}, {relations: ['address']});\n }\n```\n\nUsing this aproach would keep inserting and updating easy and it works also in the oneToMany => manyToOne Relations too\n\n========================================\n\nCode:\n```text\n@Entity({name: 'accounts'})\nexport class Account {\n\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @OneToOne(type => Address, address => address.id)\n @JoinColumn({name: 'address_id'})\n address: Address;\n\n @Column()\n name: string;\n}\n```\n\n```text\n@Entity({name: 'addresses'})\nexport class Address {\n\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column({length: 45})\n country: string;\n}\n```\n\n```text\n/**\n * Gets account by haccount ID with ALL relations\n * @param accountId The account ID\n */\n public async getAccountByAccountIdWithRelations(accountId: string): Promise<Account> {\n return await this.findOneOrFail({id: accountId}, {relations: ['address']});\n }\n```\n\n```text\naccount.address.country = 'newcountry';\n```\n\n```text\naccount\n```\n\n```text\nAccount\n```\n\n```text\nAddress\n```\n\n```text\nthis.save(account)\n```\n\n```text\naccountRepository\n```\n\n```text\naccount\n```\n\n```text\n@Entity()\n@Index([ 'studyId', 'teamId', 'enterdate' ])\nexport class DataMessage extends BaseEntity {\n @PrimaryGeneratedColumn('increment') id: number;\n\n @CreateDateColumn() enterdate: Date;\n @UpdateDateColumn({ select: false })\n updatedAt?: Date;\n @Column() owner: string;\n @Column() studyId: number;\n @Column() teamId: number;\n @Column() patient: string;\n @Column() orderId: number;\n @Column({ default: DataMessageStatus.OPEN })\n status: DataMessageStatus;\n\n @Column()\n @Index()\n resultId: number;\n\n @OneToMany(() => DataMessageContent, (c) => c.message, { cascade: true })\n contents: DataMessageContent[];\n}\n\n@Entity()\nexport class DataMessageContent extends BaseEntity {\n @PrimaryGeneratedColumn('increment') id: number;\n\n @CreateDateColumn() enterdate: Date;\n @Column() owner: string;\n @Column() role: UserRole;\n @Column({ default: MessageStatus.UNREAD })\n status: MessageStatus;\n\n @Column() txt: string;\n\n @ManyToOne(() => DataMessage, (m) => m.contents)\n message: DataMessage;\n}\n```\n\n```text\n@Entity({name: 'accounts'})\nexport class Account {\n\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column({ nullable: true })\n address_id: string;\n\n @OneToOne(type => Address, address => address.id)\n @JoinColumn({name: 'address_id'})\n address: Address;\n\n @Column()\n name: string;\n}\n```\n\n```text\npublic async getAccountByAccountIdWithRelations(accountId: string): Promise<Account> {\n return await this.findOneOrFail({id: accountId}, {relations: ['address']});\n }\n```\n\n========================================\n\nComments:\n- Can you add some more context around your answer?\n- I've added a complete example\n- That's right, cascade makes it delete and save recursive, thanks!","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":241,"estimatedTokens":1321}}282{"id":"stack-73898218","source":"stackoverflow","questionId":73898218,"title":"TypeORM: How to use sub queries in queryBuilder","tags":["node.js","typescript","postgresql","typeorm"],"text":"Title: TypeORM: How to use sub queries in queryBuilder\nTags: node.js, typescript, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have the following PostgresSQL:\n\n```\nSELECT symbol, created_at\nFROM (\n SELECT DISTINCT ON (symbol) symbol, created_at\n FROM update_history\n WHERE exchange = 'TEST' AND data_type = 'ANY'\n ORDER BY symbol, created_at DESC\n) h\nORDER BY created_at ASC\nLIMIT 500;\n```\n\nI'm trying to write this out using TypeORM's `queryBuilder`, but can't seem to work out how it translates to the above.\n\nThe closest I've got right now (which isn't correct, and doesn't return the correct data set) is the following:\n\n```\nconst result = this.repository\n .createQueryBuilder('history')\n .select(['history.symbol', 'history.createdAt'])\n .where('history.exchange = :exchange', { exchange: 'TEST' })\n .addFrom(\n (subQuery) =>\n subQuery\n .select(['h.symbol', 'h.createdAt'])\n .distinctOn(['h.symbol'])\n .from(HistoryRecord, 'h')\n .where('h.exchange = :exchange', { exchange: 'TEST' })\n .andWhere('h.dataType = :dataType', { dataType: 'ANY' })\n .orderBy({ 'h.symbol': 'DESC', 'h.createdAt': 'DESC' }),\n 'h',\n )\n .orderBy({ 'history.createdAt': 'ASC' })\n .take(500);\n```\n\nCan anyone help me out?\n\n========================================\n\nCode:\n```sql\nSELECT symbol, created_at\nFROM (\n SELECT DISTINCT ON (symbol) symbol, created_at\n FROM update_history\n WHERE exchange = 'TEST' AND data_type = 'ANY'\n ORDER BY symbol, created_at DESC\n) h\nORDER BY created_at ASC\nLIMIT 500;\n```\n\n```js\nconst result = this.repository\n .createQueryBuilder('history')\n .select(['history.symbol', 'history.createdAt'])\n .where('history.exchange = :exchange', { exchange: 'TEST' })\n .addFrom(\n (subQuery) =>\n subQuery\n .select(['h.symbol', 'h.createdAt'])\n .distinctOn(['h.symbol'])\n .from(HistoryRecord, 'h')\n .where('h.exchange = :exchange', { exchange: 'TEST' })\n .andWhere('h.dataType = :dataType', { dataType: 'ANY' })\n .orderBy({ 'h.symbol': 'DESC', 'h.createdAt': 'DESC' }),\n 'h',\n )\n .orderBy({ 'history.createdAt': 'ASC' })\n .take(500);\n```\n\n```text\nqueryBuilder\n```\n\n```text\nconst connection = getConnection();\nconst result = connection.createQueryBuilder()\n .select(['history.symbol', 'history.createdAt'])\n .addFrom(\n (qb) => {\n return qb.select(['h.symbol as symbol', 'h.createdAt as createdAt'])\n .distinctOn(['h.symbol'])\n .from(HistoryRecord, 'h')\n .where('h.exchange = :exchange', { exchange: 'TEST' })\n .andWhere('h.dataType = :dataType', { dataType: 'ANY' })\n .orderBy('h.symbol', 'DESC')\n .addOrderBy('h.createdAt', 'DESC')\n },\n 'history'\n )\n .orderBy('history.createdAt', 'ASC')\n .take(500);\n```\n\n```text\nconst result = getManager().createQueryBuilder()\n ...\n ...\n```\n\n```text\nthis.repository\n```\n\n```text\nfrom\n```\n\n```text\nhistory\n```\n\n```text\nh\n```\n\n```text\naddFrom\n```\n\n```text\nfrom\n```\n\n========================================\n\nComments:\n- Thanks, that's working with .getManyRaw()! I'm trying to use .getMany() but I'm getting the following: \"Cannot get entity metadata for the given alias 'history'\". Ideally I'd like to use an .innerJoinAndSelect() with this too. Any ideas?\n- Since `getConnection()` is deprecated, you can achieve the same with `this.repository.manager.connection.createQueryBuilder()`","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":139,"estimatedTokens":839}}283{"id":"stack-71106840","source":"stackoverflow","questionId":71106840,"title":"How to INSERT with SELECT values in TypeORM","tags":["node.js","typeorm"],"text":"Title: How to INSERT with SELECT values in TypeORM\nTags: node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nLets say I have main table Users and a reference table UserRoles such that each User has one Role saved in the column roleId, and every role has an id and a description.\n\nIf I want to insert a new User with the role Administrator, the following SQL query would work:\n\n```\nINSERT INTO `users` (`name`, `roleId`) \nVALUES ('John Doe', (SELECT `id` FROM `roles` WHERE `roles`.`description` = 'admin'));\n```\n\nHow would I replicate the same in TypeORM having two entities User and Role?\n\nI know I can do the following:\n\n```\nconst adminRole = await Role.findOne({description: 'admin'});\nconst newUser = User.create({name: 'John Doe'});\nnewUser.role = adminRole;\nawait newUser.save();\n```\n\nBut this would rather be equivalent to SELECT the role into a variable and then using that variable during the INSERT. is there a way to condense this into one query so that the database is hit only once?\n\nI know that I can create an user with the relation like this\n\n```\nUser.create({name: 'John Doe', role: {id: 1}});\n```\n\nBut I need to know the id for this. If I put the name like the following\n\n```\nUser.create({name: 'John Doe', role: {name: 'admin'}});\n```\n\nI get the following error `Error: Cannot find alias for relation at type` because I have not loaded the relation.\n\nI've found information on how to make an INSERT INTO SELECT statement here, but this is where the whole insert comes from a select, not just a particular column.\n\nIs there a way to emulate this query for insertions? or I'm forced to either do it in two steps (or as many as reference columns as I have) or use the query builder?\n\nThanks you in advance\n\n========================================\n\nCode:\n```text\nINSERT INTO `users` (`name`, `roleId`) \nVALUES ('John Doe', (SELECT `id` FROM `roles` WHERE `roles`.`description` = 'admin'));\n```\n\n```text\nconst adminRole = await Role.findOne({description: 'admin'});\nconst newUser = User.create({name: 'John Doe'});\nnewUser.role = adminRole;\nawait newUser.save();\n```\n\n```text\nUser.create({name: 'John Doe', role: {id: 1}});\n```\n\n```text\nUser.create({name: 'John Doe', role: {name: 'admin'}});\n```\n\n```text\nError: Cannot find alias for relation at type\n```\n\n```text\nconst role = await getConnection()\n .createQueryBuilder()\n .select('role')\n .from(Role, 'role')\n .where('role.description = :description', { description: 'admin' })\n .getOne();\n\n if (!role) {\n console.error('Role not found');\n return;\n }\n\n const newUser = User.create({ name: 'John Doe', role });\n```\n\n```text\nimport { getManager, getRepository } from 'typeorm';\nimport { User } from './entity/User';\nimport { Role } from './entity/Role';\n\nasync function createUserWithRole() {\n const entityManager = getManager();\n const roleRepository = getRepository(Role);\n\n try {\n await entityManager.transaction(async transactionalEntityManager => {\n const adminRole = await roleRepository.findOneOrFail({ description: 'admin' });\n const newUser = transactionalEntityManager.create(User, { name: 'John Doe', role: adminRole });\n await transactionalEntityManager.save(newUser);\n });\n console.log('User created successfully with role.');\n } catch (error) {\n console.error('Error creating user with role:', error);\n }\n}\n\ncreateUserWithRole();\n```\n\n========================================\n\nComments:\n- I've been trying to solve a very similar problem. From what I've learned so far we need to use TypeORM's Query Builder, the repository won't help us on this. My best hint so far involves creating an Insert with the query builder and then using SubQueries to try to retrieve the values I want to insert from other tables. I cant seem to make it work though\n- I think the first option is the same as I was doing, just a bit longer. The second option seems to be the right way; it does not add a lot of code and its a good practice anyway to keep everything in transactions. Too bad the relations need to be loaded one by one but at least, if the transaction allows to hit the database only once, regardless of the number of relations, then I think this is the way to go. Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":119,"estimatedTokens":1070}}284{"id":"stack-61995600","source":"stackoverflow","questionId":61995600,"title":"how to resolve getting syntax error at or near \":\" Where clause","tags":["postgresql","repository-pattern","typeorm"],"text":"Title: how to resolve getting syntax error at or near \":\" Where clause\nTags: postgresql, repository-pattern, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am new to coding and I am trying to develop new skills.\n\nI am stuck at a point where I am trying to retrieve data based on a userid from PostgreSQL Task table.\n\nI am using typeorm to achieve this\nthe following is my code \n\n```\nasync getTasks(\n getTasksFilterDTO: GetTasksFilterDTO,\n user: User,\n ): Promise {\n const { status, search } = getTasksFilterDTO;\n const query = this.createQueryBuilder('task');\n\n query.where('task.userId = : userId', { userId: user.id });\n\n const tasks = await query.getMany();\n return tasks;\n }\n```\n\nI am getting an error at line \n\n```\nquery.where('task.userId = : userId', { userId: user.id });\n```\n\nthe error is [ExceptionsHandler] syntax error at or near \":\" +736ms\nQueryFailedError: syntax error at or near \":\"\n\n```\nat new QueryFailedError (C:\\tutorials\\nestjs-task-management\\node_modules\\typeorm\\error\\QueryFailedError.js:11:28)\nat Query.callback (C:\\tutorials\\nestjs-task-management\\node_modules\\typeorm\\driver\\postgres\\PostgresQueryRunner.js:176:38)\n```\n\nCan someone help me to understand the mistake I was doing?\n\n========================================\n\nCode:\n```text\nasync getTasks(\n getTasksFilterDTO: GetTasksFilterDTO,\n user: User,\n ): Promise<Task[]> {\n const { status, search } = getTasksFilterDTO;\n const query = this.createQueryBuilder('task');\n\n query.where('task.userId = : userId', { userId: user.id });\n\n const tasks = await query.getMany();\n return tasks;\n }\n```\n\n```text\nquery.where('task.userId = : userId', { userId: user.id });\n```\n\n```text\nat new QueryFailedError (C:\\tutorials\\nestjs-task-management\\node_modules\\typeorm\\error\\QueryFailedError.js:11:28)\nat Query.callback (C:\\tutorials\\nestjs-task-management\\node_modules\\typeorm\\driver\\postgres\\PostgresQueryRunner.js:176:38)\n```\n\n```text\nquery.where('task.userId = :userId', { userId: user.id });\n```\n\n```text\n:\n```\n\n```text\nuserId\n```\n\n========================================\n\nComments:\n- Do you perhaps mean `'task.userId = :userId'` so that `:userId` will be seen as a parameter?","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":86,"estimatedTokens":543}}285{"id":"stack-68347711","source":"stackoverflow","questionId":68347711,"title":"Create a separate (in memory) database for each test","tags":["typescript","sqlite","jestjs","typeorm"],"text":"Title: Create a separate (in memory) database for each test\nTags: typescript, sqlite, jestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIt is possible to create a in memory database for each test?\n\nI currently use the following code, which works if I only run one test file or use the `--run-in-band` option.\n\n```\nimport _useDb from \"@/useDb\";\nimport { mocked } from \"ts-jest/utils\";\nimport { createConnection, getConnection } from \"typeorm\";\n\nconst useDb = mocked(_useDb);\n\njest.mock(\"@/useDb\");\n\nbeforeEach(async () => {\n useDb.mockImplementation(async (action) => {\n const db = await createConnection({\n type: \"sqlite\",\n database: \":memory:\",\n dropSchema: true,\n entities: [Entity],\n synchronize: true,\n logging: false,\n });\n\n await action(db);\n });\n});\n\nafterEach(async () => {\n const con = getConnection();\n\n await con.close();\n});\n```\n\nBut as soon as I run multiple tests at the same time I get:\n\n```\nCannotExecuteNotConnectedError: Cannot execute operation on \"default\" connection because connection is not yet established.\n```\n\nI think I could provide a name attribute with a random uuid, like they suggested in How to create separate in memory database for each test? But is this really the way to go? Isn't there some kind of parameter that tells TypeORM \"please don't create connections indexed by name\" (or whatever it is doing)?\n\n========================================\n\nCode:\n```js\nimport _useDb from \"@/useDb\";\nimport { mocked } from \"ts-jest/utils\";\nimport { createConnection, getConnection } from \"typeorm\";\n\nconst useDb = mocked(_useDb);\n\njest.mock(\"@/useDb\");\n\nbeforeEach(async () => {\n useDb.mockImplementation(async (action) => {\n const db = await createConnection({\n type: \"sqlite\",\n database: \":memory:\",\n dropSchema: true,\n entities: [Entity],\n synchronize: true,\n logging: false,\n });\n\n await action(db);\n });\n});\n\nafterEach(async () => {\n const con = getConnection();\n\n await con.close();\n});\n```\n\n```text\nCannotExecuteNotConnectedError: Cannot execute operation on \"default\" connection because connection is not yet established.\n```\n\n```text\n--run-in-band\n```\n\n```text\nbeforeEach(async () => {\n const con = await createConnection({\n type: \"sqlite\",\n database: \":memory:\",\n dropSchema: true,\n entities: [],\n synchronize: true,\n logging: false,\n });\n\n mockGetDbConnection.mockResolvedValue(con);\n});\n\nafterEach(async () => {\n const con = getConnection();\n\n await con.close();\n});\n```\n\n```text\nbeforeEach\n```\n\n```text\nafterEach\n```\n\n```text\nmockGetDbConnection\n```\n\n```text\ngetConnection\n```\n\n```text\nsetupFilesAfterEnv\n```\n\n========================================\n\nComments:\n- Check your tests and what you do as well. I had a similar problem using a different library (mock-fs) and since I loaded it early in the beforeEach, instead of it being the last thing in the beforeEach, I was getting some random errors as well with access data from it.\n- @StevenScott Okay, definitely something to keep in mind those bugs are always the worst, but as I said, it **only** happens when I run the tests via worker pool. So multiple default connections somehow get into the TypeORM pool.\n- @StevenScott so I think you were kinda right. No idea how I got it to work, but it works now. Thank you :D\n- Glad I pointed you in the right direction? I know with the Mock-FS, once I did that, anything trying to access the OS failed, so that was my gotcha, even though it was the testing code, that I thought would have been already compiled and running, before the mock. I think it might have something to do with Jest's parallel execution as well, but not 100% sure, as I did not try it with the run in sequence mode to verify this. It might be your afterAll() gets called in a different test, and maybe messes with the mock in these tests? Not sure, but glad you got it to work.","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":138,"estimatedTokens":964}}286{"id":"stack-64938191","source":"stackoverflow","questionId":64938191,"title":"TypeORM logging - enabled but no output","tags":["node.js","typescript","typeorm","koa"],"text":"Title: TypeORM logging - enabled but no output\nTags: node.js, typescript, typeorm, koa\nSource: Stack Overflow\n\nQuestion:\nSimple issue. Typeorm doesn't log anything. I've followed the instructions on https://orkhan.gitbook.io/typeorm/docs/logging\n\normconfig.json\n\n```\n{\n \"type\": \"mongodb\",\n \"host\": \"aaa\",\n \"port\": 27017,\n \"username\": \"bbb\",\n \"password\": \"ccc\",\n \"ssl\": true,\n \"database\": \"db\",\n \"entities\": [\"dist/entity/*.js\"],\n \"logging\": true\n}\n```\n\nI've also tried `logging: \"all`, `logging: [\"query\"]` but none of them have any effect.\n\nHere's how I set up the app (app.ts)\n\n```\ncreateConnection()\n .then(async (connection) => {\n // create koa app\n const app = new Koa();\n const router = new Router();\n\n // register all application routes\n AppRoutes.forEach((route) =>\n router[route.method](route.path, route.action)\n );\n\n // run app\n app.use(bodyParser());\n app.use(router.routes());\n app.use(router.allowedMethods());\n app.listen(3000);\n\n console.log(\"Koa application is up and running on port 3000\");\n })\n .catch((error) => console.log(\"TypeORM connection error: \", error));\n```\n\nMy other console.logs show up just fine but nothing from typeorm.\n\nI'm starting the project with `tsc && node dist/app.js`\n\nAfter that I make an API request, query an endpoint and typeorm will go all the way thru to query Mongodb, and return back my data. But I don't see any logs.\n\nHas anyone had this issue before, or is this a new bug?\n\n========================================\n\nCode:\n```json\n{\n \"type\": \"mongodb\",\n \"host\": \"aaa\",\n \"port\": 27017,\n \"username\": \"bbb\",\n \"password\": \"ccc\",\n \"ssl\": true,\n \"database\": \"db\",\n \"entities\": [\"dist/entity/*.js\"],\n \"logging\": true\n}\n```\n\n```js\ncreateConnection()\n .then(async (connection) => {\n // create koa app\n const app = new Koa();\n const router = new Router();\n\n // register all application routes\n AppRoutes.forEach((route) =>\n router[route.method](route.path, route.action)\n );\n\n // run app\n app.use(bodyParser());\n app.use(router.routes());\n app.use(router.allowedMethods());\n app.listen(3000);\n\n console.log(\"Koa application is up and running on port 3000\");\n })\n .catch((error) => console.log(\"TypeORM connection error: \", error));\n```\n\n```text\nlogging: \"all\n```\n\n```text\nlogging: [\"query\"]\n```\n\n```text\ntsc && node dist/app.js\n```\n\n========================================\n\nComments:\n- Provide `createConnection` logic.","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":114,"estimatedTokens":604}}287{"id":"stack-52068179","source":"stackoverflow","questionId":52068179,"title":"TypeORM lazyload update parent fails on child save","tags":["typescript","lazy-loading","one-to-one","typeorm"],"text":"Title: TypeORM lazyload update parent fails on child save\nTags: typescript, lazy-loading, one-to-one, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am not sure if this is a bug, or I am doing something wrong, but I tried a lot of things to get this working and I couldn't. I hope you guys can help.\n\nBasically I have a one to one relationship that I need to lazyLoad. The relation tree is kind of big in my project and I can't load it without promises.\n\nThe issue I face is that when I save a child, the parent update generated sql is missing the update fields: `UPDATE `a` SET WHERE `id` = 1`\n\nThis is working perfectly when I am not using lazyLoading (Promises).\n\nI got a simple example set up using the generated code tool.\n\n**Entity A**\n\n```\n@Entity()\nexport class A {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToOne(\n (type: any) => B,\n async (o: B) => await o.a\n )\n @JoinColumn()\n public b: Promise;\n}\n```\n\n**Entity B**\n\n```\n@Entity()\nexport class B {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToOne(\n (type: any) => A,\n async (o: A) => await o.b)\n a: Promise;\n\n}\n```\n\n**main.ts**\n\n```\ncreateConnection().then(async connection => {\n\n const aRepo = getRepository(A);\n const bRepo = getRepository(B);\n\n console.log(\"Inserting a new user into the database...\");\n const a = new A();\n a.name = \"something\";\n const aCreated = aRepo.create(a);\n await aRepo.save(aCreated);\n\n const as = await aRepo.find();\n console.log(\"Loaded A: \", as);\n\n const b = new B();\n b.name = \"something\";\n const bCreated = bRepo.create(b);\n bCreated.a = Promise.resolve(as[0]);\n await bRepo.save(bCreated);\n\n const as2 = await aRepo.find();\n console.log(\"Loaded A: \", as2);\n\n}).catch(error => console.log(error));\n```\n\n**Output**\n\n```\nInserting a new user into the database...\nquery: SELECT `b`.`id` AS `b_id`, `b`.`name` AS `b_name` FROM `b` `b` INNER JOIN `a` `A` ON `A`.`bId` = `b`.`id` WHERE `A`.`id` IN (?) -- PARAMETERS: [[null]]\nquery: START TRANSACTION\nquery: INSERT INTO `a`(`id`, `name`, `bId`) VALUES (DEFAULT, ?, DEFAULT) -- PARAMETERS: [\"something\"]\nquery: UPDATE `a` SET WHERE `id` = ? -- PARAMETERS: [1]\nquery failed: UPDATE `a` SET WHERE `id` = ? -- PARAMETERS: [1]\n```\n\nIf I remove the promises from the entities, everything is working fine:\n\n**Entity A**\n\n```\n...\n @OneToOne(\n (type: any) => B,\n (o: B) => o.a\n )\n @JoinColumn()\n public b: B;\n}\n```\n\n**Entity B**\n\n```\n...\n @OneToOne(\n (type: any) => A,\n (o: A) => o.b)\n a: A;\n\n}\n```\n\n**main.ts**\n\n```\ncreateConnection().then(async connection => {\n...\n const bCreated = bRepo.create(b);\n bCreated.a = as[0];\n await bRepo.save(bCreated);\n...\n```\n\n**Output**\n\n```\nquery: INSERT INTO `b`(`id`, `name`) VALUES (DEFAULT, ?) -- PARAMETERS: [\"something\"]\nquery: UPDATE `a` SET `bId` = ? WHERE `id` = ? -- PARAMETERS: [1,1]\nquery: COMMIT\nquery: SELECT `A`.`id` AS `A_id`, `A`.`name` AS `A_name`, `A`.`bId` AS `A_bId` FROM `a` `A`\n```\n\nI have also created a git project to illustrate this and for easy of testing.\n\n1) using promises (not working) https://github.com/cuzzea/bug-typeorm/tree/promise-issue\n\n2) no lazy loading (working) https://github.com/cuzzea/bug-typeorm/tree/no-promise-no-issue\n\n========================================\n\nTop Answer:\nFollowing up on @Timshel's fantastic answer (and attempt at fixing the underlying issue in typeorm itself).\n\nFor those finding there way here who are looking for a workaround in lieu of https://github.com/typeorm/typeorm/pull/2902 being merged, i think i've figured something out (assuming you're using the ActiveRecord pattern with typeorm). First to summarize, as most of this information is absent from documentation and needs to be pieced together from various github issues/this SO question:\n\nAs pointed out here and on the corresponding issue, when using `create` passing in a Promise for a lazy loaded relation field simply does not work despite the type signature of that function demanding otherwise (and despite the documentation suggesting that lazy loaded fields should be wrapped in `Promise.resolve`'s for saving purposes). What does seem to work according to\n@Timshel's comment in the aforementioned PR is:\n\nnasty TypeScript type casts when assigning object literals to lazy-load properties\n\nWhat this means is that with the `create` method, if you pass in a plain entity object (instead of a Promise containing said object) for one of these lazy loaded fields typeorm will actually set this value correctly and you will be able to save. You'll even magically get a promise when accessing this field later on. The above quote mentions that you can take advantage of this by force casting your entity objects as Promise's before passing them into create. But this needs to be done on a case by case basis and if you ever accidentally obey the type signature rather than force casting, you're going to have an unexpected result at runtime. Wouldn't it be great if we could correct this type signature to get the compiler to only yell at us when we use this function in a way that won't work? We can, heres how :).\n\n```\nimport {\n BaseEntity,\n DeepPartial,\n ObjectType,\n} from 'typeorm';\n\n/**\n * Conditional type that takes a type and maps every property which is\n * a Promise to the unwrapped value of that Promise. Specifically to correct the type\n * of typeorm's create method. Using this otherwise would likely be incredibly unwise.\n *\n * For example this type:\n * {\n * hey: number,\n * thing: Promise,\n * sup: string\n * }\n *\n * gets mapped to:\n * {\n * hey: number,\n * thing: ThingEntity,\n * sup: string\n * }\n *\n */\ntype DePromisifyValue = T extends Promise ? U : T;\ntype DePromisifyObject = T extends object\n ? { [K in keyof T]: DePromisifyValue }\n : T;\n\nexport abstract class CommonEntity extends BaseEntity {\n static create(\n this: ObjectType,\n entityLike?: DeepPartial>\n ): T {\n if (!entityLike) {\n return super.create();\n }\n return super.create(entityLike as DeepPartial);\n }\n}\n```\n\nWhat this does is define an overridden version of this `create` method which accepts the same object argument as the original `create` method, except where any `Promise` fields are there unwrapped versions (ie `myLazyLoadedUser: Promise` becomes `myLazyLoadedUser: UserEntity`). It then passes that into the original `create` method and force casts it to the old version with all the `Promise` fields, the way that `BaseEntity` likes (or lies about liking that is). Force casting at some point can't be avoided without the issue being fixed within typeorm itself, but this solution only requires force casting in one central place where we can be confident we're doing the right thing. Just extend this `CommonEntity` (call it whatever you want) instead of `BaseEntity` and the `create` method will require the correct type of you. No need to wrap your values in `Promise.resolve`. And the entity returned from it will still have those lazy loaded fields with their original `Promise` types.\n\n**Note**: I haven't handled the type signature for `create` where an array of objects is passed in. I've no need for this myself, but i'm sure the type for that with the same approach can be worked out with sufficient effort.\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class A {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToOne(\n (type: any) => B,\n async (o: B) => await o.a\n )\n @JoinColumn()\n public b: Promise<B>;\n}\n```\n\n```text\n@Entity()\nexport class B {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToOne(\n (type: any) => A,\n async (o: A) => await o.b)\n a: Promise<A>;\n\n}\n```\n\n```text\ncreateConnection().then(async connection => {\n\n const aRepo = getRepository(A);\n const bRepo = getRepository(B);\n\n console.log(\"Inserting a new user into the database...\");\n const a = new A();\n a.name = \"something\";\n const aCreated = aRepo.create(a);\n await aRepo.save(aCreated);\n\n const as = await aRepo.find();\n console.log(\"Loaded A: \", as);\n\n const b = new B();\n b.name = \"something\";\n const bCreated = bRepo.create(b);\n bCreated.a = Promise.resolve(as[0]);\n await bRepo.save(bCreated);\n\n const as2 = await aRepo.find();\n console.log(\"Loaded A: \", as2);\n\n}).catch(error => console.log(error));\n```\n\n```text\nInserting a new user into the database...\nquery: SELECT `b`.`id` AS `b_id`, `b`.`name` AS `b_name` FROM `b` `b` INNER JOIN `a` `A` ON `A`.`bId` = `b`.`id` WHERE `A`.`id` IN (?) -- PARAMETERS: [[null]]\nquery: START TRANSACTION\nquery: INSERT INTO `a`(`id`, `name`, `bId`) VALUES (DEFAULT, ?, DEFAULT) -- PARAMETERS: [\"something\"]\nquery: UPDATE `a` SET WHERE `id` = ? -- PARAMETERS: [1]\nquery failed: UPDATE `a` SET WHERE `id` = ? -- PARAMETERS: [1]\n```\n\n```text\n...\n @OneToOne(\n (type: any) => B,\n (o: B) => o.a\n )\n @JoinColumn()\n public b: B;\n}\n```\n\n```text\n...\n @OneToOne(\n (type: any) => A,\n (o: A) => o.b)\n a: A;\n\n}\n```\n\n```text\ncreateConnection().then(async connection => {\n...\n const bCreated = bRepo.create(b);\n bCreated.a = as[0];\n await bRepo.save(bCreated);\n...\n```\n\n```text\nquery: INSERT INTO `b`(`id`, `name`) VALUES (DEFAULT, ?) -- PARAMETERS: [\"something\"]\nquery: UPDATE `a` SET `bId` = ? WHERE `id` = ? -- PARAMETERS: [1,1]\nquery: COMMIT\nquery: SELECT `A`.`id` AS `A_id`, `A`.`name` AS `A_name`, `A`.`bId` AS `A_bId` FROM `a` `A`\n```\n\n```text\nUPDATE `a` SET WHERE `id` = 1\n```\n\n```text\nconst a = new A();\na.name = \"something\";\na.b = null;\nconst aCreated = aRepo.create(a);\nawait aRepo.save(aCreated);\n```\n\n```text\npromise-issue\n```\n\n```text\nUPDATE\n```\n\n```text\nawait aRepo.save(aCreated);\n```\n\n```text\nB\n```\n\n```text\na.b\n```\n\n```text\na.b = null\n```\n\n```text\naRepo.create(a)\n```\n\n```text\na.b = null;\n```\n\n```text\naRepo.create(a)\n```\n\n```text\nUPDATE\n```\n\n```text\nasync\n```\n\n```text\ninverseSide\n```\n\n```text\n@OneToOne()\n```\n\n```text\nasync (o: B) => await o.a)\n```\n\n```text\n(o: B) => o.a\n```\n\n```text\nOneToOne\n```\n\n```text\nasync\n```\n\n```text\nPromise\n```\n\n```text\nclass A\n```\n\n```text\naRepo.create()\n```\n\n```text\naRepo.save(a)\n```\n\n```text\nRepository.create()\n```\n\n```text\n.create()\n```\n\n```text\naCreated\n```\n\n```text\naRepo.save(aCreated)\n```\n\n```text\naRepo.create(a)\n```\n\n```text\nawait aRepo.save(a);\n```\n\n```text\nRepository<T>.create()\n```\n\n```text\ninstanceof T\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeorm@next\n```\n\n```text\nRelationLoader.enableLazyLoad()\n```\n\n```text\nObject.defineProperty(A, 'b', ...)\n```\n\n```text\nB\n```\n\n```text\nPromise<B>\n```\n\n```text\nRepository.create()\n```\n\n```text\nPromise\n```\n\n```text\naRepo.create(a)\n```\n\n```text\nA\n```\n\n```text\nA\n```\n\n```text\nb\n```\n\n```text\nB\n```\n\n```text\nPromise\n```\n\n```text\na.b\n```\n\n```text\nB\n```\n\n```text\nPromise\n```\n\n```text\nB\n```\n\n```text\nid\n```\n\n```text\naRepo.save()\n```\n\n```text\na\n```\n\n```text\naRepo.save()\n```\n\n```text\naRepo.create(a)\n```\n\n```text\nRepository.create()\n```\n\n```text\nawait\n```\n\n```text\nRepository.create()\n```\n\n```js\nimport {\n BaseEntity,\n DeepPartial,\n ObjectType,\n} from 'typeorm';\n\n/**\n * Conditional type that takes a type and maps every property which is\n * a Promise to the unwrapped value of that Promise. Specifically to correct the type\n * of typeorm's create method. Using this otherwise would likely be incredibly unwise.\n *\n * For example this type:\n * {\n * hey: number,\n * thing: Promise<ThingEntity>,\n * sup: string\n * }\n *\n * gets mapped to:\n * {\n * hey: number,\n * thing: ThingEntity,\n * sup: string\n * }\n *\n */\ntype DePromisifyValue<T> = T extends Promise<infer U> ? U : T;\ntype DePromisifyObject<T> = T extends object\n ? { [K in keyof T]: DePromisifyValue<T[K]> }\n : T;\n\nexport abstract class CommonEntity extends BaseEntity {\n static create<T extends CommonEntity>(\n this: ObjectType<T>,\n entityLike?: DeepPartial<DePromisifyObject<T>>\n ): T {\n if (!entityLike) {\n return super.create<T>();\n }\n return super.create<T>(entityLike as DeepPartial<T>);\n }\n}\n```\n\n```text\ncreate\n```\n\n```text\nPromise.resolve\n```\n\n```text\ncreate\n```\n\n```text\ncreate\n```\n\n```text\ncreate\n```\n\n```text\nPromise\n```\n\n```text\nmyLazyLoadedUser: Promise<UserEntity>\n```\n\n```text\nmyLazyLoadedUser: UserEntity\n```\n\n```text\ncreate\n```\n\n```text\nPromise\n```\n\n```text\nBaseEntity\n```\n\n```text\nCommonEntity\n```\n\n```text\nBaseEntity\n```\n\n```text\ncreate\n```\n\n```text\nPromise.resolve\n```\n\n```text\nPromise\n```\n\n```text\ncreate\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":83,"totalLines":669,"estimatedTokens":3108}}288{"id":"stack-60939232","source":"stackoverflow","questionId":60939232,"title":"In TypeORM how do I have a pre-calculated field on an Entity based on other fields of that Entity?","tags":["javascript","sql","typescript","sequelize.js","typeorm"],"text":"Title: In TypeORM how do I have a pre-calculated field on an Entity based on other fields of that Entity?\nTags: javascript, sql, typescript, sequelize.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to make a 'rating' field on my User Entity.\nThe User Entity has a relationship to the Rating Entity, on User there is a field called ratingsReceived, which is an eager load of all Ratings assigned to that User.\n\nI want the 'rating' field on User to be a mean calculation of all rating values which is a field on Rating Entity called 'ratingValue'.\n\nSo essentially I want this calculation to be the value of every User 'rating' field:\n\n`ratingsReceived.reduce((acc, curr) => acc + curr.ratingValue, 0) / ratingsReceived.length`\n\nThe fields in question are 'ratingsReceived' on User:\n\n```\n@OneToMany(\n () => Rating,\n rating => rating.ratingTo\n )\n ratingsReceived: Rating[];\n```\n\nAnd 'ratingValue' on Rating:\n\n```\n@Column('decimal')\n @Min(0)\n @Max(5)\n ratingValue: number;\n```\n\n========================================\n\nCode:\n```text\n@OneToMany(\n () => Rating,\n rating => rating.ratingTo\n )\n ratingsReceived: Rating[];\n```\n\n```text\n@Column('decimal')\n @Min(0)\n @Max(5)\n ratingValue: number;\n```\n\n```text\nratingsReceived.reduce((acc, curr) => acc + curr.ratingValue, 0) / ratingsReceived.length\n```\n\n```text\n// After load is called after the entity loads during find() and similar\n// I placed this decorator on my User Entity\n@AfterLoad()\n calculateRating = async () => {\n const result = await getRepository(Rating)\n .createQueryBuilder('ratings')\n .where('ratings.\"ratingToId\" = :id', { id: this.id })\n .getRawAndEntities();\n\n const ratingsAboveZero = result?.entities?.filter(x => parseFloat(x.ratingValue));\n const count = ratingsAboveZero.length;\n\n if (count > 0) {\n this.rating =\n ratingsAboveZero.reduce((acc, curr) => {\n return acc + parseFloat(curr.ratingValue);\n }, 0) / count;\n\n this.ratingCount = count;\n } else {\n this.rating = 0;\n this.ratingCount = 0;\n }\n };\n```\n\n========================================\n\nComments:\n- typeorm.io/listeners-and-subscribers","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":86,"estimatedTokens":540}}289{"id":"stack-58983386","source":"stackoverflow","questionId":58983386,"title":"Is it possible to add table prefixes for uuids in TypeORM?","tags":["javascript","database","typescript","uuid","typeorm"],"text":"Title: Is it possible to add table prefixes for uuids in TypeORM?\nTags: javascript, database, typescript, uuid, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a lot of UUIDs in various places throughout my database, and the readability would be significantly improved if they contained a prefix to denote the type of entity they are for, such as `user-09a9c8fb-dcb6-5d18-9697-e1d10c552c14` or `comment-c80c8502-4cd9-483f-9b81-705a22dba3a8`. Is there any way to accomplish this purely with TypeORM syntax?\n\nHere is an example of my current user model:\n\n```\nimport {\n Entity,\n PrimaryGeneratedColumn,\n Column,\n CreateDateColumn,\n} from 'typeorm';\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column({ unique: true })\n username: string;\n\n @Column()\n email: string;\n\n @CreateDateColumn()\n createdAt: Date;\n}\n```\n\n========================================\n\nCode:\n```text\nimport {\n Entity,\n PrimaryGeneratedColumn,\n Column,\n CreateDateColumn,\n} from 'typeorm';\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column({ unique: true })\n username: string;\n\n @Column()\n email: string;\n\n @CreateDateColumn()\n createdAt: Date;\n}\n```\n\n```text\nuser-09a9c8fb-dcb6-5d18-9697-e1d10c552c14\n```\n\n```text\ncomment-c80c8502-4cd9-483f-9b81-705a22dba3a8\n```\n\n```text\nconst generatePrefixedUUID = (prefix: string = \"\"): string => {\n return prefix + uuidv4().slice(prefix.length);\n};\n```\n\n```text\n@PrimaryColumn({\n name: \"id\",\n unique: true,\n})\nid: string = generatePrefixedUUID(\"OR#\");\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":81,"estimatedTokens":387}}290{"id":"stack-64561818","source":"stackoverflow","questionId":64561818,"title":"How do insert multiple entities and return them in TypeORM","tags":["node.js","express","graphql","typeorm"],"text":"Title: How do insert multiple entities and return them in TypeORM\nTags: node.js, express, graphql, typeorm\nSource: Stack Overflow\n\nQuestion:\nLet's say i have a Vote entity. I want to insert an array with 5 votes simultaneously and return them. I have tried : await Vote.save(votes) but that doesnt work and it doesnt return them either. Any ideas?\n\n========================================\n\nCode:\n```text\nconst votesEntities = Vote.create(votes);\n```\n\n```text\nawait Vote.save(votesEntities);\n```\n\n```text\nasync insertVotes(votes) {\n const votesEntities = Vote.create(votes);\n await Vote.insert(votesEntities);\n return votesEntities;\n}\n```\n\n```text\ninsert\n```\n\n```text\nsave\n```\n\n```text\nsave\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":37,"estimatedTokens":175}}291{"id":"stack-61837126","source":"stackoverflow","questionId":61837126,"title":"How to update with returning values in TypeORM?","tags":["postgresql","typeorm"],"text":"Title: How to update with returning values in TypeORM?\nTags: postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI wanted to update values and to return specified columns with PostgreSQL.\n\nSo far, what I found was update the value then use `findOne`, but then again it will always use two queries to achieve what I want.\n\nAnother is using RAW SQL, `UPDATE ... SET ... WHERE ... RETURNING *` and this seems a great solution so is there a way to achieve this with TypeORM using `UpdateQueryBuilder`?\n\n========================================\n\nTop Answer:\nIf using repository, this is slightly modified answer and inspired from Noam's answer:\n\n```\nimport {\n EntityRepository,\n Repository,\n} from \"typeorm\";\nimport { User } from \"../entities/user\";\n\n@EntityRepository(User)\nexport class UserRepository extends Repository {\n \n // ... other functions\n\n updateUser = async (payload: User, id: string): Promise => {\n const updatedData = await this.createQueryBuilder(\"user\")\n .update(User, { ...payload })\n .where(\"user.id = :id\", { id: id })\n .returning(\"*\") // returns all the column values\n .updateEntity(true)\n .execute();\n return updatedData.raw[0];\n };\n}\n```\n\n========================================\n\nCode:\n```text\nfindOne\n```\n\n```text\nUPDATE ... SET ... WHERE ... RETURNING *\n```\n\n```text\nUpdateQueryBuilder\n```\n\n```text\nconst firstUser = await connection\n .getRepository(User)\n .createQueryBuilder(\"user\")\n .update<User>(User, {firstName: 'new first name'})\n .where(\"user.id = :id\", { id: 1 })\n .returning(['id', 'email'])\n .updateEntity(true)\n .execute();\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\nBaseEntity\n```\n\n```text\nRepository\n```\n\n```text\nEntityManager\n```\n\n```js\nimport {\n EntityRepository,\n Repository,\n} from \"typeorm\";\nimport { User } from \"../entities/user\";\n\n@EntityRepository(User)\nexport class UserRepository extends Repository<User> {\n \n // ... other functions\n\n updateUser = async (payload: User, id: string): Promise<User> => {\n const updatedData = await this.createQueryBuilder(\"user\")\n .update<User>(User, { ...payload })\n .where(\"user.id = :id\", { id: id })\n .returning(\"*\") // returns all the column values\n .updateEntity(true)\n .execute();\n return updatedData.raw[0];\n };\n}\n```\n\n```js\nasync updateFirstName(entity: YourEntity) {\n await YourEntity.createQueryBuilder()\n .update(entity)\n .set({ firstName: 'newFirstName' })\n .whereEntity(entity)\n .returning('*')\n .execute();\n\n return entity;\n}\n```\n\n```text\nraw[0]\n```\n\n========================================\n\nComments:\n- Thanks. Now the prolem is mapping the `UpdateResult` to like User entity. I used `.createQueryBuilder(\"user\").create(firstUser.raw)[0]` to get back the entity. Do you have any other solution?\n- You can extend the entity's class with `BaseEntity` (link below) and implement it this way: `User.create(updateResult.raw[0])` github.com/typeorm/typeorm/blob/master/docs/…\n- `.returning(*}` doesn't work with all DBs, but this is a neat answer. thanks for sharing","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":129,"estimatedTokens":773}}292{"id":"stack-64293388","source":"stackoverflow","questionId":64293388,"title":"Store array of string in typeorm postgres database","tags":["sql","postgresql","typeorm"],"text":"Title: Store array of string in typeorm postgres database\nTags: sql, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI would like to store an array of strings in my Postgres database, I have the below code but it is not working as I want:\n\n```\n@Column({type: 'text', array: true, nullable: true })\n names: string[] = [];\n```\n\nI got the following error:\n\n```\nPostgreSQL said: malformed array literal: \"[\"james\"]\"\nDetail: \"[\" must introduce explicitly-specified array dimensions.\n```\n\nAnything I might be doing wrong?\n\n========================================\n\nTop Answer:\nThis should work for an array.\n\n```\n@Column('text', { array: true })\nnames: string[];\n```\n\n========================================\n\nCode:\n```text\n@Column({type: 'text', array: true, nullable: true })\n names: string[] = [];\n```\n\n```text\nPostgreSQL said: malformed array literal: \"[\"james\"]\"\nDetail: \"[\" must introduce explicitly-specified array dimensions.\n```\n\n```text\n@Column('simple-array', { nullable: true, array: true })\n city: string[];\n```\n\n```text\n@Column('text', { array: true })\nnames: string[];\n```\n\n========================================\n\nComments:\n- In my case TypeORM saved string as \"{\"a\", \"b\", \"c\"}\" and could not parse it properly when fetched from DB. What helped was adding `array: true` to column definition: `@Column({type: \"simple-array\", array: true})`","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":58,"estimatedTokens":340}}293{"id":"stack-72152136","source":"stackoverflow","questionId":72152136,"title":"NestJS microservices \"Cannot find module\"","tags":["node.js","module","nestjs","typeorm","node.js-typeorm"],"text":"Title: NestJS microservices \"Cannot find module\"\nTags: node.js, module, nestjs, typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nSo, I'm trying to create my first microservice using NestJS, but the moment I try to run it, the service stops with this error:\n\n```\n[13:39:21] Found 0 errors. Watching for file changes.\n\nError: Cannot find module 'C:\\Users\\voryi\\IdeaProjects\\YWA\\des_server\\services\\learning-service\\dist\\main'\n at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)\n at Function.Module._load (node:internal/modules/cjs/loader:778:27)\n at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)\n at node:internal/main/run_main_module:17:47\n```\n\n========================================\n\nTop Answer:\ntry `npm run build` and then restart your service\n\n========================================\n\nCode:\n```text\n[13:39:21] Found 0 errors. Watching for file changes.\n\nError: Cannot find module 'C:\\Users\\voryi\\IdeaProjects\\YWA\\des_server\\services\\learning-service\\dist\\main'\n at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)\n at Function.Module._load (node:internal/modules/cjs/loader:778:27)\n at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)\n at node:internal/main/run_main_module:17:47\n```\n\n```text\nmain.js\n```\n\n```text\ndist\n```\n\n```text\nnest-cli.json\n```\n\n```text\n\"entryFile\": \"learning-service/src/main\"\n```\n\n```text\nmain\n```\n\n```text\nnpm run build\n```\n\n```text\n\"start:prod\": \"node dist/src/main\"\n```\n\n```text\nnpm i @nestjs/microservices\n```\n\n========================================\n\nComments:\n- looks like you're trying to run `node dist/main.js` while there's no `main.js`. Check out your `dist` directory\n- It actually does generate the main, but I guess that for some reason it can't see/read it... prnt.sc/AZ4-4f7XCI6p\n- there's no `main.js` in the first level of `dist` directory, tho. You can define the entry file by adding this to your `nest-cli.json`: `\"entryFile\": \"learning-service/src/main\"`\n- Thanks a lot! Could you tell me please where can I read how it works so when I face +/- the same problem I'll be able o solve it myself?\n- I guess you just need to know how typescript define the destination of your transpiled code. Learn about the following compiler options: `baseUrl`, `rootDir` and `outDir` at typescriptlang.org/docs/handbook/compiler-options.html\n- Thanks once again! How can I mark the question as solved? Or it's some mod's function that only they can do? If so, shouldn't you post it as an answer rather than comment so it can be marked as an appropriate one? Sorry, just some questions from the newbie xd\n- you can mark my answer as the right one :)\n- Didn't work. Gives the same error. But thanks for trying!\n- For my case, this is the actual answer\n- Adding an `entryFile` field solved the issue for my monolith.","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":80,"estimatedTokens":727}}294{"id":"stack-54280856","source":"stackoverflow","questionId":54280856,"title":"TypeOrm: Create a ManyToOne relationship using uuid data type for the keys instead of integer","tags":["node.js","postgresql","typescript","nestjs","typeorm"],"text":"Title: TypeOrm: Create a ManyToOne relationship using uuid data type for the keys instead of integer\nTags: node.js, postgresql, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a Typescript Nestjs project using TypeORM and a PostgreSQL database, and I have trouble defining many-to-one relationships, because TypeORM tries to create an ID field of type integer, whereas I'm using UUID fields. Is there a way to tell TypeORM to use a different data-type than integer?\n\nHere's an example of an entity that's not working:\n\n```\nexport class AgentKitsEntity implements Model {\n @PrimaryGeneratedColumn()\n @Generated('uuid')\n id: string;\n}\n\n@Entity({name: 'users'})\nexport class User extends AgentKitsEntity implements UserModel {\n @Column()\n username: string;\n\n @ManyToOne(type => View)\n @JoinColumn({name: 'view_id', referencedColumnName: 'id'})\n view: View;\n}\n```\n\nThis leads to the following error:\n\n```\nquery failed: ALTER TABLE \"users\" ADD CONSTRAINT \"FK_2ed8b186dce83a446f94ac9aae4\" FOREIGN KEY (\"view_id\") REFERENCES \"views\"(\"id\")\nerror: { error: foreign key constraint \"FK_2ed8b186dce83a446f94ac9aae4\" cannot be implemented\n at Connection.parseE (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:554:11)\n at Connection.parseMessage (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:379:19)\n at Socket. (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:119:22)\n at emitOne (events.js:116:13)\n at Socket.emit (events.js:211:7)\n at addChunk (_stream_readable.js:263:12)\n at readableAddChunk (_stream_readable.js:250:11)\n at Socket.Readable.push (_stream_readable.js:208:10)\n at TCP.onread (net.js:601:20)\n name: 'error',\n length: 228,\n severity: 'ERROR',\n code: '42804',\n detail: 'Key columns \"view_id\" and \"id\" are of incompatible types: integer and uuid.',\n hint: undefined,\n position: undefined,\n internalPosition: undefined,\n internalQuery: undefined,\n where: undefined,\n schema: undefined,\n table: undefined,\n column: undefined,\n dataType: undefined,\n constraint: undefined,\n file: 'tablecmds.c',\n line: '6503',\n routine: 'ATAddForeignKeyConstraint' }\n```\n\nEDIT: Just to be clear, the issue isn't creating the UUID field for the primary key, that's working. The issue is that the table I'm referencing (in this example, \"views\"), uses a UUID primary key, so I need to use a UUID for the field referencing it as well (\"views\", in this example). TypeORM automatically creates the \"view_id\" field with an integer type, presumably because it assumes that primary key values will (should?) always be integers (which strikes me as a pretty crazy assumption). \n\nIt must be configurable somehow, no?\n\n========================================\n\nTop Answer:\nYou define `@PrimaryGeneratedColumn()` in schemas, which defaults to an integer sequence in postgres. The @Generated('uuid') doesn't change the column type. This decorator just tell to generate uuid instead of integer incrementation.\n\nCorrect way:\n\n```\nexport class AgentKitsEntity implements Model {\n @PrimaryGeneratedColumn('uuid')\n @Generated('uuid')\n id: string;\n}\n```\n\nWhen you create a primary key in TypeORM, you can use `@PrimaryGeneratedColumn('uuid')` to make the ID a UUID instead of a number. This ensures that in all related tables, TypeORM will automatically use UUIDs for the relationships.\n\n**But be careful:** UUIDs in PostgreSQL often need the `uuid-ossp` extension, and some cloud database providers don’t include it by default. So this will throw an error.\n\n========================================\n\nCode:\n```text\nexport class AgentKitsEntity implements Model {\n @PrimaryGeneratedColumn()\n @Generated('uuid')\n id: string;\n}\n\n@Entity({name: 'users'})\nexport class User extends AgentKitsEntity implements UserModel {\n @Column()\n username: string;\n\n @ManyToOne(type => View)\n @JoinColumn({name: 'view_id', referencedColumnName: 'id'})\n view: View;\n}\n```\n\n```text\nquery failed: ALTER TABLE \"users\" ADD CONSTRAINT \"FK_2ed8b186dce83a446f94ac9aae4\" FOREIGN KEY (\"view_id\") REFERENCES \"views\"(\"id\")\nerror: { error: foreign key constraint \"FK_2ed8b186dce83a446f94ac9aae4\" cannot be implemented\n at Connection.parseE (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:554:11)\n at Connection.parseMessage (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:379:19)\n at Socket.<anonymous> (/home/jonathan/projects/agent-kits/api-data/node_modules/pg/lib/connection.js:119:22)\n at emitOne (events.js:116:13)\n at Socket.emit (events.js:211:7)\n at addChunk (_stream_readable.js:263:12)\n at readableAddChunk (_stream_readable.js:250:11)\n at Socket.Readable.push (_stream_readable.js:208:10)\n at TCP.onread (net.js:601:20)\n name: 'error',\n length: 228,\n severity: 'ERROR',\n code: '42804',\n detail: 'Key columns \"view_id\" and \"id\" are of incompatible types: integer and uuid.',\n hint: undefined,\n position: undefined,\n internalPosition: undefined,\n internalQuery: undefined,\n where: undefined,\n schema: undefined,\n table: undefined,\n column: undefined,\n dataType: undefined,\n constraint: undefined,\n file: 'tablecmds.c',\n line: '6503',\n routine: 'ATAddForeignKeyConstraint' }\n```\n\n```js\nexport class AgentKitsEntity implements Model {\n @PrimaryGeneratedColumn('uuid')\n @Generated('uuid')\n id: string;\n}\n\n@Entity({name: 'users'})\nexport class User extends AgentKitsEntity implements UserModel {\n\n @Column()\n username: string;\n\n @ManyToOne(type => View, { nullable: true })\n @JoinColumn({name: 'view_id'})\n view: View;\n}\n```\n\n```js\nexport class AgentKitsEntity implements Model {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n}\n```\n\n```text\n@PrimaryGeneratedColumn()\n```\n\n```text\n@Generated('uuid')\n```\n\n```text\nexport class AgentKitsEntity implements Model {\n @PrimaryGeneratedColumn('uuid')\n @Generated('uuid')\n id: string;\n}\n```\n\n```text\n@PrimaryGeneratedColumn()\n```\n\n```text\n@PrimaryGeneratedColumn('uuid')\n```\n\n```text\nuuid-ossp\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.705Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":190,"estimatedTokens":1505}}295{"id":"stack-70108473","source":"stackoverflow","questionId":70108473,"title":"Pagination in TypeORM/NestJS","tags":["javascript","orm","nestjs","backend","typeorm"],"text":"Title: Pagination in TypeORM/NestJS\nTags: javascript, orm, nestjs, backend, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have to introduce pagination in `findAll()` method. I really dont know how to do it. I tried but it is giving so many errors. I used `findAndCount()` method given by `typeorm` for that, But I am not sure how it will work.\n\nAs of now below method returning all the record. I need to return at a time 10 records. Please suggest what modification I need to do.\n\n```\nasync findAll(queryCertificateDto: QueryCertificateDto,page=1): Promise {\n \n let { country, sponser } = queryCertificateDto;\n\n const query = this.certificateRepository.createQueryBuilder('certificate');\n\n if (sponser) {\n sponser = sponser.toUpperCase();\n query.andWhere('Upper(certificate.sponser)=:sponser', { sponser });\n }\n\n if (country) {\n country = country.toUpperCase();\n query.andWhere('Upper(certificate.country)=:country', { country });\n } \n const certificates = query.getMany(); \n return certificates;\n}\n```\n\nthis is `PaginatedResult` file.\n\n```\nexport class PaginatedResult {\n data: any[];\n meta: {\n total: number;\n page: number;\n last_page: number;\n };\n }\n```\n\nI tried changing code of `findAll()` but `where` clause is giving error. I am not sure how to handle `query.getMany()` in `pagination`.\n\n```\nconst take = query.take || 10\n const skip = query.skip || 0\n \n \n const [result, total] = await this.certificateRepository.findAndCount(\n {\n where: query.getMany(), //this is giving error\n take:take,\n skip:skip\n }\n );\n return result;\n```\n\nI need to introduce pagination in this method. Any help will be really helpful.\n\n========================================\n\nTop Answer:\nTypeorm has a really nice method specific to your usecase `findAndCount`\n\n```\nasync findAll(queryCertificateDto: QueryCertificateDto): Promise {\n\n const take = queryCertificateDto.take || 10\n const skip = queryCertificateDto.skip || 0\n const country = queryCertificateDto.keyword || ''\n const sponser = queryCertificateDto.sponser || ''\n \n\n const query = this.certificateRepository.createQueryBuilder('certificate');\n\n const [result, total] = await this.certificateRepository.findAndCount(\n {\n where: { country: Like('%' + country + '%') AND sponser: Like('%' + sponser + '%') }, order: { name: \"DESC\" },\n take: take,\n skip: skip\n }\n );\n \n return {\n data: result,\n count: total\n };\n}\n```\n\nMore documentation about Repository class can be found here\n\n========================================\n\nCode:\n```text\nasync findAll(queryCertificateDto: QueryCertificateDto,page=1): Promise<PaginatedResult> {\n \n let { country, sponser } = queryCertificateDto;\n\n const query = this.certificateRepository.createQueryBuilder('certificate');\n\n if (sponser) {\n sponser = sponser.toUpperCase();\n query.andWhere('Upper(certificate.sponser)=:sponser', { sponser });\n }\n\n if (country) {\n country = country.toUpperCase();\n query.andWhere('Upper(certificate.country)=:country', { country });\n } \n const certificates = query.getMany(); \n return certificates;\n}\n```\n\n```text\nexport class PaginatedResult {\n data: any[];\n meta: {\n total: number;\n page: number;\n last_page: number;\n };\n }\n```\n\n```text\nconst take = query.take || 10\n const skip = query.skip || 0\n \n \n const [result, total] = await this.certificateRepository.findAndCount(\n {\n where: query.getMany(), //this is giving error\n take:take,\n skip:skip\n }\n );\n return result;\n```\n\n```text\nfindAll()\n```\n\n```text\nfindAndCount()\n```\n\n```text\ntypeorm\n```\n\n```text\nPaginatedResult\n```\n\n```text\nfindAll()\n```\n\n```text\nwhere\n```\n\n```text\nquery.getMany()\n```\n\n```text\npagination\n```\n\n```text\nasync findAll(queryCertificateDto: QueryCertificateDto,page=1): Promise<PaginatedResult> {\n // let's say limit and offset are passed here too\n let { country, sponser, limit, offset } = queryCertificateDto;\n\n const query = this.certificateRepository.createQueryBuilder('certificate');\n\n if (sponser) {\n sponser = sponser.toUpperCase();\n query.andWhere('certificate.sponser = :sponser', { sponser });\n }\n\n if (country) {\n country = country.toUpperCase();\n query.andWhere('certificate.country = :country', { country });\n }\n\n // limit and take mean the same thing, while skip and offset mean the same thing\n const certificates = await query\n .orderBy(\"certificate.id\", \"ASC\")\n .limit(limit || 10)\n .offset(offset || 0)\n .getMany();\n\n // if you want to count just replace the `.getMany()` with `.getManyandCount()`;\n\n return certificates;\n}```\n```\n\n```text\n.getMany()\n```\n\n```text\nwhere\n```\n\n```js\nasync findAll(queryCertificateDto: QueryCertificateDto): Promise<PaginatedResult> {\n\n const take = queryCertificateDto.take || 10\n const skip = queryCertificateDto.skip || 0\n const country = queryCertificateDto.keyword || ''\n const sponser = queryCertificateDto.sponser || ''\n \n\n const query = this.certificateRepository.createQueryBuilder('certificate');\n\n const [result, total] = await this.certificateRepository.findAndCount(\n {\n where: { country: Like('%' + country + '%') AND sponser: Like('%' + sponser + '%') }, order: { name: \"DESC\" },\n take: take,\n skip: skip\n }\n );\n \n return {\n data: result,\n count: total\n };\n}\n```\n\n```text\nfindAndCount\n```\n\n========================================\n\nComments:\n- `where` clause is generally for providing a conditon. In your case `query.getMany()` does not not provides a condition.\n- I am struggling there only Tushar. Can you guide me how can I use the same method in my code? I have put the code which I tried to use but dint work. I have edited my question.\n- why do you need the query var? I don't see that you are using it afterwards\n- thanks. it is returning every time only first 10 records.\n- you're are welcome, if you want more records, just pass the limit as a query with the number of records you need and it will override the default limit which is 10, 10 is the default value, so if you don't pass any specific limit it will return 10 records. so for example, if you want 40 records, and you want it to start from an id of 11 the offset will be 10 and the limit will be 40. In a nutshell, having a limit is just saying I don't want more than this number of values, while offset is saying skip this number of records and start from here.\n- and because databases id's start from 1. An Offset of 0 while will start from 1 because you are saying skip 0 rows, likewise, 10 will start from 11, saying skip 10 rows\n- actually I am not using id which starts from 1. I am using id as uuid. which is alphanumeric number\n- Yes, it will still work.","metadata":{"transformedAt":"2026-08-18T18:33:44.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":256,"estimatedTokens":1722}}296{"id":"stack-56617592","source":"stackoverflow","questionId":56617592,"title":"TypeORM - How to create new table and run migration automatically in production mode?","tags":["mysql","node.js","express","typeorm"],"text":"Title: TypeORM - How to create new table and run migration automatically in production mode?\nTags: mysql, node.js, express, typeorm\nSource: Stack Overflow\n\nQuestion:\nI would like to create new table in MySQL and run TypeORM migration automatically when application running in production mode.\n\n**Note: This new table is not created prior starting of application in production mode.**\n\nAccording to Migration Documentation, it need to use **typeorm migration:run** command to run migration.\n\nDue to my new table only created when application called **CreateNewTableTimeStamp(inputTableName).up**, at this point it will trigger to create new table into my database.\n\nBut I found no solution how to do this migration automatically, since it is impossible for me to run **typeorm migration:run** manually each time application called this method to create new table.\n\nAfter this table is created, I will write new data into this new table afterwards.\n\nCould anyone assist on this issue?\n\nThanks.\n\n**My New Table Code:**\n\n```\nclass CreateNewTableTimeStamp implements MigrationInterface {\n\n tableName: string;\n\n constructor (inputTableName: string) {\n this.tableName = inputTableName\n }\n\n async up(queryRunner: QueryRunner): Promise {\n await queryRunner.createTable(new Table({\n name: this.tableName,\n columns: [\n {\n name: \"id\",\n type: \"int\",\n isPrimary: true\n },\n {\n name: \"email\",\n type: \"varchar\",\n }\n ]\n }), true)\n }\n\n async down(queryRunner: QueryRunner): Promise {\n const table = await queryRunner.getTable(this.tableName);\n await queryRunner.dropTable(this.tableName);\n }\n}\n```\n\n========================================\n\nTop Answer:\nFor people wanting to run migrations for the purpose of Testing and\nNOT in production environment.\n\n```\nimport {\n createConnection,\n ConnectionOptions,\n Connection,\n} from 'typeorm';\n\nimport { YourEntity } from 'path/to/your/entity.ts';\n\nconst testConfig: ConnectionOptions = {\n type: 'mongodb',\n url: 'mongodb://localhost:27017',\n database: 'test',\n useUnifiedTopology: true,\n entities: [YourEntity],\n synchronize: true,\n migrations: ['migrations/*YourMigrations.ts'],\n};\n\nlet connection: Connection;\n\nconnection = await createConnection({ ...testConfig });\nawait connection.synchronize(true);\n\nawait connection.runMigrations({\n transaction: 'all',\n});\n```\n\nRun using:\n\n```\nnode -r ts-node/register ./path/to/migrations.ts\n```\n\nor\n\n```\nnode ./path/to/compiled/migrations.js\n```\n\n========================================\n\nCode:\n```text\nclass CreateNewTableTimeStamp implements MigrationInterface {\n\n tableName: string;\n\n constructor (inputTableName: string) {\n this.tableName = inputTableName\n }\n\n async up(queryRunner: QueryRunner): Promise<any> {\n await queryRunner.createTable(new Table({\n name: this.tableName,\n columns: [\n {\n name: \"id\",\n type: \"int\",\n isPrimary: true\n },\n {\n name: \"email\",\n type: \"varchar\",\n }\n ]\n }), true)\n }\n\n async down(queryRunner: QueryRunner): Promise<any> {\n const table = await queryRunner.getTable(this.tableName);\n await queryRunner.dropTable(this.tableName);\n }\n}\n```\n\n```text\nimport {\n createConnection,\n ConnectionOptions,\n Connection,\n} from 'typeorm';\n\nimport { YourEntity } from 'path/to/your/entity.ts';\n\nconst testConfig: ConnectionOptions = {\n type: 'mongodb',\n url: 'mongodb://localhost:27017',\n database: 'test',\n useUnifiedTopology: true,\n entities: [YourEntity],\n synchronize: true,\n migrations: ['migrations/*YourMigrations.ts'],\n};\n\nlet connection: Connection;\n\nconnection = await createConnection({ ...testConfig });\nawait connection.synchronize(true);\n\nawait connection.runMigrations({\n transaction: 'all',\n});\n```\n\n```text\nnode -r ts-node/register ./path/to/migrations.ts\n```\n\n```text\nnode ./path/to/compiled/migrations.js\n```\n\n```text\nimport { MigrationInterface, QueryRunner, Table } from 'typeorm';\n\nexport class createUsers1585025619325 implements MigrationInterface {\n private table = new Table({\n name: 'users',\n columns: [\n {\n name: 'id',\n type: 'integer',\n isPrimary: true,\n isGenerated: true, // Auto-increment\n generationStrategy: 'increment',\n },\n {\n name: 'email',\n type: 'varchar',\n length: '255',\n isUnique: true,\n isNullable: false,\n },\n {\n name: 'created_at',\n type: 'timestamptz',\n isNullable: false,\n default: 'now()',\n },\n {\n name: 'updated_at',\n type: 'timestamptz',\n isNullable: false,\n default: 'now()',\n },\n ],\n });\n\n public async up(queryRunner: QueryRunner): Promise<any> {\n await queryRunner.createTable(this.table);\n }\n public async down(queryRunner: QueryRunner): Promise<any> {\n await queryRunner.dropTable(this.table);\n }\n}\n```\n\n```text\nyarn typeorm migration:run\n```\n\n```text\nyarn typeorm migration:create -n users\n```\n\n========================================\n\nComments:\n- I would not recommand running migrations from your server code, it should be done before launching your node server with a CLI command. It is best to not bring a hard dependency between code and SQL migration structure as code would evolve, and the migration should always be immutable and replayed. I would encourage you to generate raw SQL queries so no \"code\" is executed (imagine TypeOrm changes its way to execute queryRunner, your migration could become mutable depending on the version of TypeOrm!).\n- @zenbeni, thanks for your advice. Will change my design not to do migrations from my server code.\n- This workaround looks nice but can you explain why is not a good practice synchronize the database on production runtime?\n- The issue is not about synchronising the data in production. It's more about how do you want to do it production. This script is about updating the migrations manually - meaning by calling a script from terminal to update the db. I believe this must be done using: - the automatic way of running migrations that stores the migration info in db. - must be in consultation by how your devops team wants to handle the changes to DB. Many times the app is not allowed to drop or create collections/indexes.\n- this is not automatically generation method","metadata":{"transformedAt":"2026-08-18T18:33:44.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":237,"estimatedTokens":1590}}297{"id":"stack-76741461","source":"stackoverflow","questionId":76741461,"title":"Nest.js + TypeORM. TypeORM didn't see .env file","tags":["typescript","environment-variables","nestjs","typeorm","cross-env"],"text":"Title: Nest.js + TypeORM. TypeORM didn't see .env file\nTags: typescript, environment-variables, nestjs, typeorm, cross-env\nSource: Stack Overflow\n\nQuestion:\nI have some issue about typeorm migrations. I have typeorm config (see below).\n\n`data-source.ts`:\n\n```\nimport { DataSource, DataSourceOptions } from 'typeorm';\n\nexport const dataSourceOptions: DataSourceOptions = {\n type: 'postgres',\n host: process.env.POSTGRES_HOST,\n port: +process.env.POSTGRES_PORT,\n username: process.env.POSTGRES_USERNAME,\n password: process.env.POSTGRES_PASSWORD,\n database: process.env.POSTGRES_DATABASE,\n entities: ['dist/**/*.entity.js'],\n migrations: ['dist/db/migrations/*.js'],\n synchronize: true,\n};\n\nconst dataSource = new DataSource(dataSourceOptions);\nexport default dataSource;\n```\n\nAnd when I'm trying to start migrations, typeorm throws an error (but if I replace process.env with normal string, it works).\n\nI attached scripts from package.json\n\n```\n\"build\": \"nest build\",\n\"start\": \"cross-env NODE_ENV=production nest start\",\n\"start:dev\": \"cross-env NODE_ENV=development nest start --watch\",\n\"typeorm\": \"npm run build && npx typeorm -d dist/db/data-source.js\",\n\"migration:generate\": \"npm run typeorm -- migration:generate\",\n\"migration:run\": \"npm run typeorm -- migration:run\",\n\"migration:down\": \"npm run typeorm -- migration:revert\"\n```\n\nI need the config to see data from env during migrations.\n\nMaybe this is caused by the fact that I use cross env. And I read it like this\n\n`App.module.ts`:\n\n```\n@Module({\n imports: [\n...\n ConfigModule.forRoot({\n envFilePath: `.${process.env.NODE_ENV}.env`,\n }),\n ],\n...\n controllers: [],\n providers: [],\n})\nexport class AppModule {}\n```\n\nAnyway,I hope for your help\n\n========================================\n\nTop Answer:\nTo deal with commandline migrations, you can use an additional `typeorm.config.ts` file on the root directory.\n\n```\nimport { DataSource, DataSourceOptions } from 'typeorm';\nimport { config } from 'dotenv';\nimport { resolve } from 'path';\n\nconfig({ path: resolve(__dirname, '.env') });\n\nconst DataSourceConfig = new DataSource({\n type: 'mysql',\n host: process.env.TYPEORM_HOST,\n port: Number(process.env.TYPEORM_PORT),\n username: process.env.TYPEORM_USERNAME,\n password: process.env.TYPEORM_PASSWORD,\n database: process.env.TYPEORM_DATABASE,\n migrations: ['./database/migrations/*'],\n synchronize: false,\n extra: {\n charset: 'utf8mb4',\n },\n migrationsTableName: 'migrations',\n});\n\nexport default DataSourceConfig;\n```\n\nAnd to use typeorm inside NestJS app, create a `typeorm.service.js` file.\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm';\n\n@Injectable()\nexport class TypeOrmConfigService implements TypeOrmOptionsFactory {\n constructor(private configService: ConfigService) {}\n\n public createTypeOrmOptions(): TypeOrmModuleOptions {\n return {\n type: 'mysql',\n host: this.configService.get('TYPEORM_HOST'),\n port: this.configService.get('TYPEORM_PORT'),\n username: this.configService.get('TYPEORM_USERNAME'),\n password: this.configService.get('TYPEORM_PASSWORD'),\n database: this.configService.get('TYPEORM_DATABASE'),\n autoLoadEntities: true,\n };\n }\n}\n```\n\nAnd load this service in `app.module.ts` file\n\n```\n@Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n TypeOrmModule.forRootAsync({ useClass: TypeOrmConfigService }),\n ]\n});\nexport class AppModule {}\n```\n\nAnd then inside `package.json` file, define the commands. Note that I'm using the `typeorm-ts-node-commonjs` package because my `typeorm.config.js` file is in Typescript.\n\n```\n\"migration:run\": \"typeorm-ts-node-commonjs -d typeorm.config.ts migration:run\",\n\"migration:create\": \"cd database/migrations && typeorm-ts-node-commonjs migration:create\",\n\"migration:revert\": \"typeorm-ts-node-commonjs -d typeorm.config.ts migration:revert\"\n```\n\n========================================\n\nCode:\n```text\nimport { DataSource, DataSourceOptions } from 'typeorm';\n\nexport const dataSourceOptions: DataSourceOptions = {\n type: 'postgres',\n host: process.env.POSTGRES_HOST,\n port: +process.env.POSTGRES_PORT,\n username: process.env.POSTGRES_USERNAME,\n password: process.env.POSTGRES_PASSWORD,\n database: process.env.POSTGRES_DATABASE,\n entities: ['dist/**/*.entity.js'],\n migrations: ['dist/db/migrations/*.js'],\n synchronize: true,\n};\n\nconst dataSource = new DataSource(dataSourceOptions);\nexport default dataSource;\n```\n\n```text\n\"build\": \"nest build\",\n\"start\": \"cross-env NODE_ENV=production nest start\",\n\"start:dev\": \"cross-env NODE_ENV=development nest start --watch\",\n\"typeorm\": \"npm run build && npx typeorm -d dist/db/data-source.js\",\n\"migration:generate\": \"npm run typeorm -- migration:generate\",\n\"migration:run\": \"npm run typeorm -- migration:run\",\n\"migration:down\": \"npm run typeorm -- migration:revert\"\n```\n\n```text\n@Module({\n imports: [\n...\n ConfigModule.forRoot({\n envFilePath: `.${process.env.NODE_ENV}.env`,\n }),\n ],\n...\n controllers: [],\n providers: [],\n})\nexport class AppModule {}\n```\n\n```text\ndata-source.ts\n```\n\n```text\nApp.module.ts\n```\n\n```text\nnpx typeorm ...\n```\n\n```text\nConfigModule.forRoot\n```\n\n```text\ndotenv\n```\n\n```text\n@nestjs/config\n```\n\n```text\nprocess.env\n```\n\n```js\nimport { DataSource, DataSourceOptions } from 'typeorm';\nimport { config } from 'dotenv';\nimport { resolve } from 'path';\n\nconfig({ path: resolve(__dirname, '.env') });\n\nconst DataSourceConfig = new DataSource({\n type: 'mysql',\n host: process.env.TYPEORM_HOST,\n port: Number(process.env.TYPEORM_PORT),\n username: process.env.TYPEORM_USERNAME,\n password: process.env.TYPEORM_PASSWORD,\n database: process.env.TYPEORM_DATABASE,\n migrations: ['./database/migrations/*'],\n synchronize: false,\n extra: {\n charset: 'utf8mb4',\n },\n migrationsTableName: 'migrations',\n});\n\nexport default DataSourceConfig;\n```\n\n```js\nimport { Injectable } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm';\n\n@Injectable()\nexport class TypeOrmConfigService implements TypeOrmOptionsFactory {\n constructor(private configService: ConfigService) {}\n\n public createTypeOrmOptions(): TypeOrmModuleOptions {\n return {\n type: 'mysql',\n host: this.configService.get<string>('TYPEORM_HOST'),\n port: this.configService.get<number>('TYPEORM_PORT'),\n username: this.configService.get<string>('TYPEORM_USERNAME'),\n password: this.configService.get<string>('TYPEORM_PASSWORD'),\n database: this.configService.get<string>('TYPEORM_DATABASE'),\n autoLoadEntities: true,\n };\n }\n}\n```\n\n```js\n@Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n TypeOrmModule.forRootAsync({ useClass: TypeOrmConfigService }),\n ]\n});\nexport class AppModule {}\n```\n\n```text\n\"migration:run\": \"typeorm-ts-node-commonjs -d typeorm.config.ts migration:run\",\n\"migration:create\": \"cd database/migrations && typeorm-ts-node-commonjs migration:create\",\n\"migration:revert\": \"typeorm-ts-node-commonjs -d typeorm.config.ts migration:revert\"\n```\n\n```text\ntypeorm.config.ts\n```\n\n```text\ntypeorm.service.js\n```\n\n```text\napp.module.ts\n```\n\n```text\npackage.json\n```\n\n```text\ntypeorm-ts-node-commonjs\n```\n\n```text\ntypeorm.config.js\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":20,"totalLines":302,"estimatedTokens":1825}}298{"id":"stack-66943353","source":"stackoverflow","questionId":66943353,"title":"Limit and skip related column in typeorm","tags":["typescript","nestjs","typeorm"],"text":"Title: Limit and skip related column in typeorm\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to limit the related data while finding with query builder, but I miss the concept.\n\nHere is my code to get the employee orders:\n\n```\nimport { getRepository, Repository } from \"typeorm\";\n\n public async findEmployeeQuery(id : number) {\n try {\n let query = await getRepository(Employees)\n .createQueryBuilder('employee')\n .where('employee.id = :id' , {id})\n .leftJoinAndSelect('employee.customers' , 'customers')\n .getOne()\n const user = query\n return user\n } catch (error) {\n throw error\n }\n\n }\n```\n\nNow I want to limit the number of customers for each request - how can I do that?\n\nI tried the limit and skip options but this only works with the employee, not with the joined data.\n\n========================================\n\nTop Answer:\nYou have to make another query to limit customers:\n\n```\nimport { getRepository, Repository } from \"typeorm\";\n\npublic async findEmployeeQuery(id : number) {\n try {\n let user = await getRepository(Employees)\n .createQueryBuilder('employee')\n .where('employee.id = :id' , {id});\n .getOne()\n\n user.customers = await getRepository(Customers)\n .createQueryBuilder('customer')\n .where('customer.employee= :id' , {user.id});\n .limit(10) // here you set limitation you want \n .getMany()\n\n return user;\n } catch (error) {\n throw error\n }\n}\n```\n\n========================================\n\nCode:\n```js\nimport { getRepository, Repository } from \"typeorm\";\n\n public async findEmployeeQuery(id : number) {\n try {\n let query = await getRepository(Employees)\n .createQueryBuilder('employee')\n .where('employee.id = :id' , {id})\n .leftJoinAndSelect('employee.customers' , 'customers')\n .getOne()\n const user = query\n return user\n } catch (error) {\n throw error\n }\n\n }\n```\n\n```js\nimport { getRepository, Repository } from \"typeorm\";\n\npublic async findEmployeeQuery(id : number) {\n try {\n let user = await getRepository(Employees)\n .createQueryBuilder('employee')\n .where('employee.id = :id' , {id})\n .leftJoinAndSelect('employee.customers' , 'customers')\n .take(4) // limits it to 4\n .skip(5) // offset 5 entities\n .getOne()\n\n return user\n } catch (error) {\n throw error\n }\n}\n```\n\n```js\nimport { getRepository, Repository } from \"typeorm\";\n\npublic async findEmployeeQuery(id : number) {\n try {\n let user = await getRepository(Employees)\n .createQueryBuilder('employee')\n .where('employee.id = :id' , {id});\n .getOne()\n\n user.customers = await getRepository(Customers)\n .createQueryBuilder('customer')\n .where('customer.employee= :id' , {user.id});\n .limit(10) // here you set limitation you want \n .getMany()\n\n return user;\n } catch (error) {\n throw error\n }\n}\n```\n\n```text\nlet category: any = await Category.findOne({\n where: {\n id: id,\n },\n });\n // finding products linked to that category\n let products = await orm\n .createQueryBuilder(\"products\", \"p\")\n .innerJoinAndSelect(\"p.categories\", \"c\", \"c.id = :categoryId\", {\n categoryId: id,\n })\n // implementing pagination\n .skip(offset)\n .take(limit)\n .getMany();\n // Attaching the array to the Category Object\n category.products = products;\n```\n\n========================================\n\nComments:\n- Try to do that in SQL first, to limit the numbers of relations you need to use a subquery. but it is really necessary this function ? Because this can have a considerable impact on your performance at a large scale.\n- You'd better make the query from the customers table not from the Employees table.\n- i did it for customers and it works fine Thank you\n- thank you i did it from the customers side and it works fine\n- keep this method in your mind in case you have multiple `leftjoins`, it'll help you ^^\n- Okay I will use it too\n- @Youba thanks for your help, but if user is an array, so i have to loop and it make so many query to database, do you have any idea?\n- sorry but it will not work coz it's limit the employees and I want to limit the customers who created by this employee,, anyway thanks for your help","metadata":{"transformedAt":"2026-08-18T18:33:44.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":156,"estimatedTokens":1090}}299{"id":"stack-70098455","source":"stackoverflow","questionId":70098455,"title":"Typeorm doesn't return generated data id","tags":["javascript","node.js","typeorm"],"text":"Title: Typeorm doesn't return generated data id\nTags: javascript, node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nIm using Typeorm (v8.0.2) and Nestjs(v8) with Nodejs(v16).\nMy problem is when I create a book Typeorm doesn't return generated book id\n\nHere is **Book.entity**\n\n```\n@Entity()\nexport class Book {\n\n@PrimaryGeneratedColumn('increment')\nid: number;\n\n@Column()\ntitle: string;\n\n@Column()\nauthor: string;\n}\n```\n\nAnd this is **book.service**\n\n```\nasync createBook(createBookDto: CreateBookDto): Promise {\n const book = await this.bookRepository.create(createBookDto)\n await this.bookRepository.save(createBookDto)\n return book\n}\n```\n\nand when I use postman and create a Book it just returns\n\n```\n{\n title: \"example\"\n author: \"foo\"\n}\n```\n\nid of generated book is missing\n\n========================================\n\nTop Answer:\nWhat happened in my case was that a developer defined `id` in the entity file with a `@PrimaryColumn` decorator rather than a `@PrimaryGeneratedColumn` decorator, and nest was not returning the `id` after `save()`.\n\nIt must be `@PrimaryGeneratedColumn`. e.g.,\n\n`@PrimaryGeneratedColumn({ name:'id', type:'bigint' }) id !: number`\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class Book {\n\n@PrimaryGeneratedColumn('increment')\nid: number;\n\n@Column()\ntitle: string;\n\n@Column()\nauthor: string;\n}\n```\n\n```text\nasync createBook(createBookDto: CreateBookDto): Promise<Book> {\n const book = await this.bookRepository.create(createBookDto)\n await this.bookRepository.save(createBookDto)\n return book\n}\n```\n\n```text\n{\n title: \"example\"\n author: \"foo\"\n}\n```\n\n```text\nconst user = repository.create(); // same as const user = new User();\nconst user = repository.create({\n id: 1,\n firstName: \"Timber\",\n lastName: \"Saw\"\n}); // same as const user = new User(); user.firstName = \"Timber\"; user.lastName = \"Saw\";\n```\n\n```text\nthis.bookRepository.save(createBookDto)\n```\n\n```text\nthis.bookRepository.create(createBookDto)\n```\n\n```text\ncreate\n```\n\n```text\nUser\n```\n\n```text\n@PrimaryGeneratedColumn()\n```\n\n```text\nsave()\n```\n\n```text\ncreate()\n```\n\n```text\nid\n```\n\n```text\n@PrimaryColumn\n```\n\n```text\n@PrimaryGeneratedColumn\n```\n\n```text\nid\n```\n\n```text\nsave()\n```\n\n```text\n@PrimaryGeneratedColumn\n```\n\n```text\n@PrimaryGeneratedColumn({ name:'id', type:'bigint' }) id !: number\n```\n\n========================================\n\nComments:\n- According to documentation, `@PrimaryGeneratedColumn()` is already in auto-increment by default. I don't see anything in doc showing that you can use `'increment'` as an argument for `@PrimaryGeneratedColumn()`.\n- A couple of enhancements can be done. 1) `await` has no purpose with `this.bookRepository.create(createBookDto)` 2) You should use `await this.bookRepository.save(book)` instead of `await this.bookRepository.save(createBookDto)`\n- Yep, glad you added this gotcha, saved me some time","metadata":{"transformedAt":"2026-08-18T18:33:44.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":159,"estimatedTokens":723}}300{"id":"stack-69009803","source":"stackoverflow","questionId":69009803,"title":"How to use leftJoinAndSelect query in TypeORM postgres?","tags":["typescript","postgresql","typeorm","node.js-typeorm"],"text":"Title: How to use leftJoinAndSelect query in TypeORM postgres?\nTags: typescript, postgresql, typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nI've been using TypeORM and made some Entities as follows:\n\n`User.ts`\n\n```\n@PrimaryGeneratedColumn()\nid: number\n```\n\n`Post.ts`\n\n```\n@PrimaryGeneratedColumn()\nid: number\n\n@Column()\nuserId: number\n```\n\nAs I didn't want to make relations between `User` and `Post` entities, I just made a column named `userId` at `Post`.\n\n**Here's the question.**\n\nI'd like to join two tables and fetch data. But how can I use `innerJoinAndSelect` or `leftJoinAndSelect`?\n\nHere's my code:\n\n```\n// getPost.ts\n\n// Attempt 1\nconst first = await createQueryBuilder()\n .select('user')\n .from(User, 'user')\n .leftJoinAndSelect(Post, 'post', 'post.userId = user.id')\n .getMany() // only fetched User data without Post data\n\n// Attempt 2\nconst second = await createQueryBuilder('user')\n .innerJoinAndSelect('user.id', 'userId')\n .innerJoinAndMap('user.id', Post, 'post', 'userId = post.userId')\n .getMany() // Bad request error\n```\n\nBut None of these worked...\n\nI'd like to join `User` with `Post` and grab all data (but not using relation). How could I get these data?\n\n========================================\n\nTop Answer:\nSince you don't want to create foreign key relations in the database, but still would like to use join operations on the entities, you can use `createForeignKeyConstraints` property in the relation options to achieve this.\n\nUpdate your entities as below:\n\n### `User.ts`\n\n```\n@PrimaryGeneratedColumn()\nid: number\n\n@OneToMany(() => Post, (post) => post.user)\nposts: Post[]\n```\n\n### `Post.ts`\n\n```\n@PrimaryGeneratedColumn()\nid: number\n\n@Column()\nuserId: number\n\n@ManyToOne(() => User, (user) => user.posts, { createForeignKeyConstraints: false })\n@JoinColumn({ name: 'userId' })\nuser: User\n```\n\nNow you should be able to use `find` or `QueryBuilder` methods on these entities just as they had an actual relationship in the database.\n\nI didn't test this code but this is the essence of what you should be doing. Hope this helps. Cheers 🍻 !!!\n\n========================================\n\nCode:\n```js\n@PrimaryGeneratedColumn()\nid: number\n```\n\n```js\n@PrimaryGeneratedColumn()\nid: number\n\n@Column()\nuserId: number\n```\n\n```js\n// getPost.ts\n\n// Attempt 1\nconst first = await createQueryBuilder()\n .select('user')\n .from(User, 'user')\n .leftJoinAndSelect(Post, 'post', 'post.userId = user.id')\n .getMany() // only fetched User data without Post data\n\n// Attempt 2\nconst second = await createQueryBuilder('user')\n .innerJoinAndSelect('user.id', 'userId')\n .innerJoinAndMap('user.id', Post, 'post', 'userId = post.userId')\n .getMany() // Bad request error\n```\n\n```text\nUser.ts\n```\n\n```text\nPost.ts\n```\n\n```text\nUser\n```\n\n```text\nPost\n```\n\n```text\nuserId\n```\n\n```text\nPost\n```\n\n```text\ninnerJoinAndSelect\n```\n\n```text\nleftJoinAndSelect\n```\n\n```text\nUser\n```\n\n```text\nPost\n```\n\n```js\nconst first = await createQueryBuilder()\n .select(‘user’)\n .from(User, ‘user’)\n // ------------------------ fixed ------------------------\n .leftJoinAndMapOne(‘user.id’, Post, ‘post’, ‘post.userId = user.id’)\n // -------------------------------------------------------\n .getMany()\n```\n\n```text\nleftJoinAndMapOne\n```\n\n```text\nmapToProperty\n```\n\n```text\ngetPost.ts\n```\n\n```js\n@PrimaryGeneratedColumn()\nid: number\n\n@OneToMany(() => Post, (post) => post.user)\nposts: Post[]\n```\n\n```js\n@PrimaryGeneratedColumn()\nid: number\n\n@Column()\nuserId: number\n\n@ManyToOne(() => User, (user) => user.posts, { createForeignKeyConstraints: false })\n@JoinColumn({ name: 'userId' })\nuser: User\n```\n\n```text\ncreateForeignKeyConstraints\n```\n\n```text\nUser.ts\n```\n\n```text\nPost.ts\n```\n\n```text\nfind\n```\n\n```text\nQueryBuilder\n```\n\n========================================\n\nComments:\n- Is this because you don't want to create foreign keys on the database?","metadata":{"transformedAt":"2026-08-18T18:33:44.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":24,"totalLines":227,"estimatedTokens":965}}301{"id":"stack-65470444","source":"stackoverflow","questionId":65470444,"title":"type-graphql Cannot find module 'class-validator' exception","tags":["express","graphql","typeorm","typegraphql"],"text":"Title: type-graphql Cannot find module 'class-validator' exception\nTags: express, graphql, typeorm, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a GQL mutation by TypeORM and using SQL Server as database. If I am trying to run the mutation it is throwing exception. Sharing the code below;\n\n**index.ts**\n\n```\n(async () => {\n const app = express();\n \n await createConnection();\n \n const apolloServer = new ApolloServer({\n schema: await buildSchema({\n resolvers: [UserRegistrationResolver, HealthResolver],\n }),\n tracing: true,\n context: ({ req, res }) => ({ req, res })\n });\n \n apolloServer.applyMiddleware({ app, cors: false });\n \n app.listen(4000, () => {\n console.log(\"App is started\");\n })\n })();\n```\n\n**GQL Types:**\n\n```\n@InputType()\nexport class UserRegistrationType {\n\n /*......*/\n @Field()\n Reg_Security_Qus_Ans: string;\n /*......*/\n\n}\n```\n\n**Entity:**\n\n```\n@ObjectType()\n@Entity()\nexport class User_Registration extends BaseEntity {\n\n /*......*/\n\n @Field(() => Int)\n @OneToOne(()=> Security_Questions)\n @JoinColumn()\n Reg_Security_Qus_ID: Security_Questions;\n\n /*......*/\n}\n```\n\n**Mutation:**\n\n```\n@Resolver()\nexport class UserRegistrationResolver {\n@Mutation(() => User_Registration)\n async createRegistrations(\n @Arg(\"RegistrationMutation\") registrationMutation: UserRegistrationType\n ) {\n console.log(\"Boom1\");\n let oneUser = await User_Registration.insert(registrationMutation);\n return oneUser; \n }\n \n @Query(() => User_Registration)\n getUsers() {\n console.log(\"Boom\");\n return User_Registration.find();\n } \n}\n```\n\nWhen, I am trying to execute the mutation some weird error is appearing like below, asking me for **'class-validator'**, the error looks something like this,\n\n```\n\"message\": \"Cannot find module 'class-validator'\\nRequire stack:\\n-\n```\n\nCan anyone help me to solve this. I am stuck with this. Thanks in advance.\n\n========================================\n\nTop Answer:\nEither install `class-validator` or use `validate: false` option of `buildSchema`.\n\n========================================\n\nCode:\n```text\n(async () => {\n const app = express();\n \n await createConnection();\n \n const apolloServer = new ApolloServer({\n schema: await buildSchema({\n resolvers: [UserRegistrationResolver, HealthResolver],\n }),\n tracing: true,\n context: ({ req, res }) => ({ req, res })\n });\n \n apolloServer.applyMiddleware({ app, cors: false });\n \n app.listen(4000, () => {\n console.log(\"App is started\");\n })\n })();\n```\n\n```text\n@InputType()\nexport class UserRegistrationType {\n\n /*......*/\n @Field()\n Reg_Security_Qus_Ans: string;\n /*......*/\n\n}\n```\n\n```text\n@ObjectType()\n@Entity()\nexport class User_Registration extends BaseEntity {\n\n /*......*/\n\n @Field(() => Int)\n @OneToOne(()=> Security_Questions)\n @JoinColumn()\n Reg_Security_Qus_ID: Security_Questions;\n\n /*......*/\n}\n```\n\n```text\n@Resolver()\nexport class UserRegistrationResolver {\n@Mutation(() => User_Registration)\n async createRegistrations(\n @Arg(\"RegistrationMutation\") registrationMutation: UserRegistrationType\n ) {\n console.log(\"Boom1\");\n let oneUser = await User_Registration.insert(registrationMutation);\n return oneUser; \n }\n \n @Query(() => User_Registration)\n getUsers() {\n console.log(\"Boom\");\n return User_Registration.find();\n } \n}\n```\n\n```text\n\"message\": \"Cannot find module 'class-validator'\\nRequire stack:\\n-\n```\n\n```text\nnpm i class-validator\n```\n\n```text\nclass-validator\n```\n\n```text\nvalidate: false\n```\n\n```text\nbuildSchema\n```\n\n========================================\n\nComments:\n- Same bruh, was about to curse my internet out lol\n- Not stupid. npm 7+ installs absent peer dependencies automatically. npm 6- does not. We discovered this when trying to build on the server recently. But thank you for verifying. We ran into the same error again because the server's npm version got reverted.\n- I had to install `class-validator`, even though `validate` was set to `false` in my `buildSchema`","metadata":{"transformedAt":"2026-08-18T18:33:44.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":197,"estimatedTokens":1057}}302{"id":"stack-53938797","source":"stackoverflow","questionId":53938797,"title":"Syntax Error: Unexpected token { on compiled typescript","tags":["node.js","typescript","typeorm"],"text":"Title: Syntax Error: Unexpected token { on compiled typescript\nTags: node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nWhen I try to run my compiled typescript code I get a syntax error:\n\n```\n\\entity\\Config.ts:1\n(function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from \"typeorm\";\n ^\n\nSyntaxError: Unexpected token {\n```\n\nbut when I run the typescript code with `ts-node` and `nodemon` code runs just fine. \n\nSo I've worked on some logging to figure out where the problem is occurring and it seems to happen when I hit `createConnection()` method on TypeORM. I'm new to Typescript and the TypeORM library.\n\nentity/config.ts\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from \"typeorm\";\n\n@Entity()\nexport class Config extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n app: String;\n\n @Column()\n endpoint: String;\n\n @Column()\n token: String;\n}\n```\n\nserver.ts\n\n```\nimport { createConnection } from \"typeorm\";\n\n// Database connected\ncreateConnection()\n .then(() => {\n console.log(\"Test\");\n })\n .catch(err => {\n console.log(err);\n });\n```\n\nindex.ts\n\n```\nrequire(\"reflect-metadata\");\nrequire(\"dotenv/config\");\nrequire(\"./server\");\n```\n\npackage.json dependancies\n\n```\n\"scripts\": {\n \"dev:server\": \"ts-node src\",\n \"dev\": \"nodemon -e ts -w src -x npm run dev:server\",\n \"build:server\": \"tsc\",\n \"start:server\": \"node build/index.js\",\n \"start\": \"npm run build:server && npm run start:server\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"MIT\",\n \"devDependencies\": {\n \"@types/axios\": \"^0.14.0\",\n \"@types/graphql\": \"^14.0.3\",\n \"@types/node\": \"^10.12.18\",\n \"@types/winston\": \"^2.4.4\",\n \"nodemon\": \"^1.18.9\",\n \"ts-node\": \"^7.0.1\",\n \"typescript\": \"^3.2.2\"\n },\n \"dependencies\": {\n \"apollo-server-express\": \"^2.3.1\",\n \"axios\": \"^0.18.0\",\n \"dotenv\": \"^6.2.0\",\n \"express\": \"^4.16.4\",\n \"graphql\": \"^14.0.2\",\n \"pg\": \"^7.7.1\",\n \"reflect-metadata\": \"^0.1.12\",\n \"sequelize\": \"^4.42.0\",\n \"typeorm\": \"^0.2.9\",\n \"winston\": \"^3.1.0\"\n }\n}\n```\n\n========================================\n\nTop Answer:\ni managed to solve this issue by deleting the `ormconfig.json` file and passing the database config in the `createConnection` function.\n\nexample:\n\n```\nimport { User } from './entity'\n// import every other entity you have\n// .......\n\nawait createConnection({\n type: 'sqlite',\n database: 'database.sqlite',\n synchronize: true,\n logging: true,\n entities: [\n User // pass your entities in here\n ]\n })\n```\n\n========================================\n\nCode:\n```text\n\\entity\\Config.ts:1\n(function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from \"typeorm\";\n ^\n\nSyntaxError: Unexpected token {\n```\n\n```text\nimport { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from \"typeorm\";\n\n@Entity()\nexport class Config extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n app: String;\n\n @Column()\n endpoint: String;\n\n @Column()\n token: String;\n}\n```\n\n```text\nimport { createConnection } from \"typeorm\";\n\n// Database connected\ncreateConnection()\n .then(() => {\n console.log(\"Test\");\n })\n .catch(err => {\n console.log(err);\n });\n```\n\n```text\nrequire(\"reflect-metadata\");\nrequire(\"dotenv/config\");\nrequire(\"./server\");\n```\n\n```text\n\"scripts\": {\n \"dev:server\": \"ts-node src\",\n \"dev\": \"nodemon -e ts -w src -x npm run dev:server\",\n \"build:server\": \"tsc\",\n \"start:server\": \"node build/index.js\",\n \"start\": \"npm run build:server && npm run start:server\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"MIT\",\n \"devDependencies\": {\n \"@types/axios\": \"^0.14.0\",\n \"@types/graphql\": \"^14.0.3\",\n \"@types/node\": \"^10.12.18\",\n \"@types/winston\": \"^2.4.4\",\n \"nodemon\": \"^1.18.9\",\n \"ts-node\": \"^7.0.1\",\n \"typescript\": \"^3.2.2\"\n },\n \"dependencies\": {\n \"apollo-server-express\": \"^2.3.1\",\n \"axios\": \"^0.18.0\",\n \"dotenv\": \"^6.2.0\",\n \"express\": \"^4.16.4\",\n \"graphql\": \"^14.0.2\",\n \"pg\": \"^7.7.1\",\n \"reflect-metadata\": \"^0.1.12\",\n \"sequelize\": \"^4.42.0\",\n \"typeorm\": \"^0.2.9\",\n \"winston\": \"^3.1.0\"\n }\n}\n```\n\n```text\nts-node\n```\n\n```text\nnodemon\n```\n\n```text\ncreateConnection()\n```\n\n```text\n\"entities\": [\"src/database/entity/**/*.ts\", \"build/database/entity/**/*.js\"],\n \"migrations\": [\n \"src/database/migration/**/*.ts\",\n \"build/database/migration/**/*.js\"\n ],\n \"subscribers\": [\n \"src/database/subscriber/**/*.ts\",\n \"build/database/subscriber/**/*.js\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n```\n\n```text\n\"entities\": [\"build/database/entity/**/*.js\"],\n \"migrations\": [\"build/database/migration/**/*.js\"],\n \"subscribers\": [\"build/database/subscriber/**/*.js\"],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n```\n\n```text\n*ts\n```\n\n```text\nimport { User } from './entity'\n// import every other entity you have\n// .......\n\nawait createConnection({\n type: 'sqlite',\n database: 'database.sqlite',\n synchronize: true,\n logging: true,\n entities: [\n User // pass your entities in here\n ]\n })\n```\n\n```text\normconfig.json\n```\n\n```text\ncreateConnection\n```\n\n```text\nentities: [__dirname + '/models/**/*.entity.{ts,js}'],\n migrations: [__dirname + '/migrations/**/*.{ts,js}'],\n subscribers: [__dirname + '/subscriber/**/*.{ts,js}'],\n```\n\n```text\n__dirname\n```\n\n========================================\n\nComments:\n- Please post the necessary code required for someone to help you out with your question. You have not provided any code that someone could run in order to try to reproduce your issue.\n- You are right I'm sorry for not providing more information. While was simplifying the code into something easy to reproduce I got information from the error so thank you :D\n- What version of nodejs, typescript, and typeorm are you running?\n- Node: 10.14.2 Typescript:3.2.2 TypeORM: 0.2.9 All these should be the latest stables\n- @JustinRhoades did you solve your problem? Please, add also how you run your code (npm scripts or just commands) it will help\n- @havenchyk This is still a problem. I have added the scripts to the package.json stage. I've tried to run the commands on there own and run them manually to no avail\n- I'm glad I could help :)\n- Great! This way, you don't need to transpile .ts entities into .js","metadata":{"transformedAt":"2026-08-18T18:33:44.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":296,"estimatedTokens":1640}}303{"id":"stack-72580969","source":"stackoverflow","questionId":72580969,"title":"NestJS + TypeORM Error during migration run: Unable to open file","tags":["nestjs","typeorm"],"text":"Title: NestJS + TypeORM Error during migration run: Unable to open file\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using NestJS to make an API and TypeORM to interface with my database.\n\nI've configured my database as follows\n\napp.modules.ts:\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mysql',\n host: 'localhost',\n port: 3306,\n username: 'root',\n password: 'pass',\n database: 'test',\n autoLoadEntities: true,\n synchronize: true,\n migrations:['migrations/*{.ts,.js}']\n }),\nCamerasModule\n],\n})\nexport class AppModule {}\n```\n\nAll I want to do is run a migration by typing:\n\n```\ntypeorm migration:run -d .\\migrations\\1654907799338-Camera.ts\n```\n\nI think part of the problem is that TypeORM isn't registering a DataSource, because if I just type\n\n```\ntypeorm migration:run\n```\n\nit doesn't know where to look.\n\nAnyways, the error I get is:\n\n```\nError during migration run:\nError: Unable to open file: \"C:\\Users\\sean\\Documents\\Git\\db-api\\migrations\\1654907799338-Camera.ts\". Cannot use import statement outside a module\n at Function.loadDataSource (C:\\Users\\sean\\AppData\\Roaming\\nvm\\v16.13.0\\node_modules\\typeorm\\commands\\CommandUtils.js:22:19)\n at async Object.handler (C:\\Users\\sean\\AppData\\Roaming\\nvm\\v16.13.0\\node_modules\\typeorm\\commands\\MigrationRunCommand.js:34:26)\n```\n\nWhy is Nest failing to communicate with TypeORM?\n\n========================================\n\nTop Answer:\nThere several things or checklists to ensure before you run migration. I also got the above error, and this is how I resolved it\n\nMake sure you have built your project\nFor some reason typeORM cannot read a .ts file, so build your project to a /dist folder and access it in your migration command.\n\nExample: Run build:\n`tsc`\n\nRun migration:\n`yarn typeorm migration:run -d dist/`\n\n- Make sure your DB instance is running and you have created the DB you are trying to connect to.\n\n========================================\n\nCode:\n```text\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mysql',\n host: 'localhost',\n port: 3306,\n username: 'root',\n password: 'pass',\n database: 'test',\n autoLoadEntities: true,\n synchronize: true,\n migrations:['migrations/*{.ts,.js}']\n }),\nCamerasModule\n],\n})\nexport class AppModule {}\n```\n\n```text\ntypeorm migration:run -d .\\migrations\\1654907799338-Camera.ts\n```\n\n```text\ntypeorm migration:run\n```\n\n```text\nError during migration run:\nError: Unable to open file: \"C:\\Users\\sean\\Documents\\Git\\db-api\\migrations\\1654907799338-Camera.ts\". Cannot use import statement outside a module\n at Function.loadDataSource (C:\\Users\\sean\\AppData\\Roaming\\nvm\\v16.13.0\\node_modules\\typeorm\\commands\\CommandUtils.js:22:19)\n at async Object.handler (C:\\Users\\sean\\AppData\\Roaming\\nvm\\v16.13.0\\node_modules\\typeorm\\commands\\MigrationRunCommand.js:34:26)\n```\n\n```text\n\"typeorm\": \"npx typeorm-ts-node-commonjs --dataSource src/data-source.ts\",\n\"typeorm:migrate\": \"yarn typeorm migration:run\",\n\"typeorm:generate\": \"yarn typeorm migration:generate src/database/migrations/Migration --timestamp\",\n\"typeorm:revert\": \"yarn typeorm migration:revert\"\n```\n\n```text\ntypeorm migration:run -d .\\migrations\\1654907799338-Camera.ts\n```\n\n```text\n-d\n```\n\n```text\nsrc\n```\n\n```text\nDataSourceOptions\n```\n\n```text\ncli\n```\n\n```text\ntsc\n```\n\n```text\nyarn typeorm migration:run -d dist/<link your data-source.js file>\n```\n\n========================================\n\nComments:\n- Very helpful answer. It worked for me after building the project, then running migrations pointing the data-source.js file, found in the build folder (/dist). Thank you.","metadata":{"transformedAt":"2026-08-18T18:33:44.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":149,"estimatedTokens":898}}304{"id":"stack-57733797","source":"stackoverflow","questionId":57733797,"title":"How to add a new column to an existing entity with typeorm","tags":["sqlite","typeorm"],"text":"Title: How to add a new column to an existing entity with typeorm\nTags: sqlite, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am starting to study typeorm and I am confused about what happens if I add a new column to an existing entity that was already persisted with data. I use SQlite.\n\nI saw in the documentation, in the \"Migrations\" section, it looks like there is a procedure that must be done if I want to add a new column.\n\nBut when I saw this issue in typeorm's github, I understood that if I just add the new \"@Column\" annotated property to the Entity class would be enough and typeorm would create the column automatically when the app starts.\n\nI was really hoping that typeorm would be able to handle that schema change automatically.\n\nCan someone help?\n\n========================================\n\nTop Answer:\nI had to create new migration, which will add new column \"is_delete\" in table users between column \"password\" and \"created_at\"\n\nI created new migration file. After this in public async up i inserted:\n\n```\nawait queryRunner.query(`ALTER TABLE \\`users\\` ADD \\`is_delete\\` int NOT NULL DEFAULT '0' AFTER \\`password\\` `);\n```\n\nMaybe for someone it will be useful\n\n========================================\n\nCode:\n```text\ntypeorm migration:generate -c 'connectionName'\n```\n\n```text\nimport { Connection, getConnectionManager } from 'typeorm';\n\nconst connectionManager = getConnectionManager();\nconst connection = connectionManager.get(connectionName);\nawait connection.runMigrations();\n\n// start your server\nstartServer();\n```\n\n```text\nnpx typeorm schema:sync -c 'connectionName'\n```\n\n```text\nawait queryRunner.query(`ALTER TABLE \\`users\\` ADD \\`is_delete\\` int NOT NULL DEFAULT '0' AFTER \\`password\\` `);\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":53,"estimatedTokens":430}}305{"id":"stack-67591877","source":"stackoverflow","questionId":67591877,"title":"How to unit test typeorm getRepository with Jest?","tags":["javascript","typescript","testing","jestjs","typeorm"],"text":"Title: How to unit test typeorm getRepository with Jest?\nTags: javascript, typescript, testing, jestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am using typescript with typeorm and i have an repository like this:\n\n```\nimport { EntityRepository, getRepository, createQueryBuilder } from 'typeorm';\n\n@EntityRepository()\nexport default class Repo {\n async getSomething(): Promise {\n const schemaQuery = getRepository(SomeModel)\n .createQueryBuilder('sm')\n .select(...)\n .where(...);\n .....\n```\n\nmy test file is like this\n\n```\nimport * as typeorm from 'typeorm';\nimport Repo from '../../../../src/repositories/Repo';\n\ndescribe(\n 'test',\n () => {\n let repo: Repo;\n beforeEach(() => {\n repo = new Repo();\n });\n test('getSomething works', async () => {\n jest.spyOn(typeorm, 'getRepository').mockImplementation(() => ({ // typescript wants me to implement all properties of getRepository which i dont want\n createQueryBuilder: jest.fn(),\n }));\n ...\n });\n },\n);\n```\n\nhow do i mock getRepository directly from typeorm which is still complying to typescript type check?\n\n========================================\n\nTop Answer:\nI was experiencing the following error when using the approved solution:\n\n```\nTypeError: Cannot redefine property: getRepository\n at Function.defineProperty ()\n```\n\nIn order to resolve this issue, I used the following import statement instead:\n\n```\nimport * as typeorm from \"typeorm/globals\";\n```\n\n========================================\n\nCode:\n```js\nimport { EntityRepository, getRepository, createQueryBuilder } from 'typeorm';\n\n\n@EntityRepository()\nexport default class Repo {\n async getSomething(): Promise<Result> {\n const schemaQuery = getRepository(SomeModel)\n .createQueryBuilder('sm')\n .select(...)\n .where(...);\n .....\n```\n\n```js\nimport * as typeorm from 'typeorm';\nimport Repo from '../../../../src/repositories/Repo';\n\ndescribe(\n 'test',\n () => {\n let repo: Repo;\n beforeEach(() => {\n repo = new Repo();\n });\n test('getSomething works', async () => {\n jest.spyOn(typeorm, 'getRepository').mockImplementation(() => ({ // typescript wants me to implement all properties of getRepository which i dont want\n createQueryBuilder: jest.fn(),\n }));\n ...\n });\n },\n);\n```\n\n```js\njest.spyOn(typeorm, \"getRepository\").mockImplementation(() => {\n const original = jest.requireActual(\"typeorm\");\n // You need all functions used in your Query builder \n return {\n ...original,\n createQueryBuilder: jest.fn().mockImplementation(() => ({\n subQuery: jest.fn().mockReturnThis() as unknown,\n from: jest.fn().mockReturnThis() as unknown,\n where: jest.fn().mockReturnThis() as unknown,\n select: jest.fn().mockReturnThis() as unknown,\n getQuery: jest.fn().mockReturnThis() as unknown,\n setParameter: jest.fn().mockReturnThis() as unknown,\n getMany: jest\n .fn()\n .mockResolvedValue(expected) as unknown,\n })),\n };\n });\n```\n\n```text\nTypeError: Cannot redefine property: getRepository\n at Function.defineProperty (<anonymous>)\n\n 64 | } as unknown as Installation;\n 65 |\n > 66 | jest.spyOn(typeorm, 'getRepository').mockImplementation(() => {\n | ^\n 67 | const original = jest.requireActual('typeorm');\n 68 | // You need all functions used in your Query builder\n 69 | return {\n```\n\n```text\nimport * as typeorm from 'typeorm';\n.\n.\n.\n jest.spyOn(typeorm, 'getRepository').mockImplementation(() => {\n const original = jest.requireActual('typeorm');\n // You need all functions used in your Query builder\n return {\n ...original,\n createQueryBuilder: jest.fn().mockImplementation(() => ({\n subQuery: jest.fn().mockReturnThis() as unknown,\n from: jest.fn().mockReturnThis() as unknown,\n where: jest.fn().mockReturnThis() as unknown,\n select: jest.fn().mockReturnThis() as unknown,\n getQuery: jest.fn().mockReturnThis() as unknown,\n setParameter: jest.fn().mockReturnThis() as unknown,\n getMany: jest.fn().mockResolvedValue(expected) as unknown,\n })),\n };\n });\n```\n\n```text\nimport * as typeorm_functions from 'typeorm/globals';\n\njest.spyOn(typeorm_functions, 'getRepository').mockReturnValue({\n createQueryBuilder: jest.fn().mockImplementation(() => ({\n subQuery: jest.fn().mockReturnThis() as unknown,\n from: jest.fn().mockReturnThis() as unknown,\n where: jest.fn().mockReturnThis() as unknown,\n select: jest.fn().mockReturnThis() as unknown,\n getQuery: jest.fn().mockReturnThis() as unknown,\n setParameter: jest.fn().mockReturnThis() as unknown,\n getMany: jest\n .fn()\n .mockResolvedValue(expected) as unknown,\n })),\n} as unknown as Repository<unknown>);\n```\n\n```text\nTypeError: Cannot redefine property: getRepository\n at Function.defineProperty (<anonymous>)\n```\n\n```js\nimport * as typeorm from \"typeorm/globals\";\n```\n\n========================================\n\nComments:\n- I have similar questions to test the custom repositories, stackoverflow.com/questions/67580233/…\n- How to mock typeorm getRepository find method which has a where clause in it ? e.g: userRepo.find({ where: {\"userId\": 5} });\n- You probably need to replace the `getMany` field with a jest function and change the resolved value\n- I have the same problem =( Did you find a solution?","metadata":{"transformedAt":"2026-08-18T18:33:44.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":190,"estimatedTokens":1376}}306{"id":"stack-60833520","source":"stackoverflow","questionId":60833520,"title":"How can I use raw SQL in NestJS instead of TypeOrm or Sequelize?","tags":["sql","orm","sequelize.js","nestjs","typeorm"],"text":"Title: How can I use raw SQL in NestJS instead of TypeOrm or Sequelize?\nTags: sql, orm, sequelize.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nAs of today TypeOrm has 1.493 issues over 282.102 weekly downloads and Sequelize 783 issues over 571.781 weekly downloads in Github. \n\nAs I read over the TypeOrm and Sequelize Github issues, I want to avoid those major problemas by coding raw SQL instead of dealing with major issues like losing data, columns being dropped when you synchronize entities or types being changed due to default ORM types. \n\nI use NestJs 7.0.3 with TypeGraphQL, PostgreSQL v12.2 and TypeScript.\nSince 2019, I've had two issues raised with TypeOrm. \n\nI understand the advantages of using an ORM but I wonder if NestJS can work efficiently if I use raw SQL in order to replace TypeORM or Sequelize entirely?\n\nThanks so much for your insights.\nRon\n\n========================================\n\nComments:\n- I cheched your github repo and the zeldaPlay source code is amazing. You created your own Dynamic Module. After all you have done with the node-pg package, would you replace in your developments an ORM in order to avoid those issues I mentioned above or would you rather deal with the trade off and use Typeorm/Sequelize ?\n- There's a lot of refactoring going on behind the scenes. Gonna be removing the transient scope and instead working with all singletons, just by creating new provider tokens instead of using the same class name (similar to how the TypeOrm package for Nest works). It should make testing easier, but it'll be a while before I get to that\n- I usually avoid ORMs as I don't feel they bring as many advantages as they do negatives in the end of things. Plus, this way, I **know** what is being executed on my SQL server.\n- Thanks so much for sharing your experience. As a summary, in order to go this \"raw-sql\" route I should start (1) reading the manual for node-pg (2) reading nestjs Dynamic Module (3) creating my own Dynamic Module (4) Compare my code with your working code. Would you suggest any additional readings before I enter this unplanned journey?\n- You don't necessarily have to use my code as a comparison, I do use a few helper packages to make things easier; however, this article is really well written and starts getting into some of the working of Dynamic Modules. John has a lot of good Nest articles so find some stuff that interests you from him if you want as well. Here's another of his\n- All these related pieces were the direction I was looking for: Thank you for sharing so much information Best regards.","metadata":{"transformedAt":"2026-08-18T18:33:44.706Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":26,"estimatedTokens":646}}307{"id":"stack-59351687","source":"stackoverflow","questionId":59351687,"title":"Why is my Many to Many relationship field undefined?","tags":["arrays","typescript","typeorm"],"text":"Title: Why is my Many to Many relationship field undefined?\nTags: arrays, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to create a follower/following system and when I try to append the new user to the following list I get the error `Cannot read property 'push' of undefined`. This ends up creating 2 separate tables one for users following other users and one for users being followed by other users. Not sure why it's not picking up the field? Any help is appreciated. \n\n```\nimport { Length } from \"class-validator\";\nimport {\n Column,\n CreateDateColumn,\n Entity,\n JoinTable,\n ManyToMany,\n OneToMany,\n PrimaryColumn,\n RelationCount,\n Unique,\n UpdateDateColumn\n} from \"typeorm\";\n\nexport class User {\n\n @PrimaryColumn()\n public user_id: string;\n\n @Column()\n public first_name: string;\n\n @Column()\n public last_name: string;\n\n @Column()\n public email: string;\n\n @Column()\n public phone_number: string;\n\n @Column()\n public username: string;\n\n @Column()\n @CreateDateColumn()\n public created_on: Date;\n\n @Column()\n @UpdateDateColumn()\n public updated_at: Date;\n\n @ManyToMany((type) => User, (user) => user.following)\n @JoinTable()\n public followers: User[];\n\n @ManyToMany((type) => User, (user) => user.followers)\n @JoinTable()\n public following: User[];\n\n @RelationCount((user: User) => user.followers)\n public followers_count: number;\n\n @RelationCount((user: User) => user.following)\n public following_count: number;\n}\n```\n\n```\nconst { user_id, \n follow_user_id } = req.\nconst user_repo = getRepository(User);\nconst user = await user_repo.findOne({\n where: {user_id}\n});\nconst follow_user = new User();\n\nfollow_user.user_id = follow_user_id;\nuser.following.push(follow_user);\nconst result = user_repo.save(user);\n```\n\nError is referring to this line `user.following.push(follow_user);`\n\n```\nUnhandledPromiseRejectionWarning: TypeError: Cannot read property 'push' of undefined\n```\n\n========================================\n\nTop Answer:\nI encountered a similar error with OneToMany and ManyToOne relations where the relative returned null/undefined. \n\nThe workaround I'm using involves putting this in the User class:\n\n```\n@AfterLoad()\n async nullChecks() {\n if (!this.followers) {\n this.followers = []\n }\n\n if (!this.following) {\n this.following = []\n }\n }\n```\n\ndocumentation\n\n========================================\n\nCode:\n```text\nimport { Length } from \"class-validator\";\nimport {\n Column,\n CreateDateColumn,\n Entity,\n JoinTable,\n ManyToMany,\n OneToMany,\n PrimaryColumn,\n RelationCount,\n Unique,\n UpdateDateColumn\n} from \"typeorm\";\n\nexport class User {\n\n @PrimaryColumn()\n public user_id: string;\n\n @Column()\n public first_name: string;\n\n @Column()\n public last_name: string;\n\n @Column()\n public email: string;\n\n @Column()\n public phone_number: string;\n\n @Column()\n public username: string;\n\n @Column()\n @CreateDateColumn()\n public created_on: Date;\n\n @Column()\n @UpdateDateColumn()\n public updated_at: Date;\n\n @ManyToMany((type) => User, (user) => user.following)\n @JoinTable()\n public followers: User[];\n\n @ManyToMany((type) => User, (user) => user.followers)\n @JoinTable()\n public following: User[];\n\n @RelationCount((user: User) => user.followers)\n public followers_count: number;\n\n @RelationCount((user: User) => user.following)\n public following_count: number;\n}\n```\n\n```text\nconst { user_id, \n follow_user_id } = req.\nconst user_repo = getRepository(User);\nconst user = await user_repo.findOne({\n where: {user_id}\n});\nconst follow_user = new User();\n\nfollow_user.user_id = follow_user_id;\nuser.following.push(follow_user);\nconst result = user_repo.save(user);\n```\n\n```text\nUnhandledPromiseRejectionWarning: TypeError: Cannot read property 'push' of undefined\n```\n\n```text\nCannot read property 'push' of undefined\n```\n\n```text\nuser.following.push(follow_user);\n```\n\n```js\n// Source code omission\n @ManyToMany((type) => User, (user) => user.followers)\n @JoinTable()\n public following: User[] = []; // ★ Added assign\n // Source code omission\n```\n\n```js\nexport class User {\n // Source code omission\n constructor() { // ★ Added line\n this.following = []; // ★ Added line\n } // ★ Added line\n}\n```\n\n```js\nconst follow_user = new User();\n\nfollow_user.user_id = follow_user_id;\nuser.following = []; // ★ Added line\nuser.following.push(follow_user);\nconst result = user_repo.save(user);\n```\n\n```js\nconst follow_user = new User();\n\nfollow_user.user_id = follow_user_id;\nuser.following = [follow_user]; // ★ Edited line\nconst result = user_repo.save(user);\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\nUser\n```\n\n```text\n@AfterLoad()\n async nullChecks() {\n if (!this.followers) {\n this.followers = []\n }\n\n if (!this.following) {\n this.following = []\n }\n }\n```\n\n```text\n@ManyToMany((type) => User, (user) => user.following)\n@JoinTable()\nprivate _followers: User[];\n```\n\n```text\nget followers() : User[] {\n if (!_followers) {\n _followers = [];\n }\n return _followers;\n}\n```\n\n========================================\n\nComments:\n- The first way is invalid I get the error `Error: Array initializations are not allowed in entity relations. Please remove array initialization (= [])`. The 2nd option resulted in the same result. The 3rd option did work.\n- Maybe 4th way you’d like more.\n- The docs explains, that you shouldn't use initilalizers for relation arrays, as empty array is treated like match everything, which is probably not what you expected. See orkhan.gitbook.io/typeorm/docs/…\n- This works for fetching existing entries, but not when creating a new entry with `new MyClass()`.","metadata":{"transformedAt":"2026-08-18T18:33:44.706Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":281,"estimatedTokens":1428}}308{"id":"stack-70025283","source":"stackoverflow","questionId":70025283,"title":"TypeORM - Update only values that are provided and leave the rest as they are","tags":["nestjs","typeorm"],"text":"Title: TypeORM - Update only values that are provided and leave the rest as they are\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHow would I approach this using TypeORM?\n\nI have an Entity lets call it EntityA.\n\nI have 1 EntityA in my database with name = Joe, age = 17\n\nNow my front end sends a post request to my API with an Object like { name: Joe, age: 16 }\n\nHow can I tell type orm to update the EntityA in the database with the name of \"Joe\" and only update the provided values that differ from what is currently stored in the database (age in this case) ?\n\n========================================\n\nCode:\n```js\nasync function update(id: string, user: User): Promise<User> {\n // Update\n await userRepository.update(id, {\n ...(user.name && { name: user.name }),\n ...(user.surname && { surname: user.surname }),\n ...(user.age && { age: user.age }),\n });\n\n // Return\n return this.repository.findOneOrFail(id);\n }\n```\n\n```text\nundefined\n```\n\n```text\nnullable\n```\n\n```text\nuser\n```\n\n```text\nuser.name\n```\n\n========================================\n\nComments:\n- Great idea, but it still doesn't solve the original problem - if the user sends a user.name which is the same as in the DB, typeorm still updates it. You need to read the record from the DB, and add a comparison. Like: user.name && user.name !== currUser.name && ...\n- @Yehezkel No, too costly. If the values are the same, a single update is fine, since the records fields that are different are still updated.\n- I totally agree regarding the cost, just tried to answer the question exactly.","metadata":{"transformedAt":"2026-08-18T18:33:44.706Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":54,"estimatedTokens":399}}309{"id":"stack-69019803","source":"stackoverflow","questionId":69019803,"title":"TypeORM one-to-many relation using Entity Schema","tags":["node.js","typeorm","node.js-typeorm"],"text":"Title: TypeORM one-to-many relation using Entity Schema\nTags: node.js, typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nI have two entities Projects & Orders. I want to have One-to-Many Orders in Projects and Many-to-One project in Orders.\n\nMany-to-one side is working fine.\n\nWhen I try to add One-to-Many in Project entity and try to fetch all, I get following error:\n\n```\n\"Cannot read property 'joinColumns' of undefined\"\n```\n\n**Project Entity**\n\n```\nconst { EntitySchema } = require('typeorm');\nconst { BaseRelations, BaseColumns } = require('../BaseEntity');\n\nmodule.exports = new EntitySchema({\n name: 'Project', \n columns: {\n ...BaseColumns,\n name: {\n type: 'varchar',\n }\n },\n relations: {\n ...BaseRelations,\n orders: {\n type: 'one-to-many',\n target: 'Order',\n cascade: true,\n },\n },\n});\n```\n\n**Order Entity**\n\n```\nconst { EntitySchema } = require('typeorm');\n\nmodule.exports = new EntitySchema({\n name: 'Order',\n columns: {\n id: {\n primary: true,\n type: 'int',\n generated: true,\n },\n name: {\n type: 'varchar',\n name: 'name',\n },\n },\n relations: {\n project: {\n type: 'many-to-one',\n target: 'Project',\n joinColumn: {\n name: 'project_id',\n },\n }\n },\n});\n```\n\n========================================\n\nCode:\n```text\n\"Cannot read property 'joinColumns' of undefined\"\n```\n\n```text\nconst { EntitySchema } = require('typeorm');\nconst { BaseRelations, BaseColumns } = require('../BaseEntity');\n\nmodule.exports = new EntitySchema({\n name: 'Project', \n columns: {\n ...BaseColumns,\n name: {\n type: 'varchar',\n }\n },\n relations: {\n ...BaseRelations,\n orders: {\n type: 'one-to-many',\n target: 'Order',\n cascade: true,\n },\n },\n});\n```\n\n```text\nconst { EntitySchema } = require('typeorm');\n\nmodule.exports = new EntitySchema({\n name: 'Order',\n columns: {\n id: {\n primary: true,\n type: 'int',\n generated: true,\n },\n name: {\n type: 'varchar',\n name: 'name',\n },\n },\n relations: {\n project: {\n type: 'many-to-one',\n target: 'Project',\n joinColumn: {\n name: 'project_id',\n },\n }\n },\n});\n```\n\n```text\nconst { EntitySchema } = require('typeorm');\nconst { BaseRelations, BaseColumns } = require('../BaseEntity');\n\nmodule.exports = new EntitySchema({\n name: 'Project', \n columns: {\n ...BaseColumns,\n name: {\n type: 'varchar',\n }\n },\n relations: {\n ...BaseRelations,\n orders: {\n type: 'one-to-many',\n target: 'Order',\n cascade: true,\n inverseSide: 'project' // Note that this is relation name, not the entity name\n },\n },\n});\n```\n\n```text\nconst { EntitySchema } = require('typeorm');\n\nmodule.exports = new EntitySchema({\n name: 'Order',\n columns: {\n id: {\n primary: true,\n type: 'int',\n generated: true,\n },\n name: {\n type: 'varchar',\n name: 'name',\n },\n },\n relations: {\n project: {\n type: 'many-to-one',\n target: 'Project',\n joinColumn: {\n name: 'project_id',\n },\n inverseSide: 'orders' // Note that this is the relation name in project entity, no the entity name Order\n }\n },\n});\n```\n\n```text\ninverseSide\n```\n\n```text\ninverseSide\n```\n\n========================================\n\nComments:\n- Did this work so that saving the project saved all of its orders? Currently experiencing an issue here where saving the parent object only saves the first child of the array with cascade set to true.\n- yes the cascading did work.","metadata":{"transformedAt":"2026-08-18T18:33:44.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":194,"estimatedTokens":867}}310{"id":"stack-67547502","source":"stackoverflow","questionId":67547502,"title":"Nestjs - Typeorm custom connection name","tags":["node.js","nestjs","connection","typeorm"],"text":"Title: Nestjs - Typeorm custom connection name\nTags: node.js, nestjs, connection, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a Nestjs db Module and it works perfectly\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n useFactory: () => {\n return {\n name: 'default', // if I change the connection name to anything else rather then 'default' say 'test' I get an error\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n useFactory: () => {\n return {\n name: 'test', // The error seams to only show up if I use TypeOrmModule.forRootAsync\nFor TypeOrmModule.forRoot if works!\n\nIs there any different way to indicate the connection name? I need to add another connection and can't do it because of this error. Really would like to use 'forRootAsync'\n\n========================================\n\nCode:\n```text\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n useFactory: () => {\n return {\n name: 'default', // <=== here\n type: \"mysql\",\n ...\n };\n },\n }),\n\n TypeOrmModule.forFeature(entities, 'default'), // <=== here\n ],\n exports: [TypeOrmModule],\n})\nexport class DBModule {}\n```\n\n```text\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n useFactory: () => {\n return {\n name: 'test', // <=== here\n type: \"mysql\",\n ...\n };\n },\n }),\n\n TypeOrmModule.forFeature(entities, 'test'), // <=== here\n ],\n exports: [TypeOrmModule],\n})\nexport class DBModule {}\n```\n\n```text\n[Nest] 10746 - 05/15/2021, 5:55:34 PM [ExceptionHandler] Nest can't resolve dependencies of the test_UserEntityRepository (?). Please make sure that the argument testConnection at index [0] is available in the TypeOrmModule context.\n\nPotential solutions:\n- If testConnection is a provider, is it part of the current TypeOrmModule?\n- If testConnection is exported from a separate @Module, is that module imported within TypeOrmModule?\n @Module({\n imports: [ /* the Module containing testConnection */ ]\n })\n```\n\n```text\n@Module({\nimports: [\n TypeOrmModule.forRootAsync({\n name: 'test', // <=== here\n useFactory: () => {\n return {\n type: \"mysql\",\n ...\n };\n },\n }),\n\n TypeOrmModule.forFeature(entities, 'test'), // <=== here\n ],\n exports: [TypeOrmModule],\n})\nexport class DBModule {}\n```\n\n========================================\n\nComments:\n- Thanks that was the solution!\n- @levansuper glad it solved the issue. you can always get into the function definition files to check what parameters it accepts. also, you can accept this solution.\n- seems to be deprecated. any other solution?","metadata":{"transformedAt":"2026-08-18T18:33:44.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":106,"estimatedTokens":709}}311{"id":"stack-58181006","source":"stackoverflow","questionId":58181006,"title":"pass string variable to 'type' in TypeOrmModuleOptions","tags":["javascript","node.js","nestjs","typeorm","dotenv"],"text":"Title: pass string variable to 'type' in TypeOrmModuleOptions\nTags: javascript, node.js, nestjs, typeorm, dotenv\nSource: Stack Overflow\n\nQuestion:\nI want to setup a database connection for my NestJs app using TypeORM. I have a config file which reads all values from the `.env` file\n\n```\nimport { DotenvConfigOutput, config } from 'dotenv';\n\nconst envFound: DotenvConfigOutput = config();\n\nif (!envFound) {\n throw new Error('.env file was not found.');\n}\n\nprocess.env.NODE_ENV = process.env.NODE_ENV || 'development';\n\nexport const DATABASE_TYPE: string = process.env.DATABASE_TYPE || 'postgres';\nexport const DATABASE_USERNAME: string = process.env.DATABASE_USERNAME || 'admin';\nexport const DATABASE_PASSWORD: string = process.env.DATABASE_PASSWORD || 'myPW';\nexport const DATABASE_HOST: string = process.env.DATABASE_HOST || 'localhost';\nexport const DATABASE_PORT: number = Number(process.env.DATABASE_PORT) || 5432;\nexport const DATABASE_NAME: string = process.env.DATABASE_NAME || 'myDB';\nexport const DATABASE_SYNCHRONIZE: boolean = Boolean(process.env.DATABASE_SYNCHRONIZE) || true;\n```\n\nI am setting up the connection in the app.module, so on application startup.\n\n```\nimport {\n DATABASE_TYPE,\n DATABASE_HOST,\n DATABASE_PORT,\n DATABASE_USERNAME,\n DATABASE_PASSWORD,\n DATABASE_NAME,\n DATABASE_SYNCHRONIZE,\n} from './config';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: DATABASE_TYPE,\n host: DATABASE_HOST,\n port: DATABASE_PORT,\n username: DATABASE_USERNAME,\n password: DATABASE_PASSWORD,\n database: DATABASE_NAME,\n entities: [],\n synchronize: DATABASE_SYNCHRONIZE,\n }),\n ],\n controllers: [],\n providers: [],\n})\nexport class AppModule {}\n```\n\nUnfortunately I get this error at the `type` field\n\n Type 'string' is not assignable to type '\"mysql\" | \"mariadb\" |\n \"postgres\" | \"cockroachdb\" | \"sqlite\" | \"mssql\" | \"oracle\" | \"cordova\"\n | \"nativescript\" | \"react-native\" | \"sqljs\" | \"mongodb\" |\n \"aurora-data-api\" | \"expo\"'.ts(2322) MysqlConnectionOptions.d.ts(12,\n 14): The expected type comes from property 'type' which is declared\n here on type 'TypeOrmModuleOptions'\n\nI don't want to pass in a hardcoded string like `'postgres'` because I want it to keep dynamic. I prefer Postgres but some customers use oracle databases and I have to support MSSQL too.\n\nHow can I fix that configuration problem?\n\n========================================\n\nTop Answer:\nThis worked for me:\n\n```\nTypeOrmModule.forRoot({\n type: \"sqlite\" as any,\n host: \"localhost\",\n database: \"./database/sqlite\"\n})\n```\n\nI spent a whole weekend trying to figure out this issue but got stumped.\n\nDoes anybody have a better solution or explanation?\n\n========================================\n\nCode:\n```text\nimport { DotenvConfigOutput, config } from 'dotenv';\n\nconst envFound: DotenvConfigOutput = config();\n\nif (!envFound) {\n throw new Error('.env file was not found.');\n}\n\nprocess.env.NODE_ENV = process.env.NODE_ENV || 'development';\n\nexport const DATABASE_TYPE: string = process.env.DATABASE_TYPE || 'postgres';\nexport const DATABASE_USERNAME: string = process.env.DATABASE_USERNAME || 'admin';\nexport const DATABASE_PASSWORD: string = process.env.DATABASE_PASSWORD || 'myPW';\nexport const DATABASE_HOST: string = process.env.DATABASE_HOST || 'localhost';\nexport const DATABASE_PORT: number = Number(process.env.DATABASE_PORT) || 5432;\nexport const DATABASE_NAME: string = process.env.DATABASE_NAME || 'myDB';\nexport const DATABASE_SYNCHRONIZE: boolean = Boolean(process.env.DATABASE_SYNCHRONIZE) || true;\n```\n\n```text\nimport {\n DATABASE_TYPE,\n DATABASE_HOST,\n DATABASE_PORT,\n DATABASE_USERNAME,\n DATABASE_PASSWORD,\n DATABASE_NAME,\n DATABASE_SYNCHRONIZE,\n} from './config';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: DATABASE_TYPE,\n host: DATABASE_HOST,\n port: DATABASE_PORT,\n username: DATABASE_USERNAME,\n password: DATABASE_PASSWORD,\n database: DATABASE_NAME,\n entities: [],\n synchronize: DATABASE_SYNCHRONIZE,\n }),\n ],\n controllers: [],\n providers: [],\n})\nexport class AppModule {}\n```\n\n```text\n.env\n```\n\n```text\ntype\n```\n\n```text\n'postgres'\n```\n\n```text\nexport const DATABASE_TYPE: any = String(process.env.DATABASE_TYPE) || 'postgres';\n```\n\n```text\nTypeOrmModule.forRoot({\n type: \"sqlite\" as any,\n host: \"localhost\",\n database: \"./database/sqlite\"\n})\n```\n\n========================================\n\nComments:\n- sorry no, that didn't work for me. The error still remains\n- please check my updated answer, I changed the type to `any` hope this helps\n- hm the error is gone :) I can remove the cast to a string, `any` seems to be enough\n- Did you ever find a solution to this issue?\n- In my case making `type` value as **any** solves the problem, e.g. `type: 'postgres' as any`","metadata":{"transformedAt":"2026-08-18T18:33:44.707Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":174,"estimatedTokens":1184}}312{"id":"stack-55224483","source":"stackoverflow","questionId":55224483,"title":"Loading a 'bit' Mysql field from TypeOrm","tags":["nestjs","typeorm"],"text":"Title: Loading a 'bit' Mysql field from TypeOrm\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to map a Mysql bit data column against a `boolean` property with TypeOrm. I'm using the NestJs framework and can't figure out how to do it. As far as I've seen, the Mysql `bit` datatype is not supported by the framework, but I don't know any way to workaround it. According to this discussion it should be enough to declare a boolean typed field in the entity and do not decorate it with nothing but `@Column`:\n\n```\n@Column()\n enable: boolean;\n```\n\nHowever, with this I get `true` value in every single instance of the entity. Also tried adding the `import 'reflect-metadata';` either in the entity and in `app.module.ts`, with the same result.\n\nAnother choice would be to use the `tinyint` type:\n\n```\n@Column({\n type: 'tinyint',\n })\n enable: boolean;\n```\n\nWith this, I get this kind of data, where the `data` field holds the current boolean value stored:\n\n```\n\"enable\":{\"type\":\"Buffer\",\"data\":[1]}\n```\n\nDo I need to make some kind of hack to get this converted into a proper boolean value or is there another cleaner choice to do it?\n\n**EDIT 1**\n\nChanging the DB column data type to `int` seems to produce the proper output. However, it's not the most proper solution, since the `bit` type is the one that best suits here.\n\n**Versions being used:**\n\n- \"@nestjs/typeorm\": \"5.1.0\"\n\n- \"typeorm\": \"0.2.13\"\n\n- \"reflect-metadata\": \"0.1.12\"\n\n- Mysql Engine: 5.7.25\n\n**EDIT 2**\n\nI've tried updating the `typeorm` related packages to their latest versions, the same keeps happening. Also with Mysql 8.0 engine. Tried also with these decorators:\n\n```\n@Column()\n @IsBoolean()\n enable: boolean;\n```\n\nI'm in Xubuntu 16.04, BTW.\n\n========================================\n\nTop Answer:\nI'm solving this in the following way\n\n```\n@Column({\n name: 'FIELD_NAME',\n type: 'bit',\n transformer: { from: (v: Buffer) => !!v.readInt8(0), to: (v) => v },\n })\n readonly field: boolean;\n```\n\n========================================\n\nCode:\n```text\n@Column()\n enable: boolean;\n```\n\n```text\n@Column({\n type: 'tinyint',\n })\n enable: boolean;\n```\n\n```text\n\"enable\":{\"type\":\"Buffer\",\"data\":[1]}\n```\n\n```text\n@Column()\n @IsBoolean()\n enable: boolean;\n```\n\n```text\nboolean\n```\n\n```text\nbit\n```\n\n```text\n@Column\n```\n\n```text\ntrue\n```\n\n```text\nimport 'reflect-metadata';\n```\n\n```text\napp.module.ts\n```\n\n```text\ntinyint\n```\n\n```text\ndata\n```\n\n```text\nint\n```\n\n```text\nbit\n```\n\n```text\ntypeorm\n```\n\n```text\nimport {ValueTransformer} from 'typeorm';\nclass BoolBitTransformer implements ValueTransformer {\n // To db from typeorm\n to(value: boolean | null): Buffer | null {\n if (value === null) {\n return null;\n }\n const res = new Buffer(1);\n res[0] = value ? 1 : 0;\n return res;\n }\n // From db to typeorm\n from(value: Buffer): boolean | null {\n if (value === null) {\n return null;\n }\n return value[0] === 1;\n }\n}\n```\n\n```text\n@Column({\n type: 'bit',\n nullable: false,\n default: () => `\"'b'1''\"`,\n name: 'can_read',\n transformer: new BoolBitTransformer()\n })\n can_read!: boolean;\n```\n\n```js\n@Column({\n name: 'FIELD_NAME',\n type: 'bit',\n transformer: { from: (v: Buffer) => !!v.readInt8(0), to: (v) => v },\n })\n readonly field: boolean;\n```\n\n```text\n@Column({\n name: 'FIELD_NAME',\n type: 'bit',\n transformer: { from: (v: Buffer) => !!v?.readInt8(0), to: (v) => v },\n })\n field: boolean;\n```\n\n========================================\n\nComments:\n- It looks to me like bit is supported as of this PR: github.com/typeorm/typeorm/pull/3310\n- @JesseCarter tried updating `typeorm` and `@nestjs/typeorm` to their latest versions.. no luck. Also tried with Mysql engine 8.0, no luck. It keeps returning `true` for everything.","metadata":{"transformedAt":"2026-08-18T18:33:44.707Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":196,"estimatedTokens":944}}313{"id":"stack-64002621","source":"stackoverflow","questionId":64002621,"title":"How to use onDelete: 'CASCADE' on one-to-one relationship","tags":["mysql","typescript","nestjs","typeorm"],"text":"Title: How to use onDelete: 'CASCADE' on one-to-one relationship\nTags: mysql, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI try to delete user's profile when user was deleted. But it's delete nothing on profile.\n\nUser Entity\n\n```\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToOne(type => Profile, profile => profile.user, \n { eager: true, cascade: true, onDelete: 'CASCADE' })\n @JoinColumn()\n profile: Profile;\n\n}\n```\n\nProfile Entity\n\n```\n@Entity()\nexport class Profile {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n gender: string;\n\n @Column()\n photo: string;\n\n @OneToOne(type => User, user => user.profile)\n user: User;\n\n}\n```\n\nHow I delete a user.\n\n```\nconst userRepository = connection.getRepository(User);\nconst user = await userRepository.findOne({ where: {id: 'someuserId'}, relations: [\"profile\"] });\n\nawait user.remove()\n```\n\nUser was removed but nothing happen on user's profile.\n\nCan anyone explain how to delete relationship on one-to-one?\n\n========================================\n\nTop Answer:\n### Solution\n\nI recently found myself in the same spot. I created a inheritance relationship in my database. Multiple entities reference one common entity which provides basic attributes for each specialized table. For example: Common attribute holder table \"Car\" and specialized tables \"Truck\", \"Bus\". Now I wanted to delete the corresponding \"Car\"-entity whenever a \"Truck\" or \"Bus\" is deleted.\n\nIn typeorm the specialized tables should reference the common attribute table. To make the `CASCADE DELETE` work, you have to specify the side which holds the id using the `@JoinColumn()` annotation. Then you have to specify the `onDelete: \"CASCADE\"` on the One-to-One relationship of the same side as the `@JoinColumn()` annotation.\n\nTo validate the created table you can use `SHOW CREATE TABLE table_name` in your database. There you will see if the `CASCADE DELETE` is present on the correct foreign key constraint. (It should be on the table holding the foreign key).\n\nThat means, it is not required to set the `CASCADE DELETE` on both sides.\n\n### Code example\n\n(see Gaurav Sharma's answer - modified)\n\n```\n// referenced table\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n // you can use eager on the none-owning side\n // this can be very helpful for inheritance\n @OneToOne(type => Profile, profile => profile.user, { eager: true })\n profile: Profile;\n}\n\n// owning side - foreign key in this table\n@Entity()\nexport class Profile {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n gender: string;\n\n @Column()\n photo: string;\n\n // specify onDelete here because owning side FK constraint would fail \n // and it needs to know what is going to happen\n @OneToOne(type => User, user => user.profile, { onDelete: \"CASCADE\" })\n @JoinColumn()\n user: User;\n\n}\n```\n\nFrom here on you would create a new user. Set the saved user in the profile to save and save the profile.\nDeleting the profile will not delete the user.\nDeleting the user will delete the profile.\n\nI also looked into `CASCADE DELETE` from both sides. From what I have found, you would have to specify the `@JoinColumn()` annotation on both sides, declaring `onDelete: \"CASCADE\"` on both sides. This will require at least two saves for new entities and I did not find further information in the docs concerning the bidirectional `CASCADE DELETE`. I would consider deleting manually in these situations because it might become very unclear what is going to happen and when entities need to be saved.\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToOne(type => Profile, profile => profile.user, \n { eager: true, cascade: true, onDelete: 'CASCADE' })\n @JoinColumn()\n profile: Profile;\n\n}\n```\n\n```text\n@Entity()\nexport class Profile {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n gender: string;\n\n @Column()\n photo: string;\n\n @OneToOne(type => User, user => user.profile)\n user: User;\n\n}\n```\n\n```text\nconst userRepository = connection.getRepository(User);\nconst user = await userRepository.findOne({ where: {id: 'someuserId'}, relations: [\"profile\"] });\n\nawait user.remove()\n```\n\n```text\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToOne(type => Profile, profile => profile.user, \n { eager: true, onDelete: 'CASCADE' })\n @JoinColumn()\n profile: Profile;\n}\n```\n\n```text\n@Entity()\nexport class Profile {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n gender: string;\n\n @Column()\n photo: string;\n\n @OneToOne(type => User, user => user.profile, { onDelete: \"CASCADE\" })\n user: User;\n\n}\n```\n\n```text\nconst userRepository = connection.getRepository(User);\nconst user = await userRepository.findOne({ where: {id: 'someuserId'} });\n\nconst profileRepository = connection.getRepository(Profile);\nconst profile = await profileRepository.findOne({ where: {id: user.profile.id} });\n\nawait profileRepository.remove(profile)\n```\n\n```text\nconst userRepository = connection.getRepository(User);\nconst user = await userRepository.findOne({ where: {id: 'someuserId'}, relations: [\"profile\"] });\n\nconst profileRepository = connection.getRepository(Profile);\nconst profile = await profileRepository.findOne({where: {id: user.profile.id}}).getOne()\n\nawait profile.remove()\nawait user.remove()\n```\n\n```js\n// referenced table\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n // you can use eager on the none-owning side\n // this can be very helpful for inheritance\n @OneToOne(type => Profile, profile => profile.user, { eager: true })\n profile: Profile;\n}\n\n\n// owning side - foreign key in this table\n@Entity()\nexport class Profile {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n gender: string;\n\n @Column()\n photo: string;\n\n // specify onDelete here because owning side FK constraint would fail \n // and it needs to know what is going to happen\n @OneToOne(type => User, user => user.profile, { onDelete: \"CASCADE\" })\n @JoinColumn()\n user: User;\n\n}\n```\n\n```text\nCASCADE DELETE\n```\n\n```text\n@JoinColumn()\n```\n\n```text\nonDelete: \"CASCADE\"\n```\n\n```text\n@JoinColumn()\n```\n\n```text\nSHOW CREATE TABLE table_name\n```\n\n```text\nCASCADE DELETE\n```\n\n```text\nCASCADE DELETE\n```\n\n```text\nCASCADE DELETE\n```\n\n```text\n@JoinColumn()\n```\n\n```text\nonDelete: \"CASCADE\"\n```\n\n```text\nCASCADE DELETE\n```\n\n========================================\n\nComments:\n- If you look at the actual tables in your SQL database, is there an actual cascade configured?\n- here is in Users --> CONSTRAINT `FK_ef7a0cc61d7873284f1cedc5d5d` FOREIGN KEY (`profileId`) REFERENCES `profile` (`id`) ON DELETE CASCADE\n- and this --> UNIQUE KEY `REL_ef7a0cc61d7873284f1cedc5d5` (`profileId`) @AluanHaddad\n- In SQL, the `cascade` specification belongs on the child or dependent table in the relationship. I assume that `Profile` depends on `User`, so you probably need to put the cascade specification on the other end of the relationship in the decorator.\n- `user.remove()` is this syntax correct? remove does not exist on user entity.\n- I try to define onDelete: \"CASCADE\" in both entities. profile still not remove. Should I change its to Many-to-one ?\n- Sorry, I forgot to mention some points. Check my answer again\n- That is a really counterintuitive API. Specifying it on both ends makes the code read as if deleting either end will cascade delete the other, I assume the owner is not subject to deletion if the owned entity is deleted.\n- Sadly, That's how it is working. I'll raise an issue on typeorm github.\n- See my answer again. I ran that code on my machine.","metadata":{"transformedAt":"2026-08-18T18:33:44.707Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":321,"estimatedTokens":1980}}314{"id":"stack-73520301","source":"stackoverflow","questionId":73520301,"title":"How to select fields from joined table using TypeORM repository?","tags":["typescript","database","orm","nestjs","typeorm"],"text":"Title: How to select fields from joined table using TypeORM repository?\nTags: typescript, database, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have 2 models with `one-to-many` connection - Post and User:\n\n```\nentities/post.entity.ts\n@Entity()\nexport class Post {\n ...\n @ManyToOne(() => User, (user) => user.posts) user: User;\n}\n\nentities/user.entity.ts\n@Entity()\nexport class User {\n ...\n @OneToMany(() => Post, (post) => post.user) posts: Post[];\n}\n```\n\nTo get data from database I use repositories, and my question is - how can I get only `userId` field from this query.\n\n```\nconstructor(\n @InjectRepository(Post) private postRepository: Repository\n) {}\n\nfindAll(): Promise {\n return this.postRepository.find({\n relations: ['user']\n });\n}\n```\n\nNow response looks like this:\n\n```\n{\n \"id\": 1,\n \"title\": \"Nam fringilla volutpat venenatis. Nulla et sem.\",\n \"content\": \"Aliquam tr...\",\n \"preview\": \"p1\",\n \"createdAt\": \"2022-08-28T11:52:44.833Z\",\n \"updatedAt\": \"2022-08-28T11:52:44.833Z\",\n \"user\": {\n \"id\": 1,\n \"firstName\": \"Timber\",\n \"lastName\": \"Saw\",\n \"createdAt\": \"2022-08-28T11:52:44.827Z\",\n \"updatedAt\": \"2022-08-28T11:52:44.827Z\"\n }\n },\n```\n\nCause now I just get the whole entity, but I want only `id` of user. I know, I can use `createQueryBuilder`, but is it possible to do using repositories?\n\n========================================\n\nTop Answer:\nThere can also be a case where you have **a chain of joins** and you need to select a field on the other end. I could not find the solution to this in TypeORM docs, so I thought this might help some people.\n\nSay joined tables are entity_1 and entity_2 in that order. Following is an example on how you would select specific properties of entity_2.\n\nAn important note here is that **you have to select entity_1_id** even if you don't actually need it. Without its presence, the join to entity_2 would fail. entity_0_id is similarly mandatory for this selection to happen.\n\n```\nthis.entity_0_repository.find({\n relations: { entity_1: { entity_2: true } },\n select: {\n entity_0_id: true, // => mandatory\n some_property: true,\n entity_1: {\n entity_1_id: true, // => mandatory\n some_property: true,\n entity_2: {\n some_property: true\n }\n }\n }\n}\n```\n\n========================================\n\nCode:\n```text\nentities/post.entity.ts\n@Entity()\nexport class Post {\n ...\n @ManyToOne(() => User, (user) => user.posts) user: User;\n}\n\nentities/user.entity.ts\n@Entity()\nexport class User {\n ...\n @OneToMany(() => Post, (post) => post.user) posts: Post[];\n}\n```\n\n```text\nconstructor(\n @InjectRepository(Post) private postRepository: Repository<Post>\n) {}\n\nfindAll(): Promise<Post[]> {\n return this.postRepository.find({\n relations: ['user']\n });\n}\n```\n\n```text\n{\n \"id\": 1,\n \"title\": \"Nam fringilla volutpat venenatis. Nulla et sem.\",\n \"content\": \"Aliquam tr...\",\n \"preview\": \"p1\",\n \"createdAt\": \"2022-08-28T11:52:44.833Z\",\n \"updatedAt\": \"2022-08-28T11:52:44.833Z\",\n \"user\": {\n \"id\": 1,\n \"firstName\": \"Timber\",\n \"lastName\": \"Saw\",\n \"createdAt\": \"2022-08-28T11:52:44.827Z\",\n \"updatedAt\": \"2022-08-28T11:52:44.827Z\"\n }\n },\n```\n\n```text\none-to-many\n```\n\n```text\nuserId\n```\n\n```text\nid\n```\n\n```text\ncreateQueryBuilder\n```\n\n```js\nthis.postRepository.find({\n relations: {\n user: true\n },\n select: {\n user: {\n id: true\n }\n }\n });\n```\n\n```text\nthis.entity_0_repository.find({\n relations: { entity_1: { entity_2: true } },\n select: {\n entity_0_id: true, // => mandatory\n some_property: true,\n entity_1: {\n entity_1_id: true, // => mandatory\n some_property: true,\n entity_2: {\n some_property: true\n }\n }\n }\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.707Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":179,"estimatedTokens":924}}315{"id":"stack-68992271","source":"stackoverflow","questionId":68992271,"title":"Meaning of using 'eager:true' option in TypeORM","tags":["typescript","typeorm","eager-loading","node.js-typeorm"],"text":"Title: Meaning of using 'eager:true' option in TypeORM\nTags: typescript, typeorm, eager-loading, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nI've been using TypeORM and I've got some problem when pushing data as follows:\n\n`User.ts` (Entity)\n\n```\n@OneToMany(type => Post, post => post.user)\nposts: Post[]\n```\n\n`Post.ts` (Entity)\n\n```\n@ManyToOne(type => User, user => user.posts)\nuser: User\n```\n\nAnd when I tried to do **Create Post** like this:\n\n`createPost.ts`\n\n```\n// Some Codes...\n\n// Save Post\nconst post = Post.create({\n title: title,\n content: content\n})\nawait post.save()\n\n// Update User\nconst user = await User.findOne({ uid: ctx.uid })\nuser.posts.push(post) // ****************** PROBLEM ******************\nawait user.save()\n```\n\nAs I marked **PROBLEM** above, when I requested this, I got `Cannot call method 'push of undefined` error.\n\nBut luckily I could've solved this by just adding following option at `User.ts` file:\n\n```\n@OneToMany(type => Post, post => post.user, {\n // -------------- added --------------\n eager: true\n // -----------------------------------\n})\nposts: Post[]\n```\n\nAnd I'd like to know why this works... I've read the typeorm document about Eager, and it says\n\nEager relations only work when you use find* methods. If you use QueryBuilder eager relations are disabled and have to use leftJoinAndSelect to load the relation. Eager relations can only be used on one side of the relationship, using eager: true on both sides of relationship is disallowed.\n\nBut I'm not sure what the last sentence means.\n\neager: true on both sides of relationship is disallowed.\n\nSo, I've disallowed the relation between `User` and `Post`, and the file now can understand `user.posts` is defined?\n\nCould somebody please help me with this...?\n\n========================================\n\nCode:\n```js\n@OneToMany(type => Post, post => post.user)\nposts: Post[]\n```\n\n```js\n@ManyToOne(type => User, user => user.posts)\nuser: User\n```\n\n```js\n// Some Codes...\n\n// Save Post\nconst post = Post.create({\n title: title,\n content: content\n})\nawait post.save()\n\n// Update User\nconst user = await User.findOne({ uid: ctx.uid })\nuser.posts.push(post) // ****************** PROBLEM ******************\nawait user.save()\n```\n\n```js\n@OneToMany(type => Post, post => post.user, {\n // -------------- added --------------\n eager: true\n // -----------------------------------\n})\nposts: Post[]\n```\n\n```text\nUser.ts\n```\n\n```text\nPost.ts\n```\n\n```text\ncreatePost.ts\n```\n\n```text\nCannot call method 'push of undefined\n```\n\n```text\nUser.ts\n```\n\n```text\nUser\n```\n\n```text\nPost\n```\n\n```text\nuser.posts\n```\n\n```js\n@OneToMany(type => Post, post => post.user, { eager: true })\nposts: Post[]\n```\n\n```js\n@ManyToOne(type => User, user => user.posts)\nuser: User\n```\n\n```text\neager: true\n```\n\n```text\nUser.ts\n```\n\n```text\nPost.ts\n```\n\n```text\nawait User.findOne({ uid: ctx.uid })\n```\n\n```text\nPost\n```\n\n```text\nUser\n```\n\n```text\nleftJoinAndSelect\n```\n\n========================================\n\nComments:\n- Thank you for commenting! So when `await User.findOne({ uid: ctx.uid })` runs, it automatically fetch data because they are related. And because they already loaded related data from `Post`, `user.posts` is not `undefined` any more? +) About the `eager: true` option, I can only set that option in one side, but still can grab data from either side? Either from `User`, get related `Post` or from `Post`, get related `User`? Did I understand what you mean?\n- And if I need to use `eager: true` option to make `user.posts` to be **defined** , do I have to add `eager: true` option for all `@OneToMany()` relationship..? If so, could I ask you one more thing? Could you please give an answer for why not TypeORM set that option by default...? Or any other references would be soooo grateful!! Thank you so much!!\n- Yes @TonyPark. You understood my point. eager loading means related data is automatically fetched. And even you used `eager: true` or not, still you can load the relationships using `Querybuilder`.\n- Very Well. Thanks for the explanation.\n- if you enabled `eager: true` in the Entity and need to get results without it ( without reflecting the `eager` flag ), you can use `loadEagerRelations: false` and the find method. `Entity..find({ loadEagerRelations: false });` github.com/typeorm/typeorm/blob/…","metadata":{"transformedAt":"2026-08-18T18:33:44.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":182,"estimatedTokens":1078}}316{"id":"stack-69243194","source":"stackoverflow","questionId":69243194,"title":"TypeORM/MySQL: Cannot delete or update a parent row: a foreign key constraint fails","tags":["mysql","node.js","typescript","typeorm"],"text":"Title: TypeORM/MySQL: Cannot delete or update a parent row: a foreign key constraint fails\nTags: mysql, node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have an entity relationship between `comments` and `posts` **`_many-to-one_`**. I'm using `typeorm` and `typegraphql`\n\nHere is my post entity:\n\n```\n@ObjectType()\n@Entity()\nexport class Post extends BaseEntity {\n constructor(input: InputI) {\n super();\n this.caption = input?.caption;\n this.imageURL = input?.imageURL;\n this.status = input?.status;\n this.user = input?.user;\n }\n\n @Field(() => Int)\n @PrimaryGeneratedColumn({ type: \"int\" })\n id: number;\n\n @Field(() => String, { nullable: true })\n @Column({ type: \"text\", nullable: true })\n caption?: string;\n\n @Field(() => String, { nullable: true })\n @Column({ type: \"text\", nullable: true })\n imageURL?: string;\n\n @Field(() => String, { nullable: true })\n @Column({ type: \"text\", nullable: true })\n status?: string;\n\n // Relations\n @Field(() => User)\n @ManyToOne(() => User, (user) => user.posts)\n user: User;\n\n @Field(() => [Comments], { nullable: true })\n @OneToMany(() => Comments, (comment) => comment.post, {\n onDelete: \"CASCADE\",\n onUpdate: \"CASCADE\",\n })\n comments: Comments[];\n\n @Field(() => [Likes], { nullable: true })\n @OneToMany(() => Likes, (like) => like.post, {\n onDelete: \"CASCADE\",\n onUpdate: \"CASCADE\",\n })\n likes: Likes[];\n\n @Field(() => String)\n @CreateDateColumn({ nullable: false })\n createdAt: Date;\n \n @Field(() => String)\n @UpdateDateColumn({ nullable: false })\n updatedAt: Date;\n}\n```\n\nHere is my Comment Entity:\n\n```\n@ObjectType()\n@Entity()\nexport class Comments extends BaseEntity {\n @Field(() => Int)\n @PrimaryGeneratedColumn({ type: \"int\" })\n id: number;\n\n @Field(() => String)\n @Column({ nullable: true })\n avatar: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n comment: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n email: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n username: string;\n\n @Field(() => String)\n @Column({ nullable: true })\n phoneNumber: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n gender: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n status: string;\n\n @Field(() => String)\n @Column({ nullable: true, type: \"text\" })\n bio: string;\n\n @Field(() => Boolean)\n @Column({ nullable: false, default: false })\n verified: false | true;\n // @Field(() => [Comments], { nullable: true })\n // @OneToMany(() => Comments, (comment) => comment)\n // @JoinColumn()\n // replies: Comments[];\n // @ManyToOne(() => Post, (post) => post.likes)\n // post: Post;\n\n @ManyToOne(() => Post, (post) => post.comments)\n post: Post;\n //\n @Field(() => String)\n @CreateDateColumn({ type: \"datetime\", nullable: false })\n createdAt: Date;\n\n @Field(() => String)\n @UpdateDateColumn({ type: \"datetime\", nullable: false })\n updatedAt: Date;\n}\n```\n\nI don't have any problem with other mutation, the only problem comes when i want to delete a post. I'm getting the following error in the GraphQLPlayGround:\n\n```\n\"errors\": [\n {\n \"message\": \"Cannot delete or update a parent row: a foreign key constraint fails (`likeme`.`comments`, CONSTRAINT `FK_e44ddaaa6d058cb4092f83ad61f` FOREIGN KEY (`postId`) REFERENCES `post` (`id`))\",\n...\n}\n```\n\nHere is my resolver that delete a posts.\n\n```\n@Resolver()\nexport class DeletePostResolver {\n @Mutation(() => Boolean)\n async deletePost(\n @Arg(\"id\", () => Int) id: number,\n @Ctx() { req }: UserContext\n ): Promise {\n const post = await Post.findOne(\n { id },\n { relations: [\"user\", \"comments\", \"likes\"] }\n );\n if (post?.user.id === req.session.userId) {\n await Post.delete({ id });\n return true;\n }\n return false;\n }\n}\n```\n\nWhat maybe possibly my problem, I've set the `onDelete` to `CASCADE` so what's wrong here? **Help please.**\n\n========================================\n\nCode:\n```text\n@ObjectType()\n@Entity()\nexport class Post extends BaseEntity {\n constructor(input: InputI) {\n super();\n this.caption = input?.caption;\n this.imageURL = input?.imageURL;\n this.status = input?.status;\n this.user = input?.user;\n }\n\n @Field(() => Int)\n @PrimaryGeneratedColumn({ type: \"int\" })\n id: number;\n\n @Field(() => String, { nullable: true })\n @Column({ type: \"text\", nullable: true })\n caption?: string;\n\n @Field(() => String, { nullable: true })\n @Column({ type: \"text\", nullable: true })\n imageURL?: string;\n\n @Field(() => String, { nullable: true })\n @Column({ type: \"text\", nullable: true })\n status?: string;\n\n // Relations\n @Field(() => User)\n @ManyToOne(() => User, (user) => user.posts)\n user: User;\n\n @Field(() => [Comments], { nullable: true })\n @OneToMany(() => Comments, (comment) => comment.post, {\n onDelete: \"CASCADE\",\n onUpdate: \"CASCADE\",\n })\n comments: Comments[];\n\n @Field(() => [Likes], { nullable: true })\n @OneToMany(() => Likes, (like) => like.post, {\n onDelete: \"CASCADE\",\n onUpdate: \"CASCADE\",\n })\n likes: Likes[];\n\n @Field(() => String)\n @CreateDateColumn({ nullable: false })\n createdAt: Date;\n \n @Field(() => String)\n @UpdateDateColumn({ nullable: false })\n updatedAt: Date;\n}\n```\n\n```text\n@ObjectType()\n@Entity()\nexport class Comments extends BaseEntity {\n @Field(() => Int)\n @PrimaryGeneratedColumn({ type: \"int\" })\n id: number;\n\n @Field(() => String)\n @Column({ nullable: true })\n avatar: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n comment: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n email: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n username: string;\n\n @Field(() => String)\n @Column({ nullable: true })\n phoneNumber: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n gender: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n status: string;\n\n @Field(() => String)\n @Column({ nullable: true, type: \"text\" })\n bio: string;\n\n @Field(() => Boolean)\n @Column({ nullable: false, default: false })\n verified: false | true;\n // @Field(() => [Comments], { nullable: true })\n // @OneToMany(() => Comments, (comment) => comment)\n // @JoinColumn()\n // replies: Comments[];\n // @ManyToOne(() => Post, (post) => post.likes)\n // post: Post;\n\n @ManyToOne(() => Post, (post) => post.comments)\n post: Post;\n //\n @Field(() => String)\n @CreateDateColumn({ type: \"datetime\", nullable: false })\n createdAt: Date;\n\n @Field(() => String)\n @UpdateDateColumn({ type: \"datetime\", nullable: false })\n updatedAt: Date;\n}\n```\n\n```text\n\"errors\": [\n {\n \"message\": \"Cannot delete or update a parent row: a foreign key constraint fails (`likeme`.`comments`, CONSTRAINT `FK_e44ddaaa6d058cb4092f83ad61f` FOREIGN KEY (`postId`) REFERENCES `post` (`id`))\",\n...\n}\n```\n\n```text\n@Resolver()\nexport class DeletePostResolver {\n @Mutation(() => Boolean)\n async deletePost(\n @Arg(\"id\", () => Int) id: number,\n @Ctx() { req }: UserContext\n ): Promise<Boolean> {\n const post = await Post.findOne(\n { id },\n { relations: [\"user\", \"comments\", \"likes\"] }\n );\n if (post?.user.id === req.session.userId) {\n await Post.delete({ id });\n return true;\n }\n return false;\n }\n}\n```\n\n```text\ncomments\n```\n\n```text\nposts\n```\n\n```text\n_many-to-one_\n```\n\n```text\ntypeorm\n```\n\n```text\ntypegraphql\n```\n\n```text\nonDelete\n```\n\n```text\nCASCADE\n```\n\n```js\n@ObjectType()\n@Entity()\nexport class Comments extends BaseEntity {\n @Field(() => Int)\n @PrimaryGeneratedColumn({ type: \"int\" })\n id: number;\n\n @Field(() => String)\n @Column({ nullable: true })\n avatar: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n comment: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n email: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n username: string;\n\n @Field(() => String)\n @Column({ nullable: true })\n phoneNumber: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n gender: string;\n\n @Field(() => String)\n @Column({ nullable: false })\n status: string;\n\n @Field(() => String)\n @Column({ nullable: true, type: \"text\" })\n bio: string;\n\n @Field(() => Boolean)\n @Column({ nullable: false, default: false })\n verified: false | true;\n // @Field(() => [Comments], { nullable: true })\n // @OneToMany(() => Comments, (comment) => comment)\n // @JoinColumn()\n // replies: Comments[];\n // @ManyToOne(() => Post, (post) => post.likes)\n // post: Post;\n\n @ManyToOne(() => Post, (post) => post.comments, {\n onDelete: \"CASCADE\", // <---- HERE\n })\n post: Post;\n //\n @Field(() => String)\n @CreateDateColumn({ type: \"datetime\", nullable: false })\n createdAt: Date;\n\n @Field(() => String)\n @UpdateDateColumn({ type: \"datetime\", nullable: false })\n updatedAt: Date;\n}\n```\n\n```text\nonDelete\n```\n\n```text\nComment\n```\n\n```text\npost\n```\n\n```text\nPost\n```\n\n```text\npost\n```\n\n```text\nComment\n```\n\n```text\nonDelete\n```\n\n```text\npost\n```\n\n========================================\n\nComments:\n- If I'm not wrong this option { onDelete: \"CASCADE\", // <---- HERE } deletes all the comments related to the post when post is deleted, is there any way we can keep the comments even if Post is delete. My scenario is a bit different. In my case all the transaction store a client_id, all the clients and transactions are maintained in separate tables in many to one relation, how can I delete the client but keep the transaction entries?\n- please check link, Ted explain triggers, maybe help you.","metadata":{"transformedAt":"2026-08-18T18:33:44.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":448,"estimatedTokens":2346}}317{"id":"stack-59766628","source":"stackoverflow","questionId":59766628,"title":"TypeORM: Define relation in migration","tags":["node.js","sequelize.js","typeorm","typeorm-datamapper"],"text":"Title: TypeORM: Define relation in migration\nTags: node.js, sequelize.js, typeorm, typeorm-datamapper\nSource: Stack Overflow\n\nQuestion:\nHi I'm reading TypeORM docs, and trying to implement relations like showed here\nIm trying to have History model that relates to every User, so that each user has multiple history \n\nIm reading this & using that example:\n\nhttps://github.com/typeorm/typeorm/blob/master/docs/many-to-one-one-to-many-relations.md\n\nBut after try to implement it I get column userId on History model does not exist ??\n\nDoes anyone know what could be the problem ?\n\nIm assuming I should add relation in migration file for my Model but I do not see any of that in documentation ?\n\n========================================\n\nCode:\n```js\nexport class ExampleMigration implements MigrationInterface {\n public async up(queryRunner: QueryRunner): Promise<any> {\n await queryRunner.createTable(\n new Table({\n name: 'stuff',\n columns: [\n {\n name: 'id',\n type: 'uuid',\n isPrimary: true\n },\n {\n name: 'userId',\n type: 'uuid'\n }\n ]\n })\n );\n\n await queryRunner.createForeignKey(\n 'stuff',\n new TableForeignKey({\n columnNames: ['userId'],\n referencedTableName: 'users',\n referencedColumnNames: ['id']\n })\n );\n }\n\n public async down(queryRunner: QueryRunner): Promise<any> {\n await queryRunner.dropTable('userSessions');\n }\n}\n```\n\n```text\ncreateForeignKey\n```\n\n========================================\n\nComments:\n- Have you tried to let TypeORM generate the migration file for you? That should add the needed columns and foreign key constraints to the migration.\n- Yes I checked found solution by looking at the docs thank you :)","metadata":{"transformedAt":"2026-08-18T18:33:44.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":66,"estimatedTokens":451}}318{"id":"stack-62596751","source":"stackoverflow","questionId":62596751,"title":"TypeORM - Search and populate Many-to-Many relation","tags":["typeorm"],"text":"Title: TypeORM - Search and populate Many-to-Many relation\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI have two entities `Tag` and `Photo`:\n\n```\n// tag.entity.ts\n\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Tag {\n @PrimaryGeneratedColumn()\n id!: number;\n\n // Other columns\n}\n```\n\n```\n// photo.entity.ts\n\nimport { Entity, JoinTable, ManyToMany, PrimaryGeneratedColumn, } from 'typeorm';\nimport { Tag } from './tag.entity';\n\n@Entity()\nexport class Photo {\n @PrimaryGeneratedColumn()\n id!: number;\n\n @ManyToMany(type => Tag, { eager: true })\n @JoinTable()\n tags!: Tag[];\n\n // Other columns\n}\n```\n\nI need to filter results from `photos` table using results from `tags` table.\n\n```\nconst photos = await photosRepository\n .createQueryBuilder('photo')\n .leftJoinAndSelect('photo.tags', 'tag')\n .where('tag.name LIKE :searchQuery', { searchQuery: 'nature%' })\n .skip(0)\n .take(10)\n .getMany();\n```\n\nThe query above works fine: `photos` table records are filtered using `tag.name` column from `tags` table.\n\nThe issue is that an each photo entity in returned `photos` array contains **only** filtered (`tag.name LIKE :searchQuery`) `tags` relation entities. What I need is to eager load **all** `tags` relation entities for each photo. Is it possible somehow?\n\nFor example, with Laravel's Eloquent it's possible achive what I need with:\n\n```\n$photos = Photo::query()\n ->with('tags')\n ->whereHas('tags', function (Builder $query) {\n $query->where('tags.name', 'like', 'nature%');\n })\n ->skip(0)\n ->take(10)\n ->get();\n```\n\n========================================\n\nCode:\n```text\n// tag.entity.ts\n\nimport { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Tag {\n @PrimaryGeneratedColumn()\n id!: number;\n\n // Other columns\n}\n```\n\n```text\n// photo.entity.ts\n\nimport { Entity, JoinTable, ManyToMany, PrimaryGeneratedColumn, } from 'typeorm';\nimport { Tag } from './tag.entity';\n\n@Entity()\nexport class Photo {\n @PrimaryGeneratedColumn()\n id!: number;\n\n @ManyToMany(type => Tag, { eager: true })\n @JoinTable()\n tags!: Tag[];\n\n // Other columns\n}\n```\n\n```text\nconst photos = await photosRepository\n .createQueryBuilder('photo')\n .leftJoinAndSelect('photo.tags', 'tag')\n .where('tag.name LIKE :searchQuery', { searchQuery: 'nature%' })\n .skip(0)\n .take(10)\n .getMany();\n```\n\n```text\n$photos = Photo::query()\n ->with('tags')\n ->whereHas('tags', function (Builder $query) {\n $query->where('tags.name', 'like', 'nature%');\n })\n ->skip(0)\n ->take(10)\n ->get();\n```\n\n```text\nTag\n```\n\n```text\nPhoto\n```\n\n```text\nphotos\n```\n\n```text\ntags\n```\n\n```text\nphotos\n```\n\n```text\ntag.name\n```\n\n```text\ntags\n```\n\n```text\nphotos\n```\n\n```text\ntag.name LIKE :searchQuery\n```\n\n```text\ntags\n```\n\n```text\ntags\n```\n\n```js\nconst photos = await photosRepository\n .createQueryBuilder('photo')\n .leftJoin('photo.tags', 'tag')\n .leftJoinAndSelect('photo.tags', 'tagSelect')\n .where('tag.name LIKE :searchQuery', { searchQuery: 'nature%' })\n .skip(0)\n .take(10)\n .getMany();\n```\n\n========================================\n\nComments:\n- You can add join of each relation, e.g. as you have made with tags\n- @ArtOlshansky I don't need to join other relations. My question was how to load all related tags for resulting photos. Right now it only loads tags which meet where clause condition from the query.\n- need help also here : (\n- @HuaenTan There is a good answer which adds additional details, though I don't think it's satisfiable: stackoverflow.com/a/52249577/2380334\n- i don't know,but this answer changes a lot code, so maybe waiting for a better way. My question is basically the same as yours","metadata":{"transformedAt":"2026-08-18T18:33:44.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":189,"estimatedTokens":916}}319{"id":"stack-57599204","source":"stackoverflow","questionId":57599204,"title":"Using NestJS and TypeOrm, the tables are not being created automatically after I run the NestJS application","tags":["postgresql","typescript","config","nestjs","typeorm"],"text":"Title: Using NestJS and TypeOrm, the tables are not being created automatically after I run the NestJS application\nTags: postgresql, typescript, config, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nUsing a postgres DB, I am able to connect to the database, however even when following tutorials step-by-step, after creating the user.entity.ts file (code below), nothing in the database changes. \n\npostgres/typeorm are installed correctly as far as im aware with latest versions.\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'\n\n@Entity()\nexport class Users {\n\n @PrimaryGeneratedColumn('uuid')\n id: number\n\n @Column({\n length: 50\n })\n firstName: string;\n}\n```\n\nHere is the ormconfig.json\n\n```\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": \"5432\",\n \"username\": \"postgres\",\n \"password\": \"pw\",\n \"database\": \"metabook\",\n \"synchronise\": true,\n \"logging\": true,\n \"entities\": [\"./dist/**/*.entity{.ts,.js}\"]\n}\n```\n\nIt should be adding the 'users' table with 2 columns (id and firstName). In the console, logging, as its set to true in the ormconfig.json, should show the sql queries being run to create the table, but nothing happens other than the success of running the application (output below).\n\nOutput\n\nExpected output from tutorial video\n\nAnyone know if I am missing something?\n\n========================================\n\nCode:\n```text\nimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'\n\n@Entity()\nexport class Users {\n\n @PrimaryGeneratedColumn('uuid')\n id: number\n\n @Column({\n length: 50\n })\n firstName: string;\n}\n```\n\n```text\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": \"5432\",\n \"username\": \"postgres\",\n \"password\": \"pw\",\n \"database\": \"metabook\",\n \"synchronise\": true,\n \"logging\": true,\n \"entities\": [\"./dist/**/*.entity{.ts,.js}\"]\n}\n```\n\n========================================\n\nComments:\n- I think the key value is `synchronize` right?\n- Your completly right. Too used to UK spelling, thanks for pointing it out! Working as expected now","metadata":{"transformedAt":"2026-08-18T18:33:44.707Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":87,"estimatedTokens":512}}320{"id":"stack-64203055","source":"stackoverflow","questionId":64203055,"title":"TypeORM insert basic master data (types, status,..) after creating the table","tags":["typescript","nestjs","typeorm"],"text":"Title: TypeORM insert basic master data (types, status,..) after creating the table\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have question for you. I am using NestJS and typeORM. I am trying to insert default values to tables after creating the tables. For example i have a priority table and i need to insert High/Medium/Low values. I tried everything from typeorm and nestJS documentation and I read related questions and answers from here. I could not do it yet.\n\n```\nimport {getConnection} from \"typeorm\";\n\nawait getConnection()\n .createQueryBuilder()\n .insert()\n .into(User)\n .values([\n { firstName: \"Timber\", lastName: \"Saw\" }, \n { firstName: \"Phantom\", lastName: \"Lancer\" }\n ])\n .execute();\n```\n\nI have found above code and i think the way is this. But i could not find in which file should i use this code chunk. If you help me i will be very happy. Thanks.\n\n========================================\n\nTop Answer:\nI use migrations for this purpose. We can write static query or we can also load data from CSV and then save it in DB in a loop.\n\nyou can create an empty migration with `npx typeorm migration:create -n InsertMasterDataInDB`\n\nand then you can use below query to insert data\n\n`await queryRunner.manager.query(INSERT QUERY HERE IN SINGLE QUOTES);`\n\nand then `npx typeorm migration:run`\n\n========================================\n\nCode:\n```text\nimport {getConnection} from \"typeorm\";\n\nawait getConnection()\n .createQueryBuilder()\n .insert()\n .into(User)\n .values([\n { firstName: \"Timber\", lastName: \"Saw\" }, \n { firstName: \"Phantom\", lastName: \"Lancer\" }\n ])\n .execute();\n```\n\n```text\nnpx typeorm migration:create -n InsertMasterDataInDB\n```\n\n```text\nawait queryRunner.manager.query(INSERT QUERY HERE IN SINGLE QUOTES);\n```\n\n```text\nnpx typeorm migration:run\n```\n\n========================================\n\nComments:\n- Thanks for your reply. In documentation i could not see any sample like my case. Do you have a working sample? or it will be a good article somewhere on the web.\n- Here is a good practical guide for using this technique. But there is a nuance. QueryRunner has no methods for inserting data into the database. I found a useful closed issue that says how to access QueryBuilder through a reference to the Entities Manager.","metadata":{"transformedAt":"2026-08-18T18:33:44.707Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":70,"estimatedTokens":579}}321{"id":"stack-49612296","source":"stackoverflow","questionId":49612296,"title":"How to handle blob column in TypeORM","tags":["mysql","node.js","typeorm"],"text":"Title: How to handle blob column in TypeORM\nTags: mysql, node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a MySQL database that stores profile images of users. The user info should be provided via REST API that is implemented as a Node.js server. I use TypeORM for accessing the database.\n\nI want to deliver the image info as base64 string via REST API. How could I achieve this?\n\nI mapped the blob column as a Buffer in my entity. Do I have to convert the data to base64 using a listener on the property?\n\n========================================\n\nTop Answer:\nFor a cleaner code, you can try using a transformer.\nHere's a usage example for saving and retrieving a string from a blob column.\n\n```\n@Column({\n transformer: {\n to: (value: string) => Buffer.from(value),\n from: (value: Buffer) => value.toString()\n }\n })\n longText?: string;\n```\n\n========================================\n\nCode:\n```text\nBuffer.from(user.profileImage).toString('base64');\n```\n\n```text\n@Column({\n transformer: {\n to: (value: string) => Buffer.from(value),\n from: (value: Buffer) => value.toString()\n }\n })\n longText?: string;\n```\n\n========================================\n\nComments:\n- No one ever used TypeORM with blob columns?\n- Yes, only your question helped me find it, years later. Tell me if you find any better technique than this.\n- No, but to be honest, I did not search for an alternative solution :-)\n- Awesome! Saved me a lot of headache - Thanks!","metadata":{"transformedAt":"2026-08-18T18:33:44.707Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":51,"estimatedTokens":366}}322{"id":"stack-61767281","source":"stackoverflow","questionId":61767281,"title":"NestJs unit testing on typeorm pagination getting error queryBuilder.take(...).skip is not a function","tags":["unit-testing","jestjs","nestjs","typeorm"],"text":"Title: NestJs unit testing on typeorm pagination getting error queryBuilder.take(...).skip is not a function\nTags: unit-testing, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to mock createQueryBuilder to unit test pagination part, But i am getting below error\n\n queryBuilder.take(...).skip is not a function\n\nMy Mock for createQueryBuilder \n\n```\ncreateQueryBuilder: jest.fn(() => ({\n delete: jest.fn().mockReturnThis(),\n innerJoinAndSelect: jest.fn().mockReturnThis(),\n innerJoin: jest.fn().mockReturnThis(),\n from: jest.fn().mockReturnThis(),\n where: jest.fn().mockReturnThis(),\n execute: jest.fn().mockReturnThis(),\n getOne: jest.fn().mockReturnThis(),\n orderBy : jest.fn().mockReturnThis(),\n take : skip => ({\n skip: 5\n }), \n }))\n```\n\nUnit Test for Find all\n\n```\nit(\"Find All\", async () => {\n const pageData: PaginationDto = {\n page: 1,\n limit: 10,\n sortBy: \"id\",\n sortOrder: -1,\n relatinalData: relatinalData.no\n\n };\n expect(await service.getGroups(pageData)).toEqual({\n docs: [{\n groupName: \"group123\",\n description: \"Group Description\",\n roleId: 1\n },\n {\n groupName: \"group123\",\n description: \"Group Description\",\n roleId: 1\n }]\n });\n});\n```\n\nServices\n\n```\nimport { paginate } from 'nestjs-typeorm-paginate';\n\nasync getGroups(paginationDto: PaginationDto) {\n const pageOptions = await this.databaseService.preparePageData(paginationDto, 'groups');\n const queryBuilder = this.groupModel.createQueryBuilder('groups');\n const flag = paginationDto.relatinalData;\n if (relatinalData.yes === flag) {\n queryBuilder.leftJoinAndSelect(\"groups.role\", \"role\");\n }\n queryBuilder.orderBy(pageOptions.order);\n pageOptions['route'] = environment.hostname + \"groups\";\n return await paginate(queryBuilder,pageOptions);\n}\n```\n\nPagination page option Prepare function\n\n```\nasync preparePageData(paginationDto, modelName) {\n const sort = {};\n if (paginationDto.sortBy && paginationDto.sortOrder) {\n const sortValue = paginationDto.sortBy\n const sortOrder = paginationDto.sortOrder;\n if (paginationDto.relatinalData && relatinalData.yes === paginationDto.relatinalData) {\n sort[modelName + '.' + sortValue] = sortOrder;\n } else {\n sort[sortValue] = sortOrder;\n }\n }\n const options = {\n page: paginationDto.page ? Number(paginationDto.page) : constant.pageLimit,\n limit: paginationDto.limit ? Number(paginationDto.limit) : constant.limit,\n order: sort ? sort : constant.sort\n };\n return options;\n}\n```\n\nCan any one please help me to mock **nestjs-typeorm-paginate**\n\n========================================\n\nTop Answer:\nin your code `skip` is a parameter passed to function `take`. If you want `skip` to be a property of child object you have to enhance code in this way\n\n```\ncreateQueryBuilder: jest.fn(() => ({\n delete: jest.fn().mockReturnThis(),\n innerJoinAndSelect: jest.fn().mockReturnThis(),\n innerJoin: jest.fn().mockReturnThis(),\n from: jest.fn().mockReturnThis(),\n where: jest.fn().mockReturnThis(),\n execute: jest.fn().mockReturnThis(),\n getOne: jest.fn().mockReturnThis(),\n orderBy : jest.fn().mockReturnThis(),\n take : () => ({\n skip: (cnt) => ({\n skip: cnt\n }), \n })\n }))\n```\n\n========================================\n\nCode:\n```text\ncreateQueryBuilder: jest.fn(() => ({\n delete: jest.fn().mockReturnThis(),\n innerJoinAndSelect: jest.fn().mockReturnThis(),\n innerJoin: jest.fn().mockReturnThis(),\n from: jest.fn().mockReturnThis(),\n where: jest.fn().mockReturnThis(),\n execute: jest.fn().mockReturnThis(),\n getOne: jest.fn().mockReturnThis(),\n orderBy : jest.fn().mockReturnThis(),\n take : skip => ({\n skip: 5\n }), \n }))\n```\n\n```text\nit(\"Find All\", async () => {\n const pageData: PaginationDto = {\n page: 1,\n limit: 10,\n sortBy: \"id\",\n sortOrder: -1,\n relatinalData: relatinalData.no\n\n };\n expect(await service.getGroups(pageData)).toEqual({\n docs: [{\n groupName: \"group123\",\n description: \"Group Description\",\n roleId: 1\n },\n {\n groupName: \"group123\",\n description: \"Group Description\",\n roleId: 1\n }]\n });\n});\n```\n\n```text\nimport { paginate } from 'nestjs-typeorm-paginate';\n\nasync getGroups(paginationDto: PaginationDto) {\n const pageOptions = await this.databaseService.preparePageData(paginationDto, 'groups');\n const queryBuilder = this.groupModel.createQueryBuilder('groups');\n const flag = paginationDto.relatinalData;\n if (relatinalData.yes === flag) {\n queryBuilder.leftJoinAndSelect(\"groups.role\", \"role\");\n }\n queryBuilder.orderBy(pageOptions.order);\n pageOptions['route'] = environment.hostname + \"groups\";\n return await paginate(queryBuilder,pageOptions);\n}\n```\n\n```text\nasync preparePageData(paginationDto, modelName) {\n const sort = {};\n if (paginationDto.sortBy && paginationDto.sortOrder) {\n const sortValue = paginationDto.sortBy\n const sortOrder = paginationDto.sortOrder;\n if (paginationDto.relatinalData && relatinalData.yes === paginationDto.relatinalData) {\n sort[modelName + '.' + sortValue] = sortOrder;\n } else {\n sort[sortValue] = sortOrder;\n }\n }\n const options = {\n page: paginationDto.page ? Number(paginationDto.page) : constant.pageLimit,\n limit: paginationDto.limit ? Number(paginationDto.limit) : constant.limit,\n order: sort ? sort : constant.sort\n };\n return options;\n}\n```\n\n```text\ncreateQueryBuilder: jest.fn(() => ({\n leftJoinAndSelect: jest.fn().mockReturnThis(),\n orderBy: jest.fn().mockReturnThis(),\n take: jest.fn().mockReturnThis(),\n skip: jest.fn().mockReturnThis(),\n getManyAndCount: jest.fn().mockResolvedValue([groupPageResponse]),\n }))\n```\n\n```js\ncreateQueryBuilder: jest.fn(() => ({\n delete: jest.fn().mockReturnThis(),\n innerJoinAndSelect: jest.fn().mockReturnThis(),\n innerJoin: jest.fn().mockReturnThis(),\n from: jest.fn().mockReturnThis(),\n where: jest.fn().mockReturnThis(),\n execute: jest.fn().mockReturnThis(),\n getOne: jest.fn().mockReturnThis(),\n orderBy : jest.fn().mockReturnThis(),\n take : () => ({\n skip: (cnt) => ({\n skip: cnt\n }), \n })\n }))\n```\n\n```text\nskip\n```\n\n```text\ntake\n```\n\n```text\nskip\n```\n\n========================================\n\nComments:\n- Sorry, But its not working i am getting same error \"queryBuilder.take is not a function\". I think its related to nestjs-typeorm-paginate because of this i am not able to mock paginate\n- this means that function `skip` was called not after `take`\n- Can you the code where you actually mocked createQueryBuilder","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":247,"estimatedTokens":1666}}323{"id":"stack-53561491","source":"stackoverflow","questionId":53561491,"title":"How to set up typeorm .env file?","tags":["javascript","node.js","environment-variables","nestjs","typeorm"],"text":"Title: How to set up typeorm .env file?\nTags: javascript, node.js, environment-variables, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI've created a `ormconfig.env` file in the nestjs starter project and put the variables from this documentation in there and added this line here\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRoot(),\n TaskModule,\n ],\n})\nexport class AppModule {\n}`\n```\n\nAnd the console shows this error:\n\n`Error: EACCES: permission denied, scandir '/Library/Application Support/Apple/AssetCache/Data' at Object.fs.readdirSync (fs.js:904:18)`\n\nHow should I properly set up typeorm .env file in nestjs?\n\n========================================\n\nTop Answer:\nI had the same problem as in the question. As the other answer didn't solve my problem, I had to look around. I will leave my solution for those who also have similar troubles with Webpack + TypeORM, as I had.\n\nHere is what I needed to do to make it work.\n\n```\nimport { createConnection, getConnectionManager } from \"typeorm\";\n\n// For hot reload to work need to require files\nimport { Job } from \"../jobs/job.entity\";\nimport { JobAction } from \"../jobs/jobaction.entity\";\n\nexport const databaseProviders = [\n {\n provide: \"DATABASE_CONNECTION\",\n keepConnectionAlive: true,\n useFactory: async () => {\n try {\n const conn = await createConnection({\n ...connectionOption,\n // add entitities manually\n entities: [Job, JobAction],\n });\n return conn;\n } catch (err) {\n // If AlreadyHasActiveConnectionError occurs, return already existent connection\n if (err.name === \"AlreadyHasActiveConnectionError\") {\n const existentConn = getConnectionManager().get(\"default\");\n return existentConn;\n }\n throw err;\n }\n },\n },\n];\n```\n\n========================================\n\nCode:\n```text\n@Module({\n imports: [\n TypeOrmModule.forRoot(),\n TaskModule,\n ],\n})\nexport class AppModule {\n}`\n```\n\n```text\normconfig.env\n```\n\n```text\nError: EACCES: permission denied, scandir '/Library/Application Support/Apple/AssetCache/Data' at Object.fs.readdirSync (fs.js:904:18)\n```\n\n```text\nTYPEORM_ENTITIES = src/**/**.entity.ts\n```\n\n```text\nTYPEORM_ENTITIES\n```\n\n```text\n.entity.ts\n```\n\n```text\nsrc\n```\n\n```text\nimport { createConnection, getConnectionManager } from \"typeorm\";\n\n// For hot reload to work need to require files\nimport { Job } from \"../jobs/job.entity\";\nimport { JobAction } from \"../jobs/jobaction.entity\";\n\nexport const databaseProviders = [\n {\n provide: \"DATABASE_CONNECTION\",\n keepConnectionAlive: true,\n useFactory: async () => {\n try {\n const conn = await createConnection({\n ...connectionOption,\n // add entitities manually\n entities: [Job, JobAction],\n });\n return conn;\n } catch (err) {\n // If AlreadyHasActiveConnectionError occurs, return already existent connection\n if (err.name === \"AlreadyHasActiveConnectionError\") {\n const existentConn = getConnectionManager().get(\"default\");\n return existentConn;\n }\n throw err;\n }\n },\n },\n];\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":132,"estimatedTokens":760}}324{"id":"stack-62424075","source":"stackoverflow","questionId":62424075,"title":"Materialized View from NestJS/TypeORM project","tags":["nestjs","typeorm"],"text":"Title: Materialized View from NestJS/TypeORM project\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create a Materialized view from my NestJS app using TypeORM.\nThe database is a Postgres.\n\nView Entities unfortunately doesn't match requirements: https://www.bookstack.cn/read/TypeORM/view-entities.md\n\nWished behaviour: just like models, a materialized view is defined in the NestJS project, with the option 'synchronize:true' : the project creates the view on running if it doesn't exist, if it exist, it just sync with it (just like models).\n\nIs there any leads that would help me achieving this?\n\n========================================\n\nCode:\n```text\n{materialized:true}\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":20,"estimatedTokens":176}}325{"id":"stack-69727991","source":"stackoverflow","questionId":69727991,"title":"Postgres jsonb query for dynamic values","tags":["sql","node.js","postgresql","sequelize.js","typeorm"],"text":"Title: Postgres jsonb query for dynamic values\nTags: sql, node.js, postgresql, sequelize.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn the users table I have a jsob column `experience` with following json structure:\n\n```\n[\n {\n \"field\": \"devops\",\n \"years\": 9\n },\n {\n \"field\": \"backend dev\",\n \"years\": 7\n } \n... // could be N number of objects with different values\n]\n```\n\n**Business requirement**\n\nClient can request for people with experience in any field and with their respective years experience in each\n\n**This is an example query**\n\n```\nSELECT * FROM users\nWHERE\njsonb_path_exists(experience, '$[*] ? (@.field == \"devops\" && @.years > 5)') and\njsonb_path_exists(experience, '$[*] ? (@.field == \"backend dev\" && @.years > 5)')\nLIMIT 3;\n```\n\n### Issue\n\nLets say if I get a request for\n\n```\n[\n { field: \"devops\", years: 5 }, \n { field: \"java\", years: 6 }, \n { field: \"ui/ux\", years: 2 }] // and so on\n```\n\nHow do I dynamically create a query without worrying about sql injection?\n\n### Techstack\n\n- Nodejs\n\n- Typescript\n\n- TypeORM\n\n- Postgres\n\n========================================\n\nTop Answer:\nThis is a parameterized query so more or less injection safe. `qualifies` scalar subquery calculates whether `experience` satisfies all request items. The parameters are `$1` (the jsonb array of request parameters) and `$2` (the limit value). You may need to change their syntax depending on the flavour of your environment.\n\n```\nselect t.* from \n(\n select u.*,\n (\n select count(*) = jsonb_array_length($1)\n from jsonb_array_elements(u.experience) ej -- jsonb list of experiences \n inner join jsonb_array_elements($1) rj -- jsonb list of request items\n on ej ->> 'field' = rj ->> 'field'\n and (ej ->> 'years')::numeric >= (rj ->> 'years')::numeric\n ) as qualifies\n from users as u\n) as t\nwhere t.qualifies\nlimit $2;\n```\n\n**Some explanation**\n\nThe logic of the `qualifies` subquery is this: first 'normalize' the `experience` and request jsonb arrays into 'tables', then inner join them on the target condition (which is `field_a = field_b and years_a >= years_b` in this case) and count how many of them match. If the count is equal to the number of request items (i.e. `count(*) = jsonb_array_length($1)`) then all of them are satisfied and so `experience` qualifies.\n\nThus no dynamic SQL is necessary. I think that this approach may be reusable too.\n\n========================================\n\nCode:\n```json\n[\n {\n \"field\": \"devops\",\n \"years\": 9\n },\n {\n \"field\": \"backend dev\",\n \"years\": 7\n } \n... // could be N number of objects with different values\n]\n```\n\n```sql\nSELECT * FROM users\nWHERE\njsonb_path_exists(experience, '$[*] ? (@.field == \"devops\" && @.years > 5)') and\njsonb_path_exists(experience, '$[*] ? (@.field == \"backend dev\" && @.years > 5)')\nLIMIT 3;\n```\n\n```text\n[\n { field: \"devops\", years: 5 }, \n { field: \"java\", years: 6 }, \n { field: \"ui/ux\", years: 2 }] // and so on\n```\n\n```text\nexperience\n```\n\n```text\nCREATE INDEX users_experience_gin_idx ON users USING gin (experience jsonb_path_ops);\n```\n\n```sql\nSELECT *\nFROM users\nWHERE experience @? '$[*] ? (@.field == \"devops\" && @.years > 5 )'\nAND experience @? '$[*] ? (@.field == \"backend dev\" && @.years > 5)'\nLIMIT 3;\n```\n\n```sql\nSELECT 'SELECT * FROM users\nWHERE experience @? '\n || string_agg(quote_nullable(format('$[*] ? (@.field == %s && @.years > %s)'\n , f->'field'\n , f->'years')) || '::jsonpath'\n , E'\\nAND experience @? ')\n || E'\\nLIMIT 3'\nFROM jsonb_array_elements('[{\"field\": \"devops\", \"years\": 5 }, \n {\"field\": \"java\", \"years\": 6 }, \n {\"field\": \"ui/ux\", \"years\": 2 }]') f;\n```\n\n```sql\nSELECT * FROM users\nWHERE experience @? '$[*] ? (@.field == \"devops\" && @.years > 5)'::jsonpath\nAND experience @? '$[*] ? (@.field == \"java\" && @.years > 6)'::jsonpath\nAND experience @? '$[*] ? (@.field == \"ui/ux\" && @.years > 2)'::jsonpath\nLIMIT 3;\n```\n\n```sql\nCREATE OR REPLACE FUNCTION f_users_with_experience(_filter_arr jsonb, _limit int = 3)\n RETURNS SETOF users\n LANGUAGE plpgsql PARALLEL SAFE STABLE STRICT AS\n$func$\nDECLARE\n _sql text;\nBEGIN\n -- assert (you may want to be stricter?)\n IF jsonb_path_exists (_filter_arr, '$[*] ? (!exists(@.field) || !exists(@.years))') THEN\n RAISE EXCEPTION 'Parameter $2 (_filter_arr) must be a JSON array with keys \"field\" and \"years\" in every object. Invalid input was: >>%<<', _filter_arr;\n END IF;\n\n -- generate query string\n SELECT INTO _sql\n'SELECT * FROM users\nWHERE experience @? '\n || string_agg(quote_nullable(format('$[*] ? (@.field == %s && @.years > %s)'\n , f->'field'\n , f->'years'))\n , E'\\nAND experience @? ')\n || E'\\nLIMIT ' || _limit\n FROM jsonb_array_elements(_filter_arr) f;\n\n -- execute\n IF _sql IS NULL THEN\n RAISE EXCEPTION 'SQL statement is NULL. Should not occur!';\n ELSE\n -- RAISE NOTICE '%', _sql; -- debug first if in doubt\n RETURN QUERY EXECUTE _sql;\n END IF;\nEND\n$func$;\n```\n\n```text\nSELECT * FROM f_users_with_experience('[{\"field\": \"devops\", \"years\": 5 }, \n , {\"field\": \"backend dev\", \"years\": 6}]');\n```\n\n```text\nSELECT * FROM f_users_with_experience('[{\"field\": \"devops\", \"years\": 5 }]', 123);\n```\n\n```text\njsonb_path_exists (_filter_arr, '$[*] ? (!exists(@.field) || !exists(@.years))')\n```\n\n```text\njsonb_path_ops\n```\n\n```text\n@?\n```\n\n```text\njsonb_path_exists()\n```\n\n```text\nLIMIT\n```\n\n```text\njsonpath\n```\n\n```text\nquote_nullable()\n```\n\n```text\nfield\n```\n\n```text\nyears\n```\n\n```sql\nselect t.* from \n(\n select u.*,\n (\n select count(*) = jsonb_array_length($1)\n from jsonb_array_elements(u.experience) ej -- jsonb list of experiences \n inner join jsonb_array_elements($1) rj -- jsonb list of request items\n on ej ->> 'field' = rj ->> 'field'\n and (ej ->> 'years')::numeric >= (rj ->> 'years')::numeric\n ) as qualifies\n from users as u\n) as t\nwhere t.qualifies\nlimit $2;\n```\n\n```text\nqualifies\n```\n\n```text\nexperience\n```\n\n```text\n$1\n```\n\n```text\n$2\n```\n\n```text\nqualifies\n```\n\n```text\nexperience\n```\n\n```text\nfield_a = field_b and years_a >= years_b\n```\n\n```text\ncount(*) = jsonb_array_length($1)\n```\n\n```text\nexperience\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":30,"totalLines":287,"estimatedTokens":1612}}326{"id":"stack-57840579","source":"stackoverflow","questionId":57840579,"title":"TypeORM: Cannot read property 'getParameters' of undefined","tags":["javascript","mysql","typescript","relational-database","typeorm"],"text":"Title: TypeORM: Cannot read property 'getParameters' of undefined\nTags: javascript, mysql, typescript, relational-database, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm building rest API using express with typeORM for Mysql based on Wordpress database schema you can check from here. \n\nWhen I try to `inner join` or `left join` I get that `Cannot read property 'getParameters' of undefined` error every time. \n\nMy code: \n\n```\nconst posts = await this.postRepository\n .createQueryBuilder('posts')\n .innerJoinAndSelect(WpPostMetaModel, 'postmeta', 'posts.id = postmeta.post')\n .getMany()\n\nresponse.send(posts);\n```\n\nI tried also the following with the same error:\n\n```\nlet posts = await createQueryBuilder('WpPostsModel')\n .leftJoinAndSelect(WpPostMetaModel, 'postmeta', 'postmeta.post_id = WpPostsModel.ID')\n .getManyAndCount()\n```\n\nMy entities:\n\nPost entity:\n\n```\n@Entity({ name: 'wp_posts', synchronize: false })\nexport class WpPostsModel {\n\n @PrimaryGeneratedColumn({ name: 'ID' })\n public id?: number;\n\n @Column({ name: 'post_date' })\n public date?: Date;\n\n @Column({ name: 'post_date_gmt' })\n public date_gmt?: Date;\n\n ...etc\n\n @ManyToMany(() => WpTermTaxonomyModel)\n @JoinTable({\n name: 'wp_term_relationships',\n joinColumn: {\n name: 'object_id',\n referencedColumnName: 'ID'\n },\n inverseJoinColumn: {\n name: 'term_taxonomy_id',\n referencedColumnName: 'termTaxonomyId'\n }\n })\n public categories?: WpTermTaxonomyModel[];\n\n}\n```\n\nPost meta entity:\n\n```\n@Entity({ name: 'wp_postmeta' })\nexport class WpPostMetaModel {\n\n @PrimaryGeneratedColumn({ name: 'meta_id' })\n public metaId?: number;\n\n @OneToOne(() => WpPostsModel, {eager: true, cascade: true})\n @JoinColumn({ name: 'post_id' })\n public post?: WpPostsModel\n\n @Column({ name: 'meta_key' })\n public metaKey?: string;\n\n @Column({ name: 'meta_value' })\n public metaValue?: string;\n\n}\n```\n\n### update: the whole error\n\n```\n(node:1043) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'getParameters' of undefined\n at SelectQueryBuilder.join (/Volumes/Partion-2/Projects/republic-news/src/query-builder/SelectQueryBuilder.ts:1319:52)\n at SelectQueryBuilder.leftJoin (/Volumes/Partion-2/Projects/republic-news/src/query-builder/SelectQueryBuilder.ts:284:14)\n at SelectQueryBuilder.leftJoinAndSelect (/Volumes/Partion-2/Projects/republic-news/src/query-builder/SelectQueryBuilder.ts:364:14)\n at WpPostsController. (/Volumes/Partion-2/Projects/republic-news/src/controllers/post.controller.ts:54:14)\n at step (/Volumes/Partion-2/Projects/republic-news/src/controllers/post.controller.ts:33:23)\n at Object.next (/Volumes/Partion-2/Projects/republic-news/src/controllers/post.controller.ts:14:53)\n at /Volumes/Partion-2/Projects/republic-news/src/controllers/post.controller.ts:8:71\n at new Promise ()\n at __awaiter (/Volumes/Partion-2/Projects/republic-news/src/controllers/post.controller.ts:4:12)\n at WpPostsController.getAllPosts (/Volumes/Partion-2/Projects/republic-news/src/controllers/post.controller.ts:31:86)\n(node:1043) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)\n(node:1043) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n========================================\n\nTop Answer:\nI'm not familiar with the library but looking at it's code it probably throw at line `this.setParameters(subQueryBuilder.getParameters());` in join function. To fix I would enable stop on exception in Chrome Dev tools (source tab little pause icon on far right) and see while it throw, I think it's because `WpPostMetaModel` you're passing don't meet interface it should be a function (in your case you passing class - in JS is the same) that return proper data:\n\nthis is the code in source code:\n\n```\nlet subQuery: string = \"\";\nif (entityOrProperty instanceof Function) {\n const subQueryBuilder: SelectQueryBuilder = (entityOrProperty as any)(((this as any) as SelectQueryBuilder).subQuery());\n this.setParameters(subQueryBuilder.getParameters()); // I think this line throw error\n subQuery = subQueryBuilder.getQuery();\n\n} else {\n subQuery = entityOrProperty;\n}\n```\n\nYou can try to ask on the repo (GitHub issue), I think you just using the library wrong.\n\nSorry this is not exactly the answer, but there is too much text for comment.\n\n========================================\n\nCode:\n```text\nconst posts = await this.postRepository\n .createQueryBuilder('posts')\n .innerJoinAndSelect(WpPostMetaModel, 'postmeta', 'posts.id = postmeta.post')\n .getMany()\n\nresponse.send(posts);\n```\n\n```text\nlet posts = await createQueryBuilder('WpPostsModel')\n .leftJoinAndSelect(WpPostMetaModel, 'postmeta', 'postmeta.post_id = WpPostsModel.ID')\n .getManyAndCount()\n```\n\n```text\n@Entity({ name: 'wp_posts', synchronize: false })\nexport class WpPostsModel {\n\n @PrimaryGeneratedColumn({ name: 'ID' })\n public id?: number;\n\n @Column({ name: 'post_date' })\n public date?: Date;\n\n @Column({ name: 'post_date_gmt' })\n public date_gmt?: Date;\n\n ...etc\n\n @ManyToMany(() => WpTermTaxonomyModel)\n @JoinTable({\n name: 'wp_term_relationships',\n joinColumn: {\n name: 'object_id',\n referencedColumnName: 'ID'\n },\n inverseJoinColumn: {\n name: 'term_taxonomy_id',\n referencedColumnName: 'termTaxonomyId'\n }\n })\n public categories?: WpTermTaxonomyModel[];\n\n}\n```\n\n```text\n@Entity({ name: 'wp_postmeta' })\nexport class WpPostMetaModel {\n\n @PrimaryGeneratedColumn({ name: 'meta_id' })\n public metaId?: number;\n\n @OneToOne(() => WpPostsModel, {eager: true, cascade: true})\n @JoinColumn({ name: 'post_id' })\n public post?: WpPostsModel\n\n @Column({ name: 'meta_key' })\n public metaKey?: string;\n\n @Column({ name: 'meta_value' })\n public metaValue?: string;\n\n}\n```\n\n```sh\n(node:1043) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'getParameters' of undefined\n at SelectQueryBuilder.join (/Volumes/Partion-2/Projects/republic-news/src/query-builder/SelectQueryBuilder.ts:1319:52)\n at SelectQueryBuilder.leftJoin (/Volumes/Partion-2/Projects/republic-news/src/query-builder/SelectQueryBuilder.ts:284:14)\n at SelectQueryBuilder.leftJoinAndSelect (/Volumes/Partion-2/Projects/republic-news/src/query-builder/SelectQueryBuilder.ts:364:14)\n at WpPostsController.<anonymous> (/Volumes/Partion-2/Projects/republic-news/src/controllers/post.controller.ts:54:14)\n at step (/Volumes/Partion-2/Projects/republic-news/src/controllers/post.controller.ts:33:23)\n at Object.next (/Volumes/Partion-2/Projects/republic-news/src/controllers/post.controller.ts:14:53)\n at /Volumes/Partion-2/Projects/republic-news/src/controllers/post.controller.ts:8:71\n at new Promise (<anonymous>)\n at __awaiter (/Volumes/Partion-2/Projects/republic-news/src/controllers/post.controller.ts:4:12)\n at WpPostsController.getAllPosts (/Volumes/Partion-2/Projects/republic-news/src/controllers/post.controller.ts:31:86)\n(node:1043) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)\n(node:1043) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.\n```\n\n```text\ninner join\n```\n\n```text\nleft join\n```\n\n```text\nCannot read property 'getParameters' of undefined\n```\n\n```text\nconst posts = await this.postRepository.createQueryBuilder('post')\n .leftJoinAndMapOne('post.meta', WpPostmetaModel, 'postmeta', 'postmeta.post = post.id') \n // leftJoinAndMapOne instead of letftJoinAndSelect as leftJoinAndSelect didn't return the joined table\n .getMany();\n\nresponse.send(posts);\n```\n\n```text\nlet subQuery: string = \"\";\nif (entityOrProperty instanceof Function) {\n const subQueryBuilder: SelectQueryBuilder<any> = (entityOrProperty as any)(((this as any) as SelectQueryBuilder<any>).subQuery());\n this.setParameters(subQueryBuilder.getParameters()); // I think this line throw error\n subQuery = subQueryBuilder.getQuery();\n\n} else {\n subQuery = entityOrProperty;\n}\n```\n\n```text\nthis.setParameters(subQueryBuilder.getParameters());\n```\n\n```text\nWpPostMetaModel\n```\n\n========================================\n\nComments:\n- Where stack trace with the error is pointing?\n- Thanks for the reply I have updated the question with the whole error log\n- What is `postmeta`? in your model you have `post`.\n- Based on Wordpress it's an extra set of data for posts as ( custom fields ) have key and value I have one to one relation between my post meta and post itself based on Wordpress database schema as you could check from here codex.wordpress.org/images/thumb/2/25/WP4.4.2-ERD.png/…\n- I'm not familar with the API as I said but don't you need to write every single field from database table inside your class?\n- I'm using it like the documentation said you could check it from here: the same syntax as my code above github.com/typeorm/typeorm/blob/master/docs/…\n- As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":264,"estimatedTokens":2416}}327{"id":"stack-66980521","source":"stackoverflow","questionId":66980521,"title":"How to add a where clause dynamically to query which is generated using nestjs Query Builder?","tags":["node.js","nestjs","query-builder","typeorm"],"text":"Title: How to add a where clause dynamically to query which is generated using nestjs Query Builder?\nTags: node.js, nestjs, query-builder, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am working on an API for which the requirement from UI is based on the value of the search field I shall receive the filtered results. There are many search fields on UI.\n\nExample code -\n\n```\nasync getRoomsByMember(active: boolean, email: string): Promise {\n return await getRepository(Room)\n .createQueryBuilder('room')\n .innerJoinAndSelect('room.member', 'member')\n .where(\"room.active = :active\", {active: active})\n .andWhere(\"member.email = :email\", { email: email })\n .getMany();\n }\n```\n\nI shall be able to filter room members dynamically if values entered by a user on filter fields like - member phone number, city, state, country, and zip.\n\n========================================\n\nCode:\n```text\nasync getRoomsByMember(active: boolean, email: string): Promise<any[]> {\n return await getRepository(Room)\n .createQueryBuilder('room')\n .innerJoinAndSelect('room.member', 'member')\n .where(\"room.active = :active\", {active: active})\n .andWhere(\"member.email = :email\", { email: email })\n .getMany();\n }\n```\n\n```js\nasync getRoomsByMember(active: boolean, email: string): Promise<any[]> {\n const query = getRepository(Room)\n .createQueryBuilder('room')\n .innerJoinAndSelect('room.member', 'member')\n .where(\"room.active = :active\", {active: active});\n // Keep adding your other fields like member phone number, city, state, country, and zip, like below\n if(email) {\n query.andWhere(\"member.email = :email\", { email: email })\n }\n return query.getMany();\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":49,"estimatedTokens":423}}328{"id":"stack-71928918","source":"stackoverflow","questionId":71928918,"title":"TypeORM select data from nested relations","tags":["sql","typescript","orm","typeorm"],"text":"Title: TypeORM select data from nested relations\nTags: sql, typescript, orm, typeorm\nSource: Stack Overflow\n\nQuestion:\nUsing\n\n```\nawait this.budgetRepository.createQueryBuilder(\"budget\")\n .leftJoinAndSelect(\"budget.contact\", \"contact\")\n .leftJoinAndSelect(\"contact.photo\", \"contactPhoto\")\n .getMany();\n```\n\nI get a list with objects like this:\n\n```\nBudget {\n id: 1,\n unnecessary_property1: something,\n contact: Contact {\n unnecessary_property2: something,\n photo: Photo {\n unnecessary_property3: something,\n url: \"url.com\"\n },\n },\n}\n```\n\nBut I want to select only the necessary properties in the nested objects (relations) and get a list of objects like this:\n\n```\nBudget {\n id: 1,\n contact: Contact {\n photo: Photo {\n url: \"url.com\"\n },\n },\n}\n```\n\nHow is that possible with TypeORM?\n\n========================================\n\nTop Answer:\nIf you're using repository pattern that you will be achieve the similar result with:\n\n```\nawait this.budgetRepository.find({\n relations: [\"contact\", \"contact.photo\"]\n select: {\n contactfield1: true,\n contactfield2: true,\n photo: {\n phototfield1: true,\n phototfield2: true,\n }\n }\n})\n```\n\n========================================\n\nCode:\n```text\nawait this.budgetRepository.createQueryBuilder(\"budget\")\n .leftJoinAndSelect(\"budget.contact\", \"contact\")\n .leftJoinAndSelect(\"contact.photo\", \"contactPhoto\")\n .getMany();\n```\n\n```text\nBudget {\n id: 1,\n unnecessary_property1: something,\n contact: Contact {\n unnecessary_property2: something,\n photo: Photo {\n unnecessary_property3: something,\n url: \"url.com\"\n },\n },\n}\n```\n\n```text\nBudget {\n id: 1,\n contact: Contact {\n photo: Photo {\n url: \"url.com\"\n },\n },\n}\n```\n\n```text\nawait this.budgetRepository.createQueryBuilder(\"budget\")\n .leftJoinAndSelect(\"budget.contact\", \"contact\")\n .leftJoinAndSelect(\"contact.photo\", \"contactPhoto\")\n .select(['budget.id', 'contactPhoto.url']\n .getMany();\n```\n\n```text\n.select()\n```\n\n```js\nconst user = await createQueryBuilder(\"budget\")\n .leftJoinAndSelect(\"budget.contact\", \"contact\")\n .leftJoinAndSelect(\"contact.photo\", \"contactPhoto\")\n .select([/* everything from budget */, 'contact.photo.url'....]) // added selection\n .getMany();\n```\n\n```text\n.select()\n```\n\n```text\nawait this.budgetRepository.find({\n relations: [\"contact\", \"contact.photo\"]\n select: {\n contactfield1: true,\n contactfield2: true,\n photo: {\n phototfield1: true,\n phototfield2: true,\n }\n }\n})\n```\n\n========================================\n\nComments:\n- Unfortunatly, this does not work\n- i've updated the selection function to add the missing 'contact' before 'photo.url'\n- in above example, `contactfield1` must be declared in the `select`. Otherwise, field `contact` won't be returned at all.","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":143,"estimatedTokens":697}}329{"id":"stack-67453800","source":"stackoverflow","questionId":67453800,"title":"TypeORM migration:run not working errno: -3008,getaddrinfo ENOTFOUND","tags":["node.js","docker","docker-compose","typeorm"],"text":"Title: TypeORM migration:run not working errno: -3008,getaddrinfo ENOTFOUND\nTags: node.js, docker, docker-compose, typeorm\nSource: Stack Overflow\n\nQuestion:\nDo you know why I get the following error when I try to run typeorm:run to execute migration?\n\n```\nnode --require ts-node/register ./node_modules/typeorm/cli.js migration:run\nError during migration run:\nError: getaddrinfo ENOTFOUND users-service-db\nat GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:69:26) {\nerrno: -3008,\ncode: 'ENOTFOUND',\nsyscall: 'getaddrinfo',\nhostname: 'users-service-db',\nfatal: true\n }\nerror Command failed with exit code 1.\n```\n\nmy config is\n\n```\nusers-service-db:\n environment:\n - MYSQL_ROOT_PASSWORD=password\n - MYSQL_DATABASE=db\n image: mysql:5.7.20\n ports:\n - \"7201:3306\"\n```\n\nthe users-service-db is running does this `Error: getaddrinfo ENOTFOUND users-service-db` say that the host doesn't know what to do. Can you help?\n\nAfter trying Answer 1 and 2 still getting the same error don't know what to do it worked before?\n\n\r\n\r\n\n```\nversion: \"3\"\nservices:\n api-gateway:\n build:\n context: \".\"\n dockerfile: \"./api-gateway/Dockerfile\"\n depends_on:\n - chat-service\n - users-service\n ports:\n - \"7000:7000\"\n volumes:\n - ./api-gateway:/opt/app\n\n chat-service:\n build:\n context: \".\"\n dockerfile: \"./chat-service/Dockerfile\"\n depends_on:\n - chat-service-db\n ports:\n - \"7100:7100\"\n volumes:\n - ./chat-service:/opt/app\n\n chat-service-db:\n environment:\n - MYSQL_ROOT_PASSWORD=password\n - MYSQL_DATABASE=db\n image: mysql:5.7.20\n ports:\n - \"7200:3306\"\n\n phpmyadmin:\n image: phpmyadmin/phpmyadmin\n ports:\n - \"7300:80\"\n volumes:\n - ./phpmyadmin/config.user.inc.php:/etc/phpmyadmin/config.user.inc.php\n\n users-service:\n build:\n context: \".\"\n dockerfile: \"./users-service/Dockerfile\"\n depends_on:\n - users-service-db\n ports:\n - \"7101:7101\"\n volumes:\n - ./users-service:/opt/app\n\n users-service-db:\n environment:\n - MYSQL_ROOT_PASSWORD=password\n - MYSQL_DATABASE=db\n image: mysql:5.7.20\n ports:\n - \"7201:3306\"\n hostname: 'localhost'\n```\n\n\r\n\r\n\r\n\nfinally I resolved the error thanks to @Eranga Heshan\n\nI created an additional ormConfig.js file at pasted this:\n\n\r\n\r\n\n```\nexport = {\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 7201,\n \"username\": \"root\",\n \"password\": \"password\",\n \"database\": \"db\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"src/entities/**/*.ts\"\n ],\n \"migrations\": [\n \"./src/db/migrations/**/*.ts\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/db/entities\",\n \"migrationsDir\": \"src/db/migrations\"\n }\n }\n```\n\n\r\n\r\n\r\n\nthen\n\n```\nnode --require ts-node/register ./node_modules/typeorm/cli.js migration:run --config src/db/migrations/ormConfig\n```\n\n========================================\n\nCode:\n```text\nnode --require ts-node/register ./node_modules/typeorm/cli.js migration:run\nError during migration run:\nError: getaddrinfo ENOTFOUND users-service-db\nat GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:69:26) {\nerrno: -3008,\ncode: 'ENOTFOUND',\nsyscall: 'getaddrinfo',\nhostname: 'users-service-db',\nfatal: true\n }\nerror Command failed with exit code 1.\n```\n\n```text\nusers-service-db:\n environment:\n - MYSQL_ROOT_PASSWORD=password\n - MYSQL_DATABASE=db\n image: mysql:5.7.20\n ports:\n - \"7201:3306\"\n```\n\n```js\nversion: \"3\"\nservices:\n api-gateway:\n build:\n context: \".\"\n dockerfile: \"./api-gateway/Dockerfile\"\n depends_on:\n - chat-service\n - users-service\n ports:\n - \"7000:7000\"\n volumes:\n - ./api-gateway:/opt/app\n\n chat-service:\n build:\n context: \".\"\n dockerfile: \"./chat-service/Dockerfile\"\n depends_on:\n - chat-service-db\n ports:\n - \"7100:7100\"\n volumes:\n - ./chat-service:/opt/app\n\n chat-service-db:\n environment:\n - MYSQL_ROOT_PASSWORD=password\n - MYSQL_DATABASE=db\n image: mysql:5.7.20\n ports:\n - \"7200:3306\"\n\n phpmyadmin:\n image: phpmyadmin/phpmyadmin\n ports:\n - \"7300:80\"\n volumes:\n - ./phpmyadmin/config.user.inc.php:/etc/phpmyadmin/config.user.inc.php\n\n users-service:\n build:\n context: \".\"\n dockerfile: \"./users-service/Dockerfile\"\n depends_on:\n - users-service-db\n ports:\n - \"7101:7101\"\n volumes:\n - ./users-service:/opt/app\n\n users-service-db:\n environment:\n - MYSQL_ROOT_PASSWORD=password\n - MYSQL_DATABASE=db\n image: mysql:5.7.20\n ports:\n - \"7201:3306\"\n hostname: 'localhost'\n```\n\n```js\nexport = {\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 7201,\n \"username\": \"root\",\n \"password\": \"password\",\n \"database\": \"db\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\n \"src/entities/**/*.ts\"\n ],\n \"migrations\": [\n \"./src/db/migrations/**/*.ts\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/db/entities\",\n \"migrationsDir\": \"src/db/migrations\"\n }\n }\n```\n\n```text\nnode --require ts-node/register ./node_modules/typeorm/cli.js migration:run --config src/db/migrations/ormConfig\n```\n\n```text\nError: getaddrinfo ENOTFOUND users-service-db\n```\n\n```text\nexport = {\n host: 'localhost',\n port: '7201',\n type: 'mysql',\n user : 'root',\n password : 'password',\n database : 'db' ,\n};\n```\n\n```sh\nnode --require ts-node/register ./node_modules/typeorm/cli.js migration:run --config src/migrations/migrationsOrmConfig\n```\n\n```sh\ndocker ps -a\n```\n\n```sh\ndocker exec -it CONTAINER_ID /bin/bash\n```\n\n```sh\nnode --require ts-node/register ./node_modules/typeorm/cli.js migration:run\n```\n\n```text\nusers-service-db\n```\n\n```text\nlocalhost\n```\n\n```text\nmigrationsOrmConfig.ts\n```\n\n```text\nsrc/migrations\n```\n\n```text\nCONTAINER ID\n```\n\n```text\nuser-service\n```\n\n```text\nCONTAINER_ID\n```\n\n```text\ntypeorm\n```\n\n========================================\n\nComments:\n- How are you trying to run the migration? Are you trying to run it inside the container or in your terminal?\n- Inside the vs code terminal?\n- Thanks for the answer. First step i tried but still the same =>PS C:\\Users\\edibi\\eclipse-workspace\\nodejsSocketTypescriptGraph‌​QL\\users-service> node --require ts-node/register .\\node_modules\\typeorm\\cli.js --config .\\src\\db\\migrations\\typeOrmConfig.ts migration:run Error during migration run: Error: getaddrinfo ENOTFOUND users-service-db at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:69:26) { errno: -3008, code: 'ENOTFOUND', syscall: 'getaddrinfo', hostname: 'users-service-db', fatal: true } When execute step 2 it says =>/bin/sh: 1: node: not found\n- Okay, I updated the migration command in my 1st answer. For the second one, I made a mistake by asking you to go into the MySQL container. Can you try 1st answer again? For the 2nd, are you using docker-compose to run your backend? If so, can you the full docker-compose file?\n- okey you moved typeorm migrations:run command to the front. That's ok but the error won't go away. Thanks i edited the docker-compose.yml file\n- No worries, based on your docker-compose file, I updated my second answer, could you try it now?\n- yes i think we are on the right path it seems that typeorm is not in the node-modules folder for whatsoever reason. it cannot find the typeorm package in node-modules: Error: Cannot find module '/opt/app/node_modules/typeorm/cli.js' So why it is not installing the package in the image\n- Do you have `typeorm` in `package.json`?\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":19,"totalLines":337,"estimatedTokens":1823}}330{"id":"stack-68059776","source":"stackoverflow","questionId":68059776,"title":"typeORM migration:generate not recognise import baseurl","tags":["database-migration","typeorm"],"text":"Title: typeORM migration:generate not recognise import baseurl\nTags: database-migration, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am using typeORM with nestjs and typescript. I have nestjs so all import statements can start with 'src/...' typeorm will only accept imports to other entities using ../\n\nNot finding the referenced entity\n\n```\nimport { User } from 'src/users/entities/user.entity';\n```\n\nStructure to finding the referenced entity:\n\n```\nimport { User } from '../users/entities/user.entity';\n```\n\nI am using the script from package.json\n\n```\n\"migration:generate\": \"ts-node node_modules/.bin/typeorm migration:generate -n\"\n```\n\normconfig.json\n\n```\n[\n {\n \"name\": \"default\",\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"xxxx\",\n \"password\": \"xxx\",\n \"database\": \"xxxx\",\n \"schema\": \"xxx\",\n \"migrations\": [\"dist/migrations/*{.ts,.js}\"],\n \"migrationsTableName\": \"migrations_typeorm\"\n }\n]\n```\n\ntsconfig.json\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true\n }\n }\n```\n\nnest-cli.json\n\n```\n{\n \"collection\": \"@nestjs/schematics\",\n \"sourceRoot\": \"src\"\n}\n```\n\nI have tried the suggestion typeorm migration api does not generate automatic code but it does not solve my issue.\nHow do I get orm migration to accept a path starting with src/ in the import statement when including other entities?\n\nMany thanks\n\n========================================\n\nCode:\n```text\nimport { User } from 'src/users/entities/user.entity';\n```\n\n```text\nimport { User } from '../users/entities/user.entity';\n```\n\n```text\n\"migration:generate\": \"ts-node node_modules/.bin/typeorm migration:generate -n\"\n```\n\n```text\n[\n {\n \"name\": \"default\",\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5432,\n \"username\": \"xxxx\",\n \"password\": \"xxx\",\n \"database\": \"xxxx\",\n \"schema\": \"xxx\",\n \"migrations\": [\"dist/migrations/*{.ts,.js}\"],\n \"migrationsTableName\": \"migrations_typeorm\"\n }\n]\n```\n\n```text\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true\n }\n }\n```\n\n```text\n{\n \"collection\": \"@nestjs/schematics\",\n \"sourceRoot\": \"src\"\n}\n```\n\n```text\n\"test:debug\": \"node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand\"\n```\n\n```text\n\"typeorm\": \"node -r tsconfig-paths/register -r ts-node/register ./node_modules/typeorm/cli.js\"\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":142,"estimatedTokens":700}}331{"id":"stack-51994374","source":"stackoverflow","questionId":51994374,"title":"Nest.js project with TypeORM Active Record implementation","tags":["nestjs","typeorm"],"text":"Title: Nest.js project with TypeORM Active Record implementation\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to build a project with Nest.js and TypeORM. I like the Active Record approach in TypeORM\n\nI define an entity as follows, with some static helper methods:\n\n```\nexport class Book extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @Column()\n description: string;\n\n static async createNew(attributes: BookDto): Promise {\n const entity = new Book();\n entity.name = attributes.name;\n entity.description = attributes.description;\n\n return entity.save();\n }\n\n static async findByName(name: string): Promise {\n return Book.findOne({\n where: { name },\n });\n }\n}\n```\n\nI'm trying to the patterns in the Nest docs to inject it into my service:\n\n```\n@Injectable()\nexport class BookService {\n constructor(\n @InjectRepository(Book)\n private readonly bookRepository: Repository,\n ) {}\n\n async create(bookAttrs: BookDto): Promise {\n return Book.createNew(bookAttrs);\n }\n}\n```\n\nBut as you can see in my service, I am only using the static methods. In this case, do I even need to inject the dependencies? Is there a better pattern I should be following?\n\n========================================\n\nCode:\n```js\nexport class Book extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @Column()\n description: string;\n\n static async createNew(attributes: BookDto): Promise<Book> {\n const entity = new Book();\n entity.name = attributes.name;\n entity.description = attributes.description;\n\n return entity.save();\n }\n\n static async findByName(name: string): Promise<Book> {\n return Book.findOne({\n where: { name },\n });\n }\n}\n```\n\n```js\n@Injectable()\nexport class BookService {\n constructor(\n @InjectRepository(Book)\n private readonly bookRepository: Repository<Book>,\n ) {}\n\n async create(bookAttrs: BookDto): Promise<Book> {\n return Book.createNew(bookAttrs);\n }\n}\n```\n\n```text\nRepository\n```\n\n```text\nTypeOrmModule.forFeature([User])\n```\n\n========================================\n\nComments:\n- Thanks for this, I was assuming this wasn't the very \"Nest\" way to do it. However I do like the Active Record approach and this seemed to be the only way to do it like this. I'd love to see some code examples of implementing like this. The docs only seem to show static methods on the Active Record entity type: typeorm.io/#/active-record-data-mapper.\n- The more \"nest\" way to do it would be to the data mapper pattern, so you can define your scopes on your repository, not the model itself, and then mock the repository's functionality in your tests.","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":111,"estimatedTokens":669}}332{"id":"stack-64854333","source":"stackoverflow","questionId":64854333,"title":"NestJS/TypeORM: Cannot read property 'createQueryBuilder' of undefined","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: NestJS/TypeORM: Cannot read property 'createQueryBuilder' of undefined\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nCalling 'localhost:3000/contacts' (with or without parameters) at postman returns me this error and i don't know why. My backend is connected to a PostgreSQL db.\n\n```\nTypeError: Cannot read property 'createQueryBuilder' of undefined\n at ContactsRepository.Repository.createQueryBuilder (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\typeorm\\repository\\Repository.js:17:29)\n at ContactsRepository.getContacts (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\dist\\contacts\\contacts.repository.js:17:34)\n at ContactsService.getContacts (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\dist\\contacts\\contacts.service.js:24:39)\n at ContactsController.getContacts (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\dist\\contacts\\contacts.controller.js:25:37)\n at ...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:38:29\n at processTicksAndRejections (internal/process/task_queues.js:93:5)\n at async ...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:46:28\n at async ...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17\n```\n\nMy code looks like this:\n\n```\n@EntityRepository(Contact)\nexport class ContactsRepository extends Repository {\n\n async getContacts(filterDto: GetContactsFilterDto): Promise {\n const { name, search } = filterDto;\n // const query = this.createQueryBuilder('contacts');\n const query = await this.createQueryBuilder()\n .select('contacts')\n .from(Contact, 'contacts');\n\n if (name) {\n query.andWhere('contacts.name = :name', { name });\n }\n\n if (search) {\n query.andWhere(\n '(contacts.email LIKE :search OR contacts.telephone LIKE :search)',\n { search: `%${search}%` },\n );\n }\n\n const contacts = await query.getMany();\n return contacts;\n }\n```\n\n```\nimport { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity({ name: 'contacts' })\nexport class Contact extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column()\n email: string;\n\n @Column()\n html_de: string;\n\n @Column()\n html_en: string;\n\n @Column()\n name: string;\n\n @Column()\n telephone: string;\n}\n```\n\n```\nexport class ContactsController {\n constructor(private contactsService: ContactsService) {}\n\n @Get()\n getContacts(\n @Query(ValidationPipe) filterDto: GetContactsFilterDto,\n ): Promise {\n return this.contactsService.getContacts(filterDto);\n }\n```\n\n```\n@Injectable()\nexport class ContactsService {\n constructor(\n @InjectRepository(ContactsRepository)\n private contactsRepository: ContactsRepository,\n ) {}\n\n async getContacts(filterDto: GetContactsFilterDto): Promise {\n return this.contactsRepository.getContacts(filterDto);\n }\n```\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\nimport { ContactsController } from './contacts.controller';\nimport { ContactsRepository } from './contacts.repository';\nimport { ContactsService } from './contacts.service';\n\n@Module({\n controllers: [ContactsController],\n imports: [TypeOrmModule.forFeature([ContactsRepository])],\n providers: [ContactsRepository, ContactsService],\n exports: [ContactsRepository, ContactsService],\n})\nexport class ContactsModule {}\n```\n\nSomebody know how i can fix this? Regards\n\n========================================\n\nCode:\n```text\nTypeError: Cannot read property 'createQueryBuilder' of undefined\n at ContactsRepository.Repository.createQueryBuilder (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\typeorm\\repository\\Repository.js:17:29)\n at ContactsRepository.getContacts (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\dist\\contacts\\contacts.repository.js:17:34)\n at ContactsService.getContacts (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\dist\\contacts\\contacts.service.js:24:39)\n at ContactsController.getContacts (...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\dist\\contacts\\contacts.controller.js:25:37)\n at ...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:38:29\n at processTicksAndRejections (internal/process/task_queues.js:93:5)\n at async ...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:46:28\n at async ...\\Documents\\Visual Studio Code Projects\\funds-backend-nestjs\\node_modules\\@nestjs\\core\\router\\router-proxy.js:9:17\n```\n\n```text\n@EntityRepository(Contact)\nexport class ContactsRepository extends Repository<Contact> {\n\n async getContacts(filterDto: GetContactsFilterDto): Promise<Contact[]> {\n const { name, search } = filterDto;\n // const query = this.createQueryBuilder('contacts');\n const query = await this.createQueryBuilder()\n .select('contacts')\n .from(Contact, 'contacts');\n\n if (name) {\n query.andWhere('contacts.name = :name', { name });\n }\n\n if (search) {\n query.andWhere(\n '(contacts.email LIKE :search OR contacts.telephone LIKE :search)',\n { search: `%${search}%` },\n );\n }\n\n const contacts = await query.getMany();\n return contacts;\n }\n```\n\n```text\nimport { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity({ name: 'contacts' })\nexport class Contact extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column()\n email: string;\n\n @Column()\n html_de: string;\n\n @Column()\n html_en: string;\n\n @Column()\n name: string;\n\n @Column()\n telephone: string;\n}\n```\n\n```text\nexport class ContactsController {\n constructor(private contactsService: ContactsService) {}\n\n @Get()\n getContacts(\n @Query(ValidationPipe) filterDto: GetContactsFilterDto,\n ): Promise<ContactDto[]> {\n return this.contactsService.getContacts(filterDto);\n }\n```\n\n```text\n@Injectable()\nexport class ContactsService {\n constructor(\n @InjectRepository(ContactsRepository)\n private contactsRepository: ContactsRepository,\n ) {}\n\n async getContacts(filterDto: GetContactsFilterDto): Promise<Contact[]> {\n return this.contactsRepository.getContacts(filterDto);\n }\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\nimport { ContactsController } from './contacts.controller';\nimport { ContactsRepository } from './contacts.repository';\nimport { ContactsService } from './contacts.service';\n\n@Module({\n controllers: [ContactsController],\n imports: [TypeOrmModule.forFeature([ContactsRepository])],\n providers: [ContactsRepository, ContactsService],\n exports: [ContactsRepository, ContactsService],\n})\nexport class ContactsModule {}\n```\n\n```text\nContactsRepository\n```\n\n```text\nTypeOrmModule.forFeature()\n```\n\n```text\nproviders\n```\n\n```text\nexports\n```\n\n```text\nContactsRepository\n```\n\n```text\nRepository\n```\n\n========================================\n\nComments:\n- In a older version i didnt use the alias 'contacts'. Back then I named my entity 'contacts' to fit the table name 'contacts'. Wanted to make it more consistent, because an entity should be singular. It worked. Does it have something to do with it? Because right now i tried it with getManager, and it works again. const query = await getManager().createQueryBuilder(Contact, 'contacts'); github.com/typeorm/typeorm/blob/master/docs/…\n- Can you also show your `ContactsModule`?\n- I brought it back to working using TypeORM's Connection in the service: `this.contactsRepository = this.connection.getCustomRepository(ContactsRepository);` Still i'm wondering why i am not able to use Dependency Injection anymore. It must be because of the Alias used in the Entity: `@Entity({ name: 'contacts' })`\n- StackOverflow comments don't do multiline formatting. Can you add it to your question body instead of the comment?\n- I edited my post and added the module.\n- I think you need to remove `ContactsRepository` from the `providers` and `exports` arrays. That way, when Nest finds the `ContactsRepository` injection token via `@InjectRepository()` it will know this is a TypeORM related class and get it from the TypeORM system\n- I removed the exports and its working again. thanks!","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":260,"estimatedTokens":2116}}333{"id":"stack-57055996","source":"stackoverflow","questionId":57055996,"title":"How to catch a Typeorm transaction error in NestJs","tags":["javascript","graphql","nestjs","typeorm"],"text":"Title: How to catch a Typeorm transaction error in NestJs\nTags: javascript, graphql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a server side written in node.js and nestJs, querying with typeorm.\n\nI'm trying to wrap some query's to the database with transaction as suggested here with some changes inspired by typeorm's docs, like this:\n\n```\ngetManager().transaction(async transactionalEntityManager => {\n transactionalEntityManager.save(newEntity)\n transactionalEntityManager.save(newEntity1)\n});\n```\n\nThe transaction works well and rollback the database if there was an error.\ntested this way: \n\n```\ngetManager().transaction(async transactionalEntityManager => {\n transactionalEntityManager.save(newEntity)\n throw 'There is an error'\n transactionalEntityManager.save(newEntity1)\n});\n```\n\nThe execution of the transaction is inside a graphQL Mutation, so I should return an error to the client if something went wrong, the problem is that I can't catch the errors from the transaction.\n\nTried doing this: \n\n```\n@Mutation(returns => Entity)\n async create(): Promise {\n let entity = null;\n let error = null;\n getManager().transaction(async transactionalEntityManager => {\n try {\n entity = await transactionalEntityManager.save(newEntity)\n await transactionalEntityManager.save(newEntity1);\n } catch (err) {\n error = err\n }\n })\n if (error) {\n return error\n }\n return entity\n }\n```\n\nwhen I throw error I catch it successfully, but when a real error occurs I can `console.log()` it in the server but it never reaches to return to the client.\n\n========================================\n\nCode:\n```text\ngetManager().transaction(async transactionalEntityManager => {\n transactionalEntityManager.save<Entity>(newEntity)\n transactionalEntityManager.save<Entity1>(newEntity1)\n});\n```\n\n```text\ngetManager().transaction(async transactionalEntityManager => {\n transactionalEntityManager.save<Entity>(newEntity)\n throw 'There is an error'\n transactionalEntityManager.save<Entity1>(newEntity1)\n});\n```\n\n```text\n@Mutation(returns => Entity)\n async create(): Promise<Entity> {\n let entity = null;\n let error = null;\n getManager().transaction(async transactionalEntityManager => {\n try {\n entity = await transactionalEntityManager.save<Entity>(newEntity)\n await transactionalEntityManager.save<Entity1>(newEntity1);\n } catch (err) {\n error = err\n }\n })\n if (error) {\n return error\n }\n return entity\n }\n```\n\n```text\nconsole.log()\n```\n\n```text\nawait getManager().transaction(async transactionalEntityManager => {\n ...\n throw 'ERROR THAT SHOULD BE CATCHED'\n}\n```\n\n```text\nconst ok = await getManager().transaction(async transactionalEntityManager => {\n await transactionalEntityManager.save<Entity>(newEntity)\n await transactionalEntityManager.save<Entity>(newEntity2)\n return 'OK'\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":109,"estimatedTokens":716}}334{"id":"stack-70287250","source":"stackoverflow","questionId":70287250,"title":"How to make OneToOne relationship optional for multiple inherited classes?","tags":["typescript","nestjs","entity","typeorm","ts-node"],"text":"Title: How to make OneToOne relationship optional for multiple inherited classes?\nTags: typescript, nestjs, entity, typeorm, ts-node\nSource: Stack Overflow\n\nQuestion:\nSuppose I have a class `Animal` which are inherited by `Dog` and `Cat`.\n\n```\nexport class Animal extends BaseEntity{\n @PrimaryGeneratedColumn()\n id:number;\n}\n\n@Entity()\nexport class Cat extends Animal{\n ...\n}\n\n@Entity()\nexport class Dog extends Animal{\n ...\n}\n```\n\nNow, I want to show a `OneToOne` relationship with their owner.\n\n```\n@Entity\nexport class Owner extends BaseEntity{\n ....\n \n @OneToOne()\n pet:???\n}\n```\n\n`Owner` is a class which has an attribute `pet` that can either be a Cat or a Dog.\nHow can I achieve this using typeorm?\n\nOr am I doing it wrong?\n\n========================================\n\nTop Answer:\nYou can use @ChildEntity() for children and @Entity() for main class in typeorm.\n\n========================================\n\nCode:\n```text\nexport class Animal extends BaseEntity{\n @PrimaryGeneratedColumn()\n id:number;\n}\n\n@Entity()\nexport class Cat extends Animal{\n ...\n}\n\n@Entity()\nexport class Dog extends Animal{\n ...\n}\n```\n\n```text\n@Entity\nexport class Owner extends BaseEntity{\n ....\n \n @OneToOne()\n pet:???\n}\n```\n\n```text\nAnimal\n```\n\n```text\nDog\n```\n\n```text\nCat\n```\n\n```text\nOneToOne\n```\n\n```text\nOwner\n```\n\n```text\npet\n```\n\n```text\n@Entity()\n@TableInheritance({ column: { type: \"varchar\", name: \"type\" } })\nexport class Content {\n \n @PrimaryGeneratedColumn()\n id: number;\n \n @Column()\n title: string;\n \n @Column()\n description: string;\n \n}\n```\n\n```text\n@ChildEntity()\nexport class Photo extends Content {\n \n @Column()\n size: string;\n \n}\n```\n\n```text\n@ChildEntity()\nexport class Question extends Content {\n \n @Column()\n answersCount: number;\n \n}\n```\n\n```text\n@ChildEntity()\nexport class Post extends Content {\n \n @Column()\n viewCount: number;\n \n}\n```\n\n========================================\n\nComments:\n- I didn't get what should be done in Owner.pet, should pass the Animal entity? will Animal or the Child be stored on database with its relationship with Owner?","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":151,"estimatedTokens":534}}335{"id":"stack-71723151","source":"stackoverflow","questionId":71723151,"title":"QueryFailedError: malformed array literal: \"[]\" in typeORM","tags":["postgresql","nestjs","typeorm"],"text":"Title: QueryFailedError: malformed array literal: \"[]\" in typeORM\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to add a new row to a table in postgres using TypeORM, but receive the issue related to array literals. The problem occurs with a `subscriptions` field\n\nEntity format:\n\n```\nexport class User {\n @PrimaryColumn()\n userId: string;\n\n @Column(\"varchar\")\n email: string;\n\n @Column(\"text\", { array: true })\n userCookieIds: string[];\n\n @Column(\"varchar\", { array: true })\n userLocalIds: string[]\n\n @Column(\"jsonb\", { array: true })\n subscriptions: object[] \n}\n```\n\nThe code of typeORM insert:\n\n```\nuser = new User()\n user.userId = uuidv4()\n user.email = ''\n user.userCookieIds = [userCookieId]\n user.subscriptions = []\n user.userLocalIds = [] \n await this.usersRepository.save(user)\n```\n\nI checked all similar questions on StackOverflow, but it didn't help :-(\n\nAny help is highly appreciated\n\n========================================\n\nCode:\n```text\nexport class User {\n @PrimaryColumn()\n userId: string;\n\n @Column(\"varchar\")\n email: string;\n\n @Column(\"text\", { array: true })\n userCookieIds: string[];\n\n @Column(\"varchar\", { array: true })\n userLocalIds: string[]\n\n @Column(\"jsonb\", { array: true })\n subscriptions: object[] \n}\n```\n\n```text\nuser = new User()\n user.userId = uuidv4()\n user.email = ''\n user.userCookieIds = [userCookieId]\n user.subscriptions = []\n user.userLocalIds = [] \n await this.usersRepository.save(user)\n```\n\n```text\nsubscriptions\n```\n\n```text\narray: true\n```\n\n```text\n@Column\n```\n\n========================================\n\nComments:\n- guessing you fixed this already but can you the error text with us? I think you can drop [] from the data types when you specify {array:true}","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":92,"estimatedTokens":450}}336{"id":"stack-71047130","source":"stackoverflow","questionId":71047130,"title":"What happens if I delete a record from the typeorm migration table?","tags":["postgresql","database-migration","typeorm"],"text":"Title: What happens if I delete a record from the typeorm migration table?\nTags: postgresql, database-migration, typeorm\nSource: Stack Overflow\n\nQuestion:\nHow is the migrations table created by TypeORM used?\n\nFor one, I suppose it's used to track all the migrations that have already been executed in a database.\n\nIf I were to delete a migration file, manually execute the \"down\" query that undoes the migration, as well as remove its associated record from the migrations (or whatever `migrationTableName` is set to) table, will it be like the migration was never there in the first place?\n\n========================================\n\nCode:\n```text\nmigrationTableName\n```\n\n```text\nmigrations\n```\n\n```text\ntypeorm migration:run\n```\n\n```text\ntypeorm migration:run\n```\n\n```text\nmigrations\n```\n\n```text\ntypeorm migration:run\n```\n\n```text\nmigrations\n```\n\n```text\ntypeorm migration:revert\n```\n\n========================================\n\nComments:\n- Has anybody tried this out? does it corrupt the typeorm?\n- Typeorm uses that table to track which migrations to not run again. So if you have non-idempotent migrations whose records you're deleting, it will cause issues.","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":51,"estimatedTokens":291}}337{"id":"stack-75828352","source":"stackoverflow","questionId":75828352,"title":"How to mock Typeorm DataSource with Jest","tags":["typescript","unit-testing","jestjs","typeorm"],"text":"Title: How to mock Typeorm DataSource with Jest\nTags: typescript, unit-testing, jestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIm new to using typeorm and Jest for that matter. I have a function that is creating and returning a DataSource here:\n\napp/lib/connections/createDBConnection.ts\n\n```\nconst createDBConnection = async () => {\n const dbUrl = Environment.get('DATABASE_URL')\n const db = new DataSource({\n type: 'postgres',\n url: dbUrl,\n synchronize: false,\n entities: [],\n connectTimeoutMS: 10000,\n })\n await db.initialize()\n return db\n}\n\nexport default createDBConnection\n```\n\nHere is the get function if it helps:\n\n```\nexport class Environment {\n public static get(key: string): string {\n const result = process.env[key]\n\n if (result === undefined) {\n throw new Error(`Failed to find key ${key} in environment`)\n }\n\n return result\n }\n```\n\nHere is my test file:\n\n```\nconst FakeDB = new DataSource({\n type: 'postgres',\n url: 'fakeURL',\n synchronize: false,\n entities: [],\n connectTimeoutMS: 10000,\n})\n\njest.mock('app/lib/connections/createDBConnection', () => {\n return jest.fn().mockImplementation(() => Promise.resolve(FakeDB))\n}\n)\n\nafterEach(() => {\n jest.clearAllMocks()\n})\n\ntest('creates a fake connection', async () => {\n const DbConnection = await createDBConnection()\n expect(DbConnection).toBeTruthy()\n expect(DbConnection).toBeInstanceOf(DataSource)\n expect(DbConnection).toEqual(FakeDB)\n \n // Im trying to make something like these pass\n expect(FakeDB.initialize).toHaveBeenCalled\n expect(FakeDB.isInitialized).toBe(true)\n})\n```\n\nIm not sure how to mock out the initialize function correctly. I want to verify its called in my function somehow. The first three assertions seem to pass, but im not sure if its actually correct, since those bottom 2 both fail. Any help or advice will be appreciated.\n\nIve tried mocking the initialize a couple of ways like:\n\n```\njest.mock('typeorm'), () => {\n return jest.fn().mockImplementation(() => {\n return {\n initialize: () => {true}\n }\n })\n }\n```\n\n========================================\n\nCode:\n```text\nconst createDBConnection = async () => {\n const dbUrl = Environment.get('DATABASE_URL')\n const db = new DataSource({\n type: 'postgres',\n url: dbUrl,\n synchronize: false,\n entities: [],\n connectTimeoutMS: 10000,\n })\n await db.initialize()\n return db\n}\n\nexport default createDBConnection\n```\n\n```text\nexport class Environment {\n public static get(key: string): string {\n const result = process.env[key]\n\n if (result === undefined) {\n throw new Error(`Failed to find key ${key} in environment`)\n }\n\n return result\n }\n```\n\n```text\nconst FakeDB = new DataSource({\n type: 'postgres',\n url: 'fakeURL',\n synchronize: false,\n entities: [],\n connectTimeoutMS: 10000,\n})\n\njest.mock('app/lib/connections/createDBConnection', () => {\n return jest.fn().mockImplementation(() => Promise.resolve(FakeDB))\n}\n)\n\nafterEach(() => {\n jest.clearAllMocks()\n})\n\ntest('creates a fake connection', async () => {\n const DbConnection = await createDBConnection()\n expect(DbConnection).toBeTruthy()\n expect(DbConnection).toBeInstanceOf(DataSource)\n expect(DbConnection).toEqual(FakeDB)\n \n // Im trying to make something like these pass\n expect(FakeDB.initialize).toHaveBeenCalled\n expect(FakeDB.isInitialized).toBe(true)\n})\n```\n\n```text\njest.mock('typeorm'), () => {\n return jest.fn().mockImplementation(() => {\n return {\n initialize: () => {true}\n }\n })\n }\n```\n\n```text\nconst mockDS = {\n initialize: jest.fn(),\n};\n\njest.mock(\"typeorm\", () => {\n return {\n DataSource: jest.fn().mockImplementation(() => mockDS),\n };\n});\n\n// Env\nconst mockEnv = {\n get: jest.fn(),\n};\njest.mock(\"src/path/to/environment/file\", () => {\n return {\n Environment: mockEnv,\n };\n});\n\nimport createDBConnection from \"src/app/lib/connections/createDBConnection.ts\";\n\nafterEach(() => {\n jest.clearAllMocks();\n});\n\ntest(\"calls .initialize() and env.get\", async () => {\n await createDBConnection();\n\n expect(mockEnv.get).toHaveBeenCalledWith(\"DATABASE_URL\");\n expect(mockDS.initialize).toHaveBeenCalled();\n});\n```\n\n```text\nDataSource\n```\n\n```text\nisInitialized=true\n```\n\n```text\ncreateDBConnection\n```\n\n```text\nDataSource\n```\n\n```text\ncreateDBConnection\n```\n\n```text\nEnvironment.get\n```\n\n```text\nDATABASE_URL\n```\n\n```text\ndb.initialize()\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.708Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":226,"estimatedTokens":1082}}338{"id":"stack-50656921","source":"stackoverflow","questionId":50656921,"title":"TypeORM create connection globally","tags":["node.js","typescript","typeorm"],"text":"Title: TypeORM create connection globally\nTags: node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am using typeorm with typescript in my node Js application. I am trying to figure out the way of using the single DB connection for all functions in the class. For example, I have two functions my class and want to use the global/single connection for all functions instead of creating a connection in every function as shown below:\n\n```\nexport class SQLDBService implements IDatabaseService{\nprivate readonly logger = getLogger(\"SQLDBService\");\nprivate connection:Connection;\n\n getConversation(conversationId: string): ConversationEntity {\n\n let conversationEntity = new ConversationEntity();\n createConnection(/*...*/).then(async connection => {\n let dbObj = await connection.getRepository(ConversationEntity).findOne({\n conversationId: Equal(conversationId)\n });\n if(dbObj)\n conversationEntity = dbObj;\n });\n return conversationEntity;\n}\n\n pushWrapUp(conversationId: string, wrapUp: string): void {\n\n createConnection().then(async connection => {\n let conversationEntity = await connection.getRepository(ConversationEntity).findOne({\n conversationId: Equal(conversationId)\n });\n if(conversationEntity){\n conversationEntity.wrapUp = wrapUp;\n conversationEntity.endTime = new Date();\n await connection.manager.save(conversationEntity);\n }\n });\n}}\n```\n\nCan someone point me in the right direction?\n\n========================================\n\nTop Answer:\nYou should use a global connection pool which will create, hold, and take care the used connections for you. I am not familiar with node.js, so I cannot give out a name of this kind 3rd party library. But there must be some, since the connection pool is a widely accepted design pattern.\n\n========================================\n\nCode:\n```text\nexport class SQLDBService implements IDatabaseService{\nprivate readonly logger = getLogger(\"SQLDBService\");\nprivate connection:Connection;\n\n\n getConversation(conversationId: string): ConversationEntity {\n\n let conversationEntity = new ConversationEntity();\n createConnection(/*...*/).then(async connection => {\n let dbObj = await connection.getRepository(ConversationEntity).findOne({\n conversationId: Equal(conversationId)\n });\n if(dbObj)\n conversationEntity = dbObj;\n });\n return conversationEntity;\n}\n\n pushWrapUp(conversationId: string, wrapUp: string): void {\n\n createConnection().then(async connection => {\n let conversationEntity = await connection.getRepository(ConversationEntity).findOne({\n conversationId: Equal(conversationId)\n });\n if(conversationEntity){\n conversationEntity.wrapUp = wrapUp;\n conversationEntity.endTime = new Date();\n await connection.manager.save(conversationEntity);\n }\n });\n}}\n```\n\n```text\nimport {getRepository} from \"typeorm\";\n\n ...\n async getConversation(conversationId: string): ConversationEntity {\n let conversationEntity = new ConversationEntity();\n let dbObj = getRepository(ConversationEntity).findOne({\n conversationId: Equal(conversationId)\n });\n if(dbObj) conversationEntity = dbObj;\n return conversationEntity;\n }\n```\n\n```text\nasync..await\n```\n\n```text\ncreateConnection\n```\n\n```text\ngetConnection()\n```\n\n```text\ncreateConnection\n```\n\n```text\ngetRepository\n```\n\n```text\nexport class SQLDBService implements IDatabaseService {\n private readonly logger = getLogger(\"SQLDBService\");\n private connection:Connection;\n\n init() {\n this.connection = await createConnection(/*...*/)\n }\n getConversation(conversationId: string): ConversationEntity {\n\n let conversationEntity = new ConversationEntity();\n let dbObj = await this.connection.getRepository(ConversationEntity).findOne({\n conversationId: Equal(conversationId)\n });\n if(dbObj)\n conversationEntity = dbObj;\n return conversationEntity;\n }\n\n pushWrapUp(conversationId: string, wrapUp: string): void {\n\n let conversationEntity = await this.connection.getRepository(ConversationEntity).findOne({\n conversationId: Equal(conversationId)\n });\n if(conversationEntity){\n conversationEntity.wrapUp = wrapUp;\n conversationEntity.endTime = new Date();\n await this.connection.manager.save(conversationEntity);\n }\n }\n}\n\nconst db = new SQLDBService()\ntry {\n await db.init()\n}\ncatch (error) {\n console.error(\"db connection error\")\n console.error(error)\n console.error(\"db connection error\")\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.709Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":160,"estimatedTokens":1152}}339{"id":"stack-61429463","source":"stackoverflow","questionId":61429463,"title":"Typeorm: paginate relations","tags":["node.js","postgresql","typescript","typeorm"],"text":"Title: Typeorm: paginate relations\nTags: node.js, postgresql, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have these two entities:\n\n```\n@Entity()\n@Unique([\"userName\"])\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n @Length(4, 20)\n userName: string;\n\n @ManyToMany(type => League, league => league.members)\n leagues: League[];\n\n}\n```\n\n```\n@Entity()\nexport class League {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n @Length(3, 50)\n name: string;\n\n @Column()\n @Length(0, 200)\n description: string;\n\n @Column()\n @Length(4, 20)\n country: string;\n\n @ManyToMany(type => User)\n @JoinTable()\n members: User[];\n}\n```\n\nBut a league can have many members so it is not optimal to bring all the members of a league into one call. Is it possible to paginate the relation of members of a league?\n\nMy models are wrong?\n\nI'm using typeorm@^0.2.24 and nodejs with typescript\n\n========================================\n\nCode:\n```text\n@Entity()\n@Unique([\"userName\"])\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n @Length(4, 20)\n userName: string;\n\n @ManyToMany(type => League, league => league.members)\n leagues: League[];\n\n}\n```\n\n```text\n@Entity()\nexport class League {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n @Length(3, 50)\n name: string;\n\n @Column()\n @Length(0, 200)\n description: string;\n\n @Column()\n @Length(4, 20)\n country: string;\n\n @ManyToMany(type => User)\n @JoinTable()\n members: User[];\n}\n```\n\n```text\n// This will be paginated\nconst leagueMembers = await connection\n .createQueryBuilder(User, \"user\")\n .leftJoin(\"user.leagues\", \"league\", \"league.id = :leagueId\"; { leagueId })\n .orderBy(\"user.id\")\n .skip(..)\n .take(..)\n .getMany();\n```\n\n```text\nfind\n```\n\n```text\nQueryBuilder\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":116,"estimatedTokens":449}}340{"id":"stack-66127800","source":"stackoverflow","questionId":66127800,"title":"TypeORM, ManyToOne relation: get parents rows that have no child relations","tags":["mysql","typeorm"],"text":"Title: TypeORM, ManyToOne relation: get parents rows that have no child relations\nTags: mysql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have 2 tables, `lists` and `items`. A list can have 0 or many items. An item is only in one list.\n\n```\nexport class List {\n @OneToMany(() => Item, (item) => item.list, {\n nullable: true,\n })\n items: Item[];\n}\n\nexport class Item {\n @ManyToOne(() => List, (list) => list.items)\n list: List;\n}\n```\n\n- How can I get **all** the `list` objects that have **0** item?\n\nMy code below is returning an error: Unknown column 'list.items' in 'where clause'.\n\n```\nconst listsWithoutItems = await this.listsRepository\n .createQueryBuilder('list')\n .where('list.item IS NULL')\n .getMany();\n```\n\n========================================\n\nCode:\n```js\nexport class List {\n @OneToMany(() => Item, (item) => item.list, {\n nullable: true,\n })\n items: Item[];\n}\n\nexport class Item {\n @ManyToOne(() => List, (list) => list.items)\n list: List;\n}\n```\n\n```js\nconst listsWithoutItems = await this.listsRepository\n .createQueryBuilder('list')\n .where('list.item IS NULL')\n .getMany();\n```\n\n```text\nlists\n```\n\n```text\nitems\n```\n\n```text\nlist\n```\n\n```text\nconst listsWithoutItems = await this.listsRepository\n.createQueryBuilder('list')\n.where('NOT EXISTS (SELECT * FROM Item i WHERE i.listId = list.id)')\n.getMany();\n```\n\n```text\nconst listsWithoutItems = await listsRepository\n .createQueryBuilder('list')\n .leftJoin('list.items', 'Item')\n .where('Item.id IS NULL')\n .getMany();\n```\n\n```text\n.where\n```\n\n========================================\n\nComments:\n- Thanks a lot for your help. It now works perfectly and I learned something new!","metadata":{"transformedAt":"2026-08-18T18:33:44.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":91,"estimatedTokens":418}}341{"id":"stack-72002706","source":"stackoverflow","questionId":72002706,"title":"Missing required argument: dataSource","tags":["node.js","postgresql","typeorm"],"text":"Title: Missing required argument: dataSource\nTags: node.js, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI tried to generate migration files with typeorm version 0.3.6.I don't know why but in version 0.2.x it work with the command\n\n```\nnpm run typeorm migration:generate -n \n```\n\nIn newest version,I't so mess with me, I get another to another bugs , finally, I think I almost done but I continue get the error\n\n```\nMissing required argument: dataSource\n```\n\nthis is scripts in my package.json\n\n```\n\"scripts\": {\n \"server\": \"nodemon dist/index.js\",\n \"watch\": \"tsc -w\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"typeorm\": \"ts-node ./node_modules/typeorm/cli.js\" \n },\n```\n\normconfig.json\n\n```\n{\n \"type\":\"postgres\",\n \"host\":\"localhost\",\n \"port\":5432,\n \"username\":\"postgres\",\n \"password\":\"\",\n \"database\":\"test-deploy\",\n \"entities\":[\"dist/entities/*.js\"],\n \"migrations\":[\"dist/migrations/*.js\"]\n}\n```\n\ndataSource.ts\n\n```\nexport const dataSource = new DataSource({\n type:\"postgres\",\n username: process.env.PG_USERNAME_DEV,\n password: process.env.PG_PASSWORD_DEV,\n database: \"memories\",\n synchronize: false,\n logging: false,\n entities: [Admin,...],\n subscribers: [],\n migrations: [],\n})\n//For ApolloServer\nexport const resolvers : NonEmptyArray =[AdminResolver,...]\n```\n\nMy file structure like this\n\n```\nserver\n src\n ...\n dist\n data-source.js\n entities/myEntity.js\n```\n\nand the command i use to generate migration\n\n```\nnpm run typeorm migration:generate -n initial -d dist/data-source.js\n```\n\nAm i missing something? How can i fix it?\n\n========================================\n\nCode:\n```text\nnpm run typeorm migration:generate -n <file name>\n```\n\n```text\nMissing required argument: dataSource\n```\n\n```text\n\"scripts\": {\n \"server\": \"nodemon dist/index.js\",\n \"watch\": \"tsc -w\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"typeorm\": \"ts-node ./node_modules/typeorm/cli.js\" \n },\n```\n\n```text\n{\n \"type\":\"postgres\",\n \"host\":\"localhost\",\n \"port\":5432,\n \"username\":\"postgres\",\n \"password\":\"\",\n \"database\":\"test-deploy\",\n \"entities\":[\"dist/entities/*.js\"],\n \"migrations\":[\"dist/migrations/*.js\"]\n}\n```\n\n```text\nexport const dataSource = new DataSource({\n type:\"postgres\",\n username: process.env.PG_USERNAME_DEV,\n password: process.env.PG_PASSWORD_DEV,\n database: \"memories\",\n synchronize: false,\n logging: false,\n entities: [Admin,...],\n subscribers: [],\n migrations: [],\n})\n//For ApolloServer\nexport const resolvers : NonEmptyArray<Function> =[AdminResolver,...]\n```\n\n```text\nserver\n src\n ...\n dist\n data-source.js\n entities/myEntity.js\n```\n\n```text\nnpm run typeorm migration:generate -n initial -d dist/data-source.js\n```\n\n```text\nconst AppDataSource = new DataSource({\n type: 'mysql',\n host: 'localhost',\n port: 645664,\n username: 'test',\n password: 'test',\n database: 'oracli',\n synchronize: false,\n logging: true,\n \"entities\": [\n \"src/typeorm/**/*.ts\"\n ],\n \"migrations\": [\n \"typeorm/migrations/**/*.ts\"\n ],\n \"subscribers\": [\n \"src/subscriber/**/*.ts\"\n ],\n});\n\nexport default AppDataSource;\n```\n\n```text\n\"migrate:create\": \"typeorm migration:create \\\"./typeorm/migrations/\",\n\"migrate:up\": \"ts-node --transpile-only ./node_modules/typeorm/cli.js migration:run -d ormconfig.ts\",\n\"migrate:down\": \"ts-node --transpile-only ./node-modules/typeorm/cli.js migration:revert\"\n```\n\n```text\nserver\n typeorm\n migrations\n src\n ormconfig.ts\n package.json\n```\n\n```text\normconfig.ts\n```\n\n```text\n\"typeorm\": \"^0.3.6\"\n```\n\n========================================\n\nComments:\n- I had same issue, and this thread solved the issue: stackoverflow.com/questions/71803499/…","metadata":{"transformedAt":"2026-08-18T18:33:44.709Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":193,"estimatedTokens":924}}342{"id":"stack-65459084","source":"stackoverflow","questionId":65459084,"title":"TypeError: circular structure to JSON starting at object with constructor 'ClientRequest' property 'socket' -> object with constructor 'Socket'","tags":["javascript","node.js","typescript","typeorm"],"text":"Title: TypeError: circular structure to JSON starting at object with constructor 'ClientRequest' property 'socket' -> object with constructor 'Socket'\nTags: javascript, node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nIm getting the following error when I try to make post request to my own typeorm API using axios:\n\n```\nTypeError: Converting circular structure to JSON\n --> starting at object with constructor 'ClientRequest'\n | property 'socket' -> object with constructor 'Socket'\n --- property '_httpMessage' closes the circle\n at JSON.stringify ()\n at stringify (C:\\Users\\Usuario\\Documents\\Manga-Api\\Manga-Api\\node_modules\\express\\lib\\response.js:1123:12)\n at ServerResponse.json (C:\\Users\\Usuario\\Documents\\Manga-Api\\Manga-Api\\node_modules\\express\\lib\\response.js:260:14)\n at ServerResponse.send (C:\\Users\\Usuario\\Documents\\Manga-Api\\Manga-Api\\node_modules\\express\\lib\\response.js:158:21)\n at C:\\Users\\Usuario\\Documents\\Manga-Api\\Manga-Api\\src\\managers\\scrape.manager.ts:163:33\n at processTicksAndRejections (node:internal/process/task_queues:93:5)\n```\n\nI have tried to use some libraries to fix the circular structure JSON and parse it but both failed:\n\n```\nconst safeStringify = require('json-stringify-safe');\nconst CircularJSON = require('circular-json');\n```\n\nNone of the entities's relations have cascade option added.\n\n```\nawait axios.post(apiName+'/object', data, { headers: { Authorization: res.req.headers.authorization } }).then(response => { res.send(response); });\n```\n\nData example with the object I want to persist in my database:\n\n```\ndata = {\n \"response\": \"Manga created\",\n \"manga\": {\n \"magazine\": {\n \"name\": \"JUMP SQ.\",\n \"japanName\": \"ジャンプSQ.\",\n \"website\": \"https://jumpsq.shueisha.co.jp/sq/\",\n \"releaseDate\": \"\",\n \"id\": 33,\n \"mangas\": [\n {\n \"finished\": false,\n \"id\": 91,\n \"chapter\": 312,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 166,\n \"chapter\": 201,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 175,\n \"chapter\": 85,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 202,\n \"chapter\": 95,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 363,\n \"chapter\": 94,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 366,\n \"chapter\": 124,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 456,\n \"chapter\": 46,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 515,\n \"chapter\": 50,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 520,\n \"chapter\": 14,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 567,\n \"chapter\": 14,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 1024,\n \"chapter\": 0,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n }\n ]\n },\n \"author\": {\n \"name\": \"AIMOTO SHOU\",\n \"japanName\": \"\",\n \"id\": 417,\n \"mangas\": [\n {\n \"finished\": false,\n \"id\": 456,\n \"chapter\": 46,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 1024,\n \"chapter\": 0,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n }\n ]\n },\n \"languages\": [\n {\n \"code\": 0,\n \"name\": \"Kemono Jihen\"\n },\n {\n \"code\": 1,\n \"name\": \"怪物事変\"\n }\n ]\n }\n}\n```\n\nIf I try to post this JSON via Postman It works propperly. Buy not by code, maybe due the circular problem with the Entities\n\n========================================\n\nTop Answer:\nTypeError: JSON circular structure starting from the object\n\nDelete that property from the object you want to return that caused this error or loop\n\nExample:\n\nDelete object.property\nin your case\nDelete object.socket\n\n========================================\n\nCode:\n```text\nTypeError: Converting circular structure to JSON\n --> starting at object with constructor 'ClientRequest'\n | property 'socket' -> object with constructor 'Socket'\n --- property '_httpMessage' closes the circle\n at JSON.stringify (<anonymous>)\n at stringify (C:\\Users\\Usuario\\Documents\\Manga-Api\\Manga-Api\\node_modules\\express\\lib\\response.js:1123:12)\n at ServerResponse.json (C:\\Users\\Usuario\\Documents\\Manga-Api\\Manga-Api\\node_modules\\express\\lib\\response.js:260:14)\n at ServerResponse.send (C:\\Users\\Usuario\\Documents\\Manga-Api\\Manga-Api\\node_modules\\express\\lib\\response.js:158:21)\n at C:\\Users\\Usuario\\Documents\\Manga-Api\\Manga-Api\\src\\managers\\scrape.manager.ts:163:33\n at processTicksAndRejections (node:internal/process/task_queues:93:5)\n```\n\n```text\nconst safeStringify = require('json-stringify-safe');\nconst CircularJSON = require('circular-json');\n```\n\n```text\nawait axios.post(apiName+'/object', data, { headers: { Authorization: res.req.headers.authorization } }).then(response => { res.send(response); });\n```\n\n```text\ndata = {\n \"response\": \"Manga created\",\n \"manga\": {\n \"magazine\": {\n \"name\": \"JUMP SQ.\",\n \"japanName\": \"ジャンプSQ.\",\n \"website\": \"https://jumpsq.shueisha.co.jp/sq/\",\n \"releaseDate\": \"\",\n \"id\": 33,\n \"mangas\": [\n {\n \"finished\": false,\n \"id\": 91,\n \"chapter\": 312,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 166,\n \"chapter\": 201,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 175,\n \"chapter\": 85,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 202,\n \"chapter\": 95,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 363,\n \"chapter\": 94,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 366,\n \"chapter\": 124,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 456,\n \"chapter\": 46,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 515,\n \"chapter\": 50,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 520,\n \"chapter\": 14,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 567,\n \"chapter\": 14,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 1024,\n \"chapter\": 0,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n }\n ]\n },\n \"author\": {\n \"name\": \"AIMOTO SHOU\",\n \"japanName\": \"\",\n \"id\": 417,\n \"mangas\": [\n {\n \"finished\": false,\n \"id\": 456,\n \"chapter\": 46,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n },\n {\n \"finished\": false,\n \"id\": 1024,\n \"chapter\": 0,\n \"state\": false,\n \"published\": false,\n \"updated\": false,\n \"priority\": 0\n }\n ]\n },\n \"languages\": [\n {\n \"code\": 0,\n \"name\": \"Kemono Jihen\"\n },\n {\n \"code\": 1,\n \"name\": \"怪物事変\"\n }\n ]\n }\n}\n```\n\n========================================\n\nComments:\n- I think `res.send` might be expecting something other than an entire response object.\n- @backtick You were right, I was supposed to do res.send(response.data) not the whole response object. Such a noob fail hahaha thank you bro!!\n- I have tried many methods. Finally, this worked for me. It was not res.send(), it was actually the data we are passing. I was passing simply response, but when I use response.data i got the result. Thanks","metadata":{"transformedAt":"2026-08-18T18:33:44.710Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":383,"estimatedTokens":2524}}343{"id":"stack-77258717","source":"stackoverflow","questionId":77258717,"title":"Cannot access variable before initialization error when variable is initialized in another file","tags":["node.js","typescript","typeorm","nodemon","ts-node"],"text":"Title: Cannot access variable before initialization error when variable is initialized in another file\nTags: node.js, typescript, typeorm, nodemon, ts-node\nSource: Stack Overflow\n\nQuestion:\nI have something like this:\n\nphoto.ts\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from \"typeorm\"\nimport { User } from \"./User\"\n\n@Entity()\nexport class Photo {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column()\n url: string\n\n @ManyToOne(() => User, (user) => user.photos)\n user: User\n}\n```\n\nuser.ts\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column, OneToMany } from \"typeorm\"\nimport { Photo } from \"./Photo\"\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column()\n name: string\n\n @OneToMany(() => Photo, (photo) => photo.user)\n photos: Photo[]\n}\n```\n\nAm running using `nodemon` and i have `ts-node` installed, but am getting the following error:\n\n```\nReferenceError: Cannot access 'User' before initialization\n at file:///path/to/project/src/database/entities/photo.ts:14:9\n at ModuleJob.run (node:internal/modules/esm/module_job:194:25)\n```\n\nThis error beats me as I don't even know where to start because, frankly, I have never encountered the error before, any help would be greatly appreciated.\n\nVersions:\n\n```\nnode: v18.17.1\nts-node: v10.9.1\nnodemon: v3.0.1\ntypescript: v5.2.2\n```\n\n========================================\n\nTop Answer:\nI had this issue when I had one file with global variable declaration:\n\n```\nvar v\n```\n\nand another file with local variable use but also this same local variable declaration (by accident) AFTER it was first used in a function:\n\n```\nfunction f() {\n\n v = 5;\n \n let v = 5;\n\n}\n```\n\nSo for the function `f` the variable `v` is local.\n\n========================================\n\nCode:\n```text\nimport { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from \"typeorm\"\nimport { User } from \"./User\"\n\n@Entity()\nexport class Photo {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column()\n url: string\n\n @ManyToOne(() => User, (user) => user.photos)\n user: User\n}\n```\n\n```text\nimport { Entity, PrimaryGeneratedColumn, Column, OneToMany } from \"typeorm\"\nimport { Photo } from \"./Photo\"\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column()\n name: string\n\n @OneToMany(() => Photo, (photo) => photo.user)\n photos: Photo[]\n}\n```\n\n```text\nReferenceError: Cannot access 'User' before initialization\n at file:///path/to/project/src/database/entities/photo.ts:14:9\n at ModuleJob.run (node:internal/modules/esm/module_job:194:25)\n```\n\n```text\nnode: v18.17.1\nts-node: v10.9.1\nnodemon: v3.0.1\ntypescript: v5.2.2\n```\n\n```text\nnodemon\n```\n\n```text\nts-node\n```\n\n```text\nphoto.ts\n```\n\n```text\nUser\n```\n\n```text\nuser.ts\n```\n\n```text\nuser\n```\n\n```text\nphotos\n```\n\n```text\nUser\n```\n\n```text\nPhoto\n```\n\n```text\nRelation\n```\n\n```text\nuser: Relation<User>\n```\n\n```text\nuser: User\n```\n\n```text\nphotos: Relation<Photo[]>\n```\n\n```text\nphotos: Photo[]\n```\n\n```text\nvar v\n```\n\n```text\nfunction f() {\n\n v = 5;\n \n let v = 5;\n\n}\n```\n\n```text\nf\n```\n\n```text\nv\n```\n\n```text\n/*jshint esversion: 6 */ \nconst https = require('https');\nconst url = require('url');\n. . . \n\n/** @type {Object} A JS Object holding the SSL certificate data */\nconst options = \n{\n key: fs.readFileSync('/etc/letsencrypt/live/sandsoft.ie/privkey.pem'),\n cert: fs.readFileSync('/etc/letsencrypt/live/sandsoft.ie/fullchain.pem')\n}; \n \n\nconst httpsServer = https.createServer(options, (req, res) =>\n{\n unifiedServer(req, res);\n});\n\n\nconst unifiedServer = (req, res) =>\n { \n let field,\n data, \n mode,\n message,\n ... \n etc; \n \n headers = { 'Access-Control-Allow-Origin': '*', \n 'Access-Control-Request-Method': '*',\n 'Access-Control-Allow-Headers': 'Content-Type',\n 'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',\n 'Access-Control-Max-Age': 2592000\n },\n endpoint = \"\", \n dashIndex = 0;\n \n if(req.method === 'GET')\n {\n const theURL = new URL(req.url, \"http://myco.com:3001\");\n endpoint = theURL.pathname;\n data = theURL.search.substring(1); \n let getUser = data.substring(data.indexOf(\"user=\") + 5, data.indexOf(\"&\"));\n router.route(endpoint, data, getCallback); // ERROR AT THIS LINE !!\n }\n\n if(req.method === 'POST')\n {\n endpoint = req.url;\n data = \"\";\n req.on('data', chunk =>\n {\n data=chunk.toString();\n });\n \n req.on('end', () => \n { \n router.route(endpoint, data, fetchCallback);\n }); \n }\n \n \n const getCallback = message => \n {\n . . . \n . . . \n . . . \n };\n \n \n const fetchCallback = message => \n {\n . . . \n . . . \n . . . \n };\n\n}\n\n\n\n\nhttpsServer.listen(3001, () => console.log(\"Node HTTPS server listening on port 3001 . . . \"));\n```\n\n```text\nif (req.method === \"GET\")\n```\n\n```text\nrouter.route(endpoint, data, getCallback);\n```\n\n========================================\n\nComments:\n- I don't have a (specific) solution for you, but the problem is that your two modules have a cyclic relationship and they both try to use the other's exported member during the initial module execution (thanks to the decorators). So one or the other has to be run first (`photo.ts` in your example) and when it tries to use `User`, that exported member hasn't been initialized yet because `user.ts` hasn't been executed yet. The general solution is to avoid that kind of cycle where each module tries to use the exported member from the other during the *initial* execution. But I don't know how...\n- ...you'd do that with the decorators above. In general, you'll have to delay the initialization of one of those classes until the other is ready. I can think of a hacky way to do that, but you'd have to pick whether to do it to `User` or `Photo` and that choice depends on how those are used by other modules.\n- To be clear: It's fine for modules to have cyclic relationships with each other, ESM is designed to handle that. The problem is when the top-level code in each module relies on the top-level code of the other module having already been run. In a non-cyclic relationship, the JavaScript engine can execute the modules in an appropriate order, but in a cyclic relationship it's a Catch-22.\n- Some information about \"circular relationships\" on the TypeORM website here: typeorm.io/#relations-in-esm-projects It says to use the `Relation` type to avoid this. Not clear to me how that helps, but I've never used TypeORM and not gotten into it in any depth, so...\n- @T.J.Crowder it actually works, you can put in answers so i accept it, thanks alot\n- Cyclic Redundancy is the one.","metadata":{"transformedAt":"2026-08-18T18:33:44.710Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":25,"totalLines":318,"estimatedTokens":1785}}344{"id":"stack-64032145","source":"stackoverflow","questionId":64032145,"title":"tsyringe - Injecting a dependency with overloaded constuctor","tags":["javascript","node.js","typescript","dependency-injection","typeorm"],"text":"Title: tsyringe - Injecting a dependency with overloaded constuctor\nTags: javascript, node.js, typescript, dependency-injection, typeorm\nSource: Stack Overflow\n\nQuestion:\nHi friends how are you doing?\n\nI'm trying to do something different, I don't know if it's away from the concept itself but it would help me to achieve what I'm trying to do in an elegant way.\n\nI'm using a repository pattern and in the implementation I want to use a overloaded constructor and use an optional argument, basically passing some adicional information when it's needed.\n\nThe problem is, it's working great when the constructor is empty, but by the time change de signature to receive one more argument, the TSYSRINGE throws an execption.\n\nI Really think that I'm missing something really simple, but I can't figure what. Could you please help me on this one? Thanks\n\n**ERROR:**\n\n```\nError: Cannot inject the dependency at position #0 of \"ListProjectsServices\" constructor. Reason:\n TypeInfo not known for \"ProjectsRepository\"\n```\n\n**Controller**\n\n```\nexport default class ProjectsController {\n public async index(request: Request, response: Response): Promise {\n const listProjectsServices = container.resolve(ListProjectsServices);\n const projects = await listProjectsServices.execute();\n response.json(projects);\n }\n```\n\n**Service**\n\n```\n@injectable()\nexport default class ListProjectsServices {\n\n constructor(\n @inject('ProjectsRepository')\n private ProjectsRepository: IProjectsRepository,\n ) {}\n\n public async execute(): Promise {\n const ProjectsList = await this.ProjectsRepository.findAllProjects();\n return ProjectsList;\n }\n}\n```\n\n**Container - to create the injection token**\n\n```\ncontainer.registerSingleton(\n 'ProjectsRepository',\n ProjectsRepository,\n);\n```\n\n**Repository - Notice the extra_details argument in the constructor**\n\nafter adding it, the problem occurs\n\n```\n@EntityRepository(Projects)\nexport default class ProjectsRepository implements IProjectsRepository {\n private ormRepository: Repository;\n\n constructor(extra_details?: object) {\n this.ormRepository = getRepository(Projects);\n }\n[...]\n```\n\n========================================\n\nTop Answer:\nWe had the same problem here and we didn't want to have to use the delay function in the controller because we would be breaking the dependency injection principle... One way to solve the problem is to import your \"Container\" file into the main project file, in our case called \"server.ts\" and installing a lib called \"reflect-metadata\".\n\nserver.ts:\n\n```\nimport * as dotenv from 'dotenv';\n\ndotenv.config();\n\nimport express from 'express';\nimport 'express-async-errors';\nimport 'reflect-metadata'; // here is reflect-metadata import!\nimport config from './config/application';\nimport './infra/container'; // here is container import!\nimport { errorHandler } from './infra/http/middlewares/errorHandler';\nimport useSwagger from './infra/http/middlewares/swagger';\nimport { routes } from './infra/http/routes';\nimport { morganMiddleware } from './infra/logging/morgan';\n\nexport const app = express();\n\napp.use(morganMiddleware);\napp.use(express.json());\napp.use(`${config.prefix}/api`, routes);\napp.use(`${config.prefix}`, express.static('public'));\nuseSwagger(`${config.prefix}/api/docs`, app);\napp.all(`${config.prefix}`, (_, res) => res.redirect(`${config.prefix}/api/docs`));\napp.use(errorHandler);\n```\n\ncontainer/index.ts:\n\n```\nimport { container } from 'tsyringe';\nimport { RecurrenceNotificationUseCase } from '../../application/useCases/RecurrenceNotificationUseCase';\nimport { PubSubImplementation } from '../pubsub/PubSubImplementation';\n\ncontainer.registerSingleton('IPubSub', PubSubImplementation);\ncontainer.registerSingleton('IRecurrenceNotificationUseCase', RecurrenceNotificationUseCase);\n```\n\n========================================\n\nCode:\n```js\nError: Cannot inject the dependency at position #0 of \"ListProjectsServices\" constructor. Reason:\n TypeInfo not known for \"ProjectsRepository\"\n```\n\n```js\nexport default class ProjectsController {\n public async index(request: Request, response: Response): Promise<void> {\n const listProjectsServices = container.resolve(ListProjectsServices);\n const projects = await listProjectsServices.execute();\n response.json(projects);\n }\n```\n\n```js\n@injectable()\nexport default class ListProjectsServices {\n\n constructor(\n @inject('ProjectsRepository')\n private ProjectsRepository: IProjectsRepository,\n ) {}\n\n public async execute(): Promise<Projects[]> {\n const ProjectsList = await this.ProjectsRepository.findAllProjects();\n return ProjectsList;\n }\n}\n```\n\n```js\ncontainer.registerSingleton<IProjectsRepository>(\n 'ProjectsRepository',\n ProjectsRepository,\n);\n```\n\n```js\n@EntityRepository(Projects)\nexport default class ProjectsRepository implements IProjectsRepository {\n private ormRepository: Repository<Projects>;\n\n constructor(extra_details?: object) {\n this.ormRepository = getRepository(Projects);\n }\n[...]\n```\n\n```text\nimport { container, delay } from 'tsyringe';\n\ncontainer.registerSingleton<IProjectsRepository>(\n 'ProjectsRepository',\n delay(() => ProjectsRepository),\n);\n```\n\n```text\n\"entities\": [\n \"./src/modules/**/infra/typeorm/entities/*.ts\"\n],\n```\n\n```text\nimport * as dotenv from 'dotenv';\n\ndotenv.config();\n\nimport express from 'express';\nimport 'express-async-errors';\nimport 'reflect-metadata'; // here is reflect-metadata import!\nimport config from './config/application';\nimport './infra/container'; // here is container import!\nimport { errorHandler } from './infra/http/middlewares/errorHandler';\nimport useSwagger from './infra/http/middlewares/swagger';\nimport { routes } from './infra/http/routes';\nimport { morganMiddleware } from './infra/logging/morgan';\n\nexport const app = express();\n\napp.use(morganMiddleware);\napp.use(express.json());\napp.use(`${config.prefix}/api`, routes);\napp.use(`${config.prefix}`, express.static('public'));\nuseSwagger(`${config.prefix}/api/docs`, app);\napp.all(`${config.prefix}`, (_, res) => res.redirect(`${config.prefix}/api/docs`));\napp.use(errorHandler);\n```\n\n```text\nimport { container } from 'tsyringe';\nimport { RecurrenceNotificationUseCase } from '../../application/useCases/RecurrenceNotificationUseCase';\nimport { PubSubImplementation } from '../pubsub/PubSubImplementation';\n\ncontainer.registerSingleton('IPubSub', PubSubImplementation);\ncontainer.registerSingleton('IRecurrenceNotificationUseCase', RecurrenceNotificationUseCase);\n```\n\n========================================\n\nComments:\n- Hey buddy, did you solved it?\n- No really friend, in fact I had to change the strategy.\n- This sounds interesting indeed, I will surely try. Sounds elegant and efficient! Thank you my friend!","metadata":{"transformedAt":"2026-08-18T18:33:44.710Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":226,"estimatedTokens":1677}}345{"id":"stack-67921425","source":"stackoverflow","questionId":67921425,"title":"TypeORM not converting `Date` to utc","tags":["date","serialization","typeorm"],"text":"Title: TypeORM not converting `Date` to utc\nTags: date, serialization, typeorm\nSource: Stack Overflow\n\nQuestion:\nLets start by providing the database definition of the entity in question:\n\n```\n@Column({ name: \"last_seen\", type: \"timestamp\", nullable: true })\n @Index()\n public lastSeen: Date | null = null;\n\n @CreateDateColumn({ name: \"created\", type: \"timestamp\", nullable: false })\n public created!: Date;\n```\n\nThe database is UTC but the server (in development) is in the \"Asia/Tehran\" time zone. As far as I know, TypeORM should store dates in UTC and convert them back to local time on retrieval.\n\nHowever, and I think this is happening recently since I don't remember having a similar issue on this project which is ongoing for 6 months now, but the Dates are now stored raw. For example, if I save `10:00+4:30` in javascript for the `lastSeen` property it will be saved invalidly as `10:00`.\n\nOn the other hand, when reading dates that are created by the database in \"UTC\" automatically, for example as is the case for the `created` property, the value is read in the local timezone instead of getting converted from \"UTC\". In these cases, the data is stored correctly in the Database in \"UTC\".\n\nIs there an option that I am missing here in regard to date time conversion with TypeORM?\n\n========================================\n\nCode:\n```js\n@Column({ name: \"last_seen\", type: \"timestamp\", nullable: true })\n @Index()\n public lastSeen: Date | null = null;\n\n @CreateDateColumn({ name: \"created\", type: \"timestamp\", nullable: false })\n public created!: Date;\n```\n\n```text\n10:00+4:30\n```\n\n```text\nlastSeen\n```\n\n```text\n10:00\n```\n\n```text\ncreated\n```\n\n```text\ntimestamptz\n```\n\n```text\ntimestamp\n```\n\n========================================\n\nComments:\n- I think you have to use `timestamptz` (timestamp with timezone) instead of the basic `timestamp`. See this article for more information. Moreover, as far as I know, `timestamptz` *is always* the best/suggested approach.\n- It makes no sense tho, TimestamptZ stores time zone data and it can make the DB more complicated instead of helping with it.\n- @CarloCorradini ok, it makes sense, thanks, will try, the naming here with timestamp and timestamptz is bad, to say the least.\n- Maybe you can add the answer so that this question shows up higher in searches. Indeed the `timestamp with time zone` approach helped me after a few hours of research. I was trying to prevent using timezone in the database as well, but simply throwing away the offset instead of taking it into account while there are no advantages to doing so makes no sense; at least not yet until someone points to another article that refutes the one @CarloCorradini sent.\n- @Pedram Done! Hope it helps! :)\n- If I'm not mistake this only works if the timezone of your database on the server is set correctly, right? So for example if Postgres on my server was set to 'Europe/Rome', then this would add an offset. That means you'd have to check if the timezone was set to UTC before applying `timestamptz`\n- @FlorestanKorp Citing the official doc: *All timezone-aware dates and times are stored internally in UTC. They are converted to local time in the zone specified by the TimeZone configuration parameter before being displayed to the client.*\n- If you use a date data type that is time zone aware, the whole procedure is quite simple because you can convert it to any other time zone or UTC/GMT with a single line of code.","metadata":{"transformedAt":"2026-08-18T18:33:44.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":71,"estimatedTokens":865}}346{"id":"stack-55629060","source":"stackoverflow","questionId":55629060,"title":"How to correctly update an entity with express and typeorm","tags":["node.js","express","typeorm"],"text":"Title: How to correctly update an entity with express and typeorm\nTags: node.js, express, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm looking for the best way to update a `User` entity with typeorm and express.\n\nI have something like this (I have reduced, but there are many other attributes) :\n\n```\nclass User {\n id: string;\n lastname: string;\n firstname: string;\n email: string;\n password: string;\n isAdmin: boolean;\n}\n```\n\nAnd I have a path to update user's attributes like : \n\n```\napp.patch(\"/users/me\", ensureAuthenticated, UserController.update);\n```\n\nNow (and it's my question), how to properly update the user? I don't want the user to be able to add themselves as an admin.\n\nSo I have : \n\n```\nexport const update = async (req: Request, res: Response) => {\n const { sub } = res.locals.token;\n const { lastname, firstname, phone, email } = req.body;\n\n const userRepository = getRepository(User);\n const currentUser = await userRepository.findOne({ id: sub });\n\n const newUserData: User = {\n ...currentUser,\n lastname: lastname || currentUser.lastname,\n firstname: firstname || currentUser.firstname,\n phone: phone || currentUser.phone,\n email: email || currentUser.email\n };\n\n await userRepository\n .update({ id: sub }, newUserData)\n .then(r => {\n return res.status(204).send();\n })\n .catch(err => {\n logger.error(err);\n return res.status(500).json({ error: \"Error.\" });\n });\n};\n```\n\nWith that, I'm sure to update the right attributes, and the user can't update admin. \nBut I find it very verbose to create a new object and fill in the informations.\n\nDo you have a better way to do it?\nThanks.\n\n========================================\n\nCode:\n```js\nclass User {\n id: string;\n lastname: string;\n firstname: string;\n email: string;\n password: string;\n isAdmin: boolean;\n}\n```\n\n```js\napp.patch(\"/users/me\", ensureAuthenticated, UserController.update);\n```\n\n```js\nexport const update = async (req: Request, res: Response) => {\n const { sub } = res.locals.token;\n const { lastname, firstname, phone, email } = req.body;\n\n const userRepository = getRepository(User);\n const currentUser = await userRepository.findOne({ id: sub });\n\n const newUserData: User = {\n ...currentUser,\n lastname: lastname || currentUser.lastname,\n firstname: firstname || currentUser.firstname,\n phone: phone || currentUser.phone,\n email: email || currentUser.email\n };\n\n await userRepository\n .update({ id: sub }, newUserData)\n .then(r => {\n return res.status(204).send();\n })\n .catch(err => {\n logger.error(err);\n return res.status(500).json({ error: \"Error.\" });\n });\n};\n```\n\n```text\nUser\n```\n\n```text\nclass UserDto {\n // define properties\n constructor(data: any) {\n // validate data\n ...\n }\n}\n\nconst userDto = new UserDto(req.body); \n\nawait userRepository\n .update({ id: sub }, userDto)\n .then(r => {\n ...\n })\n .catch(err => {\n ...\n });\n```\n\n========================================\n\nComments:\n- But what about when you use Nest with TypeORM? Then entities and DTOs are separate classes and you need a way to merge your entities with the data from the DTOs before saving them with the repository.\n- Yes in that case you'll need to convert DTO classes into the entity classes before saving them.","metadata":{"transformedAt":"2026-08-18T18:33:44.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":140,"estimatedTokens":832}}347{"id":"stack-63468683","source":"stackoverflow","questionId":63468683,"title":"Jest with NestJS and async function","tags":["nestjs","typeorm","ts-jest"],"text":"Title: Jest with NestJS and async function\nTags: nestjs, typeorm, ts-jest\nSource: Stack Overflow\n\nQuestion:\nI'm trying to a test a async function of a `service` in **nestJS**.\n\nthis function is async... basically get a value (JSON) from database (using repository - TypeORM), and when successfully get the data, \"transform\" to a different class (DTO)...\nthe implementation:\n\n```\nasync getAppConfig(): Promise {\n return this.configRepository.findOne({\n key: Equal(\"APPLICATION\"),\n }).then(config => {\n if (config == null) {\n return new class implements ConfigAppDto {\n clientId = '';\n clientSecret = '';\n };\n }\n return JSON.parse(config.value) as ConfigAppDto;\n });\n}\n```\n\nusing a controller, I checked that this worked ok.\nNow, I'm trying to use Jest to do the tests, but with no success...\nMy problem is how to mock the `findOne` function from `repository`..\n\n**Edit**: I'm trying to use `@golevelup/nestjs-testing` to mock `Repository`!\n\nI already mocked the `repository`, but for some reason, the `resolve` is never called..\n\n```\ndescribe('getAppConfig', () => {\n const repo = createMock>();\n\n beforeEach(async () => {\n await Test.createTestingModule({\n providers: [\n ConfigService,\n {\n provide: getRepositoryToken(Config),\n useValue: repo,\n }\n ],\n }).compile();\n });\n\n it('should return ConfigApp parameters', async () => {\n const mockedConfig = new Config('APPLICATION', '{\"clientId\": \"foo\",\"clientSecret\": \"bar\"}');\n repo.findOne.mockResolvedValue(mockedConfig);\n expect(await repo.findOne()).toEqual(mockedConfig); // ok\n\n const expectedReturn = new class implements ConfigAppDto {\n clientId = 'foo';\n clientSecret = 'bar';\n };\n expect(await service.getAppConfig()).toEqual(expectedReturn);\n\n // jest documentation about async -> https://jestjs.io/docs/en/asynchronous\n // return expect(service.getAppConfig()).resolves.toBe(expectedReturn);\n });\n})\n```\n\n- the `expect(await repo.findOne()).toEqual(mockedConfig);` works great;\n\n- `expect(await service.getAppConfig()).toEqual(expectedReturn);` got a timeout => `Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout`;\n\nusing debug, I see that the `service.getAppConfig()` is called, the `repository.findOne()` too, but the `.then` of repository of findOne is never called.\n\n**Update**: I'm trying to mock the repository using `@golevelup/nestjs-testing`, and for some reason, the mocked result don't works on service.\nIf I mock the repository using only `jest` (like code below), the test works... so, I think my real problem it's `@golevelup/nestjs-testing`.\n\n```\n...\nprovide: getRepositoryToken(Config),\nuseValue: {\n find: jest.fn().mockResolvedValue([new Config()])\n},\n...\n```\n\n========================================\n\nTop Answer:\nI think `expect(await repo.findOne()).toEqual(mockedConfig);` works because you mocked it, so it returns right away.\nIn the case of `expect(await service.getAppConfig()).toEqual(expectedReturn);`, you did not mock it so it is probably taking more time, thus the `it` function returns before the `Promise` resolved completely.\n\nThe comments you posted from jest documentation should do the trick if you mock the call to `getAppConfig()`.\n\n```\nservice.getAppConfig = jest.fn(() => Promise.resolve(someFakeValue))\n```\n\nor\n\n```\nspyOn(service, 'getAppConfig').and.mockReturnValue(Promise.resolve(fakeValue))\n```\n\n========================================\n\nCode:\n```text\nasync getAppConfig(): Promise<ConfigAppDto> {\n return this.configRepository.findOne({\n key: Equal(\"APPLICATION\"),\n }).then(config => {\n if (config == null) {\n return new class implements ConfigAppDto {\n clientId = '';\n clientSecret = '';\n };\n }\n return JSON.parse(config.value) as ConfigAppDto;\n });\n}\n```\n\n```text\ndescribe('getAppConfig', () => {\n const repo = createMock<Repository<Config>>();\n\n beforeEach(async () => {\n await Test.createTestingModule({\n providers: [\n ConfigService,\n {\n provide: getRepositoryToken(Config),\n useValue: repo,\n }\n ],\n }).compile();\n });\n\n it('should return ConfigApp parameters', async () => {\n const mockedConfig = new Config('APPLICATION', '{\"clientId\": \"foo\",\"clientSecret\": \"bar\"}');\n repo.findOne.mockResolvedValue(mockedConfig);\n expect(await repo.findOne()).toEqual(mockedConfig); // ok\n\n const expectedReturn = new class implements ConfigAppDto {\n clientId = 'foo';\n clientSecret = 'bar';\n };\n expect(await service.getAppConfig()).toEqual(expectedReturn);\n\n // jest documentation about async -> https://jestjs.io/docs/en/asynchronous\n // return expect(service.getAppConfig()).resolves.toBe(expectedReturn);\n });\n})\n```\n\n```text\n...\nprovide: getRepositoryToken(Config),\nuseValue: {\n find: jest.fn().mockResolvedValue([new Config()])\n},\n...\n```\n\n```text\nservice\n```\n\n```text\nfindOne\n```\n\n```text\nrepository\n```\n\n```text\n@golevelup/nestjs-testing\n```\n\n```text\nRepository\n```\n\n```text\nrepository\n```\n\n```text\nresolve\n```\n\n```text\nexpect(await repo.findOne()).toEqual(mockedConfig);\n```\n\n```text\nexpect(await service.getAppConfig()).toEqual(expectedReturn);\n```\n\n```text\nAsync callback was not invoked within the 5000 ms timeout specified by jest.setTimeout\n```\n\n```text\nservice.getAppConfig()\n```\n\n```text\nrepository.findOne()\n```\n\n```text\n.then\n```\n\n```text\n@golevelup/nestjs-testing\n```\n\n```text\njest\n```\n\n```text\n@golevelup/nestjs-testing\n```\n\n```text\n// i'm injecting Connection because I need for some transactions later;\nconstructor(@InjectRepository(Config) private readonly configRepo: Repository<Config>, private connection: Connection) {}\n\nasync getAppConfig(): Promise<ConfigApp> {\n return this.configRepo.findOne({\n key: Equal(\"APPLICATION\"),\n }).then(config => {\n if (config == null) {\n return new ConfigApp();\n }\n return JSON.parse(config.value) as ConfigApp;\n })\n}\n```\n\n```text\ndescribe('getAppConfig', () => {\n const configApi = new Config();\n configApi.key = 'APPLICATION';\n configApi.value = '{\"clientId\": \"foo\", \"clientSecret\": \"bar\"}';\n\n beforeEach(async () => {\n const module = await Test.createTestingModule({\n providers: [\n ConfigAppService,\n {\n provide: getRepositoryToken(Config),\n useValue: {\n findOne: jest.fn().mockResolvedValue(new\n Config(\"APPLICATION\", '{\"clientId\": \"foo\", \"clientSecret\": \"bar\"}')),\n },\n },\n {\n provide: getConnectionToken(),\n useValue: {},\n }\n ],\n }).compile();\n\n service = module.get<ConfigAppService>(ConfigAppService);\n });\n\n it('should return ConfigApp parameters', async () => {\n const expectedValue: ConfigApp = new ConfigApp(\"foo\", \"bar\");\n\n return service.getAppConfig().then(value => {\n expect(value).toEqual(expectedValue);\n })\n });\n})\n```\n\n```text\nRepository\n```\n\n```text\nNestJS\n```\n\n```text\n@golevelup/nestjs-testing\n```\n\n```text\n@golevelup/nestjs-testing\n```\n\n```text\nJest\n```\n\n```text\nNestJS\n```\n\n```text\nservice.getAppConfig = jest.fn(() => Promise.resolve(someFakeValue))\n```\n\n```text\nspyOn(service, 'getAppConfig').and.mockReturnValue(Promise.resolve(fakeValue))\n```\n\n```text\nexpect(await repo.findOne()).toEqual(mockedConfig);\n```\n\n```text\nexpect(await service.getAppConfig()).toEqual(expectedReturn);\n```\n\n```text\nit\n```\n\n```text\nPromise\n```\n\n```text\ngetAppConfig()\n```\n\n```text\nusersRepository.findOneOrFail.mockResolvedValue({ userId: 1, email: \"some-random-email@email.com\" });\n```\n\n```js\ndescribe(\"UsersService\", () => {\n let usersService: UsersService;\n const usersRepository = createMock<Repository<User>>();\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n UsersService,\n {\n provide: getRepositoryToken(User),\n useValue: usersRepository,\n },\n }).compile();\n\n usersService = module.get(UsersService);\n });\n\n it(\"should be defined\", () => {\n expect(usersService).toBeDefined();\n });\n it(\"finds a user\", async () => {\n usersRepository.findOne.mockResolvedValue({ userId: 1, email: \"some-random-email@email.com\" });\n\n expect(await usersRepository.findOne()).toBe({ userId: 1, email: \"some-random-email@email.com\" });\n });\n});\n```\n\n```text\ncreateMock\n```\n\n```text\n@golevelup/nestjs-testing\n```\n\n```text\ncreateMock\n```\n\n========================================\n\nComments:\n- What does your ConfigService look like?\n- It's the first part of the code in the question: `async getAppConfig(): Promise`\n- My question was on the implementation of the ConfigService ;) How do you load the env vars? Can you show us?\n- i don't get! no env vars used! the `ConfigService.APP_CONFIG_KEY` its just a static string with value `\"APPLICATION\"`. Almost the entire ConfigService it's here... the only part that I don't included its the static string, imports, and constructor (with `@InjectRepository`, because this is not related with the problem... I will update the code)\n- What if you comment ` expect(await repo.findOne()).toEqual(mockedConfig); // ok`? Maybe jest is mocking only in the first time, just guessing.\n- but I don't wanna mock `getAppConfig` function! I wanna test this function... I mocked the `findOne` because internally, the getAppConfig use this. About taking more time, I already configured Jest for timeout after 60 seconds, and still, the timeout occur, because the `then` is never called.\n- Ok, and if you try the example from jest documentation ? `return expect(service.getAppConfig()).resolves.toBe(expectedReturn)‌​;`\n- I already tried the example from jest documentation: `Timeout - Async callback was not invoked within the 60000 ms timeout specified by jest.setTimeout.Error:`","metadata":{"transformedAt":"2026-08-18T18:33:44.710Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":39,"totalLines":389,"estimatedTokens":2431}}348{"id":"stack-72529880","source":"stackoverflow","questionId":72529880,"title":"Updating an entity's type in TypeORM single table inheritance","tags":["typescript","postgresql","typeorm","single-table-inheritance"],"text":"Title: Updating an entity's type in TypeORM single table inheritance\nTags: typescript, postgresql, typeorm, single-table-inheritance\nSource: Stack Overflow\n\nQuestion:\nIs there any way to change an inheriting entity's type (in the DB) to a different entity type?\n\n========================================\n\nCode:\n```text\nawait em.update(OldType, { uid: uid }, {[entityTypeColumnName]: 'NewType'})\n```\n\n```text\nuid\n```\n\n```text\nOldType\n```\n\n```text\nNewType\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":25,"estimatedTokens":115}}349{"id":"stack-56972374","source":"stackoverflow","questionId":56972374,"title":"Is it possible to do a full join with Typeorm?","tags":["typeorm"],"text":"Title: Is it possible to do a full join with Typeorm?\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nIs there a way to do a full join with Typeorm?\n\nMy current query looks like this:\n\n```\nthis.myRepository.createQueryBuilder('myEntity')\n```\n\nI need to fetch all `myEntity` rows. Sometimes they are related to a `myRelatedEntity` row, in which case the data of the latter must be fetched too. Sometimes they are not related to a `myRelationEntity`, in which case I still need to fetch the `myEntity` row.\n\nApparently there is no other way to do what I need than with a FULL JOIN. However it seems like FULL JOINs are not available in Typeorm.\n\nIs there any way I can reach my goal?\n\n========================================\n\nCode:\n```text\nthis.myRepository.createQueryBuilder('myEntity')\n```\n\n```text\nmyEntity\n```\n\n```text\nmyRelatedEntity\n```\n\n```text\nmyRelationEntity\n```\n\n```text\nmyEntity\n```\n\n```text\nthis.myRepository.query(`\n SELECT *\n FROM myEntity\n FULL JOIN otherEntity ON otherEntity.id = myEntity.fid\n`);\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":49,"estimatedTokens":257}}350{"id":"stack-69256658","source":"stackoverflow","questionId":69256658,"title":"Sudden TypeORM FindConditions type errors","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: Sudden TypeORM FindConditions type errors\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nAfter reinstalling node_modules I am suddenly getting a FindOneOptions/ObjectID error in my NestJS service.\n\nWas building fine minutes ago beforehand.\nMakes me wonder, is this a code err or a typings err?\n\nUsing \"@nestjs/typeorm\": \"^7.1.5\"\n\nWhich seems to be using typeorm 0.2.35:\n\nLocal installed version: 0.2.35.\n\nGlobal installed TypeORM version: 0.2.37.\n\nThe actual code\n\n```\nasync getOne(id: number, userId?: string, type?: XPType, currentUser?: User) {\n const options: FindConditions = {\n id\n };\n userId && (options.userId = userId);\n type && (options.type = type);\n\n const post = await XP.findOne(options); // Here is the actual error:\n\n```\nNo overload matches this call.\n Overload 1 of 3, '(this: ObjectType, id?: string | number | Date | ObjectID, options?: FindOneOptions): Promise', gave the following error.\n Argument of type 'FindConditions' is not assignable to parameter of type 'string | number | Date | ObjectID'.\n Type 'FindConditions' is missing the following properties from type 'ObjectID': generationTime, equals, generate, getTimestamp, toHexString\n Overload 2 of 3, '(this: ObjectType, options?: FindOneOptions): Promise', gave the following error.\n Type 'FindConditions' has no properties in common with type 'FindOneOptions'.\n Overload 3 of 3, '(this: ObjectType, conditions?: FindConditions, options?: FindOneOptions): Promise', gave the following error.\n Argument of type 'import(\"/Users/bracicot/dev/dev-server/dev-server/node_modules/typeorm/find-options/FindConditions\").FindConditions' is not assignable to parameter of type 'import(\"/Users/bracicot/dev/dev-server/packages/server-common/node_modules/typeorm/find-options/FindConditions\").FindConditions'.\n Types of property 'userId' are incompatible.\n Type 'string | import(\"/Users/bracicot/dev/dev-server/dev-server/node_modules/typeorm/find-options/FindOperator\").FindOperator' is not assignable to type 'string | import(\"/Users/bracicot/dev/dev-server/packages/server-common/node_modules/typeorm/find-options/FindOperator\").FindOperator'.\n Type 'FindOperator' is not assignable to type 'string | FindOperator'.\n Type 'import(\"/Users/bracicot/dev/dev-server/dev-server/node_modules/typeorm/find-options/FindOperator\").FindOperator' is not assignable to type 'import(\"/Users/bracicot/dev/dev-server/packages/server-common/node_modules/typeorm/find-options/FindOperator\").FindOperator'.\n Types have separate declarations of a private property '_type'.ts(2769)\nconst options: FindConditions\n```\n\nSeems to be related to 4241 but am not sure. I'm hoping someone can help me understand this.\n\n========================================\n\nCode:\n```text\nasync getOne(id: number, userId?: string, type?: XPType, currentUser?: User) {\n const options: FindConditions<XP> = {\n id\n };\n userId && (options.userId = userId);\n type && (options.type = type);\n\n const post = await XP.findOne(options); // <-- error\n ...\n```\n\n```text\nNo overload matches this call.\n Overload 1 of 3, '(this: ObjectType<XP>, id?: string | number | Date | ObjectID, options?: FindOneOptions<XP>): Promise<...>', gave the following error.\n Argument of type 'FindConditions<XP>' is not assignable to parameter of type 'string | number | Date | ObjectID'.\n Type 'FindConditions<XP>' is missing the following properties from type 'ObjectID': generationTime, equals, generate, getTimestamp, toHexString\n Overload 2 of 3, '(this: ObjectType<XP>, options?: FindOneOptions<XP>): Promise<XP>', gave the following error.\n Type 'FindConditions<XP>' has no properties in common with type 'FindOneOptions<XP>'.\n Overload 3 of 3, '(this: ObjectType<XP>, conditions?: FindConditions<XP>, options?: FindOneOptions<XP>): Promise<...>', gave the following error.\n Argument of type 'import(\"/Users/bracicot/dev/dev-server/dev-server/node_modules/typeorm/find-options/FindConditions\").FindConditions<import(\"/Users/bracicot/dev/dev-server/packages/server-common/dist/entities/experience-post.entity\").XP>' is not assignable to parameter of type 'import(\"/Users/bracicot/dev/dev-server/packages/server-common/node_modules/typeorm/find-options/FindConditions\").FindConditions<import(\"/Users/bracicot/dev/dev-server/packages/server-common/dist/entities/experience-post.entity\").XP>'.\n Types of property 'userId' are incompatible.\n Type 'string | import(\"/Users/bracicot/dev/dev-server/dev-server/node_modules/typeorm/find-options/FindOperator\").FindOperator<string>' is not assignable to type 'string | import(\"/Users/bracicot/dev/dev-server/packages/server-common/node_modules/typeorm/find-options/FindOperator\").FindOperator<string>'.\n Type 'FindOperator<string>' is not assignable to type 'string | FindOperator<string>'.\n Type 'import(\"/Users/bracicot/dev/dev-server/dev-server/node_modules/typeorm/find-options/FindOperator\").FindOperator<string>' is not assignable to type 'import(\"/Users/bracicot/dev/dev-server/packages/server-common/node_modules/typeorm/find-options/FindOperator\").FindOperator<string>'.\n Types have separate declarations of a private property '_type'.ts(2769)\nconst options: FindConditions<XP>\n```\n\n```text\n'string | import(\"/Users/bracicot/dev/dev-server/dev-server/node_modules/typeorm/find-options/FindOperator\").FindOperator<string>'\n```\n\n```text\n'string | import(\"/Users/bracicot/dev/dev-server/packages/server-common/node_modules/typeorm/find-options/FindOperator\").FindOperator<string>\n```\n\n```text\nFindConditions\n```\n\n```text\n(this: ObjectType<XP>, conditions?: FindConditions<XP>, options?: FindOneOptions<XP>): Promise<...>\n```\n\n```text\ndev-server\n```\n\n```text\nserver-common\n```\n\n```text\nnode_modules/typeorm/find-options/FindOperator\n```\n\n```text\nTypes have separate declarations of a private property '_type'.\n```\n\n```text\nserver-common\n```\n\n```text\nserver-common\n```\n\n```text\nAfter reinstalling node_modules\n```\n\n```text\n^\n```\n\n```text\n~\n```\n\n```text\nx\n```\n\n```text\npackage.json\n```\n\n========================================\n\nComments:\n- what's the type of `XP`? I'm using `FindConditions` type just like you but with custom repositories\n- Hey @MicaelLevi it's a class to model the data. Standard data stuff in it such as id, title, and many others. For now I've changed all instances of `FindConditions` to `any`. No idea what happened here.\n- Wow @Martin Grönlund thank you for such a detailed and brilliant answer.","metadata":{"transformedAt":"2026-08-18T18:33:44.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":147,"estimatedTokens":1627}}351{"id":"stack-66881061","source":"stackoverflow","questionId":66881061,"title":"how to create how to create many to many relationship in typeorm, [NestJS]","tags":["mysql","nestjs","typeorm"],"text":"Title: how to create how to create many to many relationship in typeorm, [NestJS]\nTags: mysql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHow can I save data in manytomany relationship??\n(user, book (MTM))\nhere is a many-to-many relationship between the user and the book.\nMy service is not correct.\nAlso, my code doesn't work.\nThe data is stored in the book table.\n\nI need your help, everything\nThank you in advance.\n\nMy Stack => NestJs, TypeORM, MySQL\n\nThere are my entities.\nenter image description here\n\nuser.entity\n\n```\n@Entity('User')\nexport class User {\n @PrimaryGeneratedColumn()\n id!: number;\n\n @Column()\n real_name!: string;\n\n @Column()\n nick_name!: string;\n\n @Column()\n @IsEmail()\n email!: string;\n\n @Column()\n password!: string;\n\n @Column()\n phone_number!: string;\n\n @Column()\n image_url: string;\n\n @BeforeInsert()\n async hashPassword() {\n this.password = await argon2.hash(this.password, {type: argon2.argon2id, hashLength: 40});\n }\n}\n```\n\nbook.entity\n\n```\n@Entity('Book')\nexport class Book {\n @PrimaryGeneratedColumn()\n id!: number;\n\n @Column()\n title: string;\n\n @Column()\n image_url: string;\n\n @Column()\n contents: string;\n\n @Column({ type: 'datetime'})\n datetime: string;\n\n @ManyToMany(() => User)\n @JoinTable()\n users: User[];\n}\n```\n\nbook.controller.ts\n\n```\n@UseGuards(JwtAuthGuard)\n @Post('bpc')\n savebpc(@Req() req: any, @Query('title') bookTitle: string){\n return this.BookService.addBpc(req, bookTitle);\n }\n```\n\nbook.service.ts\n\n```\nasync addBpc(req: any, bookTitle: string): Promise{\n const userId = req.user.id;\n const bookId = await getRepository('Book')\n .createQueryBuilder('book')\n .where({title:bookTitle})\n .getRawOne()\n\n if (!bookId){\n throw new NotFoundException('Not_found_book');\n }\n\n const user = await getRepository('User')\n .createQueryBuilder('user')\n .where({id: userId})\n .getRawOne()\n\n //bookId.user.push(user);\n //await this.bookRepository.save(bookId);\n\n let userdata = new User();\n userdata.id = user.user_id;\n userdata.real_name = user.user_real_name;\n userdata.nick_name = user.user_nick_name;\n userdata.email = user.user_email;\n userdata.password = user.user_password;\n userdata.image_url = user.user_image_url;\n console.log(userdata);\n \n\n let bookBpc = new Book();\n bookBpc.title = bookId.book_title;\n bookBpc.image_url = bookId.book_image_url;\n bookBpc.contents = bookId.book_contents;\n bookBpc.datetime = bookId.book_datetime;\n bookBpc.users = [user];\n console.log(bookBpc);\n\n await this.bookRepository.create([bookBpc]);\n return 'suceess';\n }\n```\n\n========================================\n\nCode:\n```text\n@Entity('User')\nexport class User {\n @PrimaryGeneratedColumn()\n id!: number;\n\n @Column()\n real_name!: string;\n\n @Column()\n nick_name!: string;\n\n @Column()\n @IsEmail()\n email!: string;\n\n @Column()\n password!: string;\n\n @Column()\n phone_number!: string;\n\n @Column()\n image_url: string;\n\n @BeforeInsert()\n async hashPassword() {\n this.password = await argon2.hash(this.password, {type: argon2.argon2id, hashLength: 40});\n }\n}\n```\n\n```text\n@Entity('Book')\nexport class Book {\n @PrimaryGeneratedColumn()\n id!: number;\n\n @Column()\n title: string;\n\n @Column()\n image_url: string;\n\n @Column()\n contents: string;\n\n @Column({ type: 'datetime'})\n datetime: string;\n\n @ManyToMany(() => User)\n @JoinTable()\n users: User[];\n}\n```\n\n```text\n@UseGuards(JwtAuthGuard)\n @Post('bpc')\n savebpc(@Req() req: any, @Query('title') bookTitle: string){\n return this.BookService.addBpc(req, bookTitle);\n }\n```\n\n```text\nasync addBpc(req: any, bookTitle: string): Promise<any>{\n const userId = req.user.id;\n const bookId = await getRepository('Book')\n .createQueryBuilder('book')\n .where({title:bookTitle})\n .getRawOne()\n\n if (!bookId){\n throw new NotFoundException('Not_found_book');\n }\n\n const user = await getRepository('User')\n .createQueryBuilder('user')\n .where({id: userId})\n .getRawOne()\n\n\n //bookId.user.push(user);\n //await this.bookRepository.save(bookId);\n\n let userdata = new User();\n userdata.id = user.user_id;\n userdata.real_name = user.user_real_name;\n userdata.nick_name = user.user_nick_name;\n userdata.email = user.user_email;\n userdata.password = user.user_password;\n userdata.image_url = user.user_image_url;\n console.log(userdata);\n \n\n let bookBpc = new Book();\n bookBpc.title = bookId.book_title;\n bookBpc.image_url = bookId.book_image_url;\n bookBpc.contents = bookId.book_contents;\n bookBpc.datetime = bookId.book_datetime;\n bookBpc.users = [user];\n console.log(bookBpc);\n\n await this.bookRepository.create([bookBpc]);\n return 'suceess';\n }\n```\n\n```text\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n @Column({ type: 'varchar', nullable: false, unique: true })\n username: string;\n // we need to add a default password and get it form the .env file\n @Column({ type: 'varchar', nullable: true, default: '' })\n password: string;\n @Column({ type: 'varchar', nullable: true })\n firstname: string;\n @Column({ type: 'varchar', nullable: true })\n lastname: string;\n @Column({ type: 'varchar', nullable: false })\n email: string;\n @Column({ type: 'boolean', nullable: true, default: false })\n connected: boolean;\n @CreateDateColumn({ name: 'created_at' })\n createdAt: Date;\n\n @UpdateDateColumn({ name: 'updated_at' })\n updatedAt: Date;\n\n // new properties\n @Column({ name: 'login_attempts', type: 'int', default: 0, nullable: true })\n loginAttempts: number;\n @Column({ name: 'lock_until', type: 'bigint', default: 0, nullable: true })\n lockUntil: number;\n\n //Many-to-many relation with role\n @ManyToMany((type) => Role, {\n cascade: true,\n })\n @JoinTable({\n name: \"users_roles\",\n joinColumn: { name: \"userId\", referencedColumnName: \"id\" },\n inverseJoinColumn: { name: \"roleId\" }\n })\n roles: Role[];\n}\n```\n\n```text\n@Entity()\nexport class Role {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column({ type: 'varchar', nullable: false, unique: true })\n profile: string;\n\n @Column({ type: 'varchar', nullable: false })\n description: string;\n\n //Many-to-many relation with user\n @ManyToMany((type) => User, (user) => user.roles)\n users: User[];\n @CreateDateColumn({ name: 'created_at' })\n createdAt: Date;\n\n @UpdateDateColumn({ name: 'updated_at' })\n updatedAt: Date;\n}\n```\n\n```text\nlet entity = await this.userRepository.create(data); //here you create new dataobject that contain user columns \n\n let entity2 = { ...entity, roles: data.selectedRoles } // you have to add the association roles here \n\n const user = await this.userRepository.save(entity2);\n```\n\n========================================\n\nComments:\n- Thank you so much for your answer in the midst of busy. I got a hint from the answer and solved it with the code below It doesn't matter though it looks like a shortcut. await getConnection() .createQueryBuilder() .relation(Book, \"users\") .of(bookBpc) .add(userdata);","metadata":{"transformedAt":"2026-08-18T18:33:44.710Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":324,"estimatedTokens":1787}}352{"id":"stack-76982359","source":"stackoverflow","questionId":76982359,"title":"How to replace deprecated getConnectionManager and getManager?","tags":["nestjs","typeorm"],"text":"Title: How to replace deprecated getConnectionManager and getManager?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a NestJS application utilizing TypeORM for database access.\n\nTypeORM has deprecated how `getConnection` and `getConnectionManager` can be used. I need direct access to it for dealing with transactions.\n\nHow to deal with this nowadays?\n\nThe answer at getConnection/getRepository typeorm is deprecated is not helpful and can't be applied on NestJS applications.\n\nMy `app.module.ts` looks like this:\n\n```\nconst connectionOptions: ConnectionOptions = {\n type: 'postgres',\n host: config.host,\n port: config.port,\n username: config.user || 'postgres',\n // ...\n}\n@Module({\n imports: [\n ConfigModule.forRoot({\n isGlobal: true,\n cache: true,\n load: [configuration],\n }),\n\n TypeOrmModule.forRoot({\n ...connectionOptions,\n autoLoadEntities: true,\n }),\n```\n\nFor handling transactions, I found the following docs:\n\n```\nimport {getManager} from \"typeorm\";\nawait getManager().transaction(async transactionalEntityManager => {\n\n});\n```\n\nUnfortunately, `getManager` is deprecated.\n\nIn the TypeORM-Gitbook, I found the following examples:\n\n```\nawait myDataSource.transaction(async (transactionalEntityManager) => {\n // execute queries using transactionalEntityManager\n})\n```\n\nHowever, it is not clear to me how to achieve this global DataSource-instance and how to inject this one into `app.module.ts` initialization?\n\nIn the answer to the question I mentioned at the beginning, they suggest code like:\n\n```\nexport const appDataSource = new DataSource({\n // ... options\n});\n```\n\nIn the scope of a NestJS application, I can't find a suitable place to inject this.\n\n`package.json`:\n\n```\n\"dependencies\": {\n \"@golevelup/ts-jest\": \"^0.3.6\",\n \"@nestjs/axios\": \"^3.0.0\",\n \"@nestjs/common\": \"^9.0.0\",\n \"@nestjs/config\": \"^2.3.1\",\n \"@nestjs/core\": \"^9.0.0\",\n \"@nestjs/jwt\": \"^10.0.3\",\n \"@nestjs/passport\": \"^9.0.3\",\n \"@nestjs/platform-express\": \"^9.0.0\",\n \"@nestjs/swagger\": \"^6.3.0\",\n \"@nestjs/typeorm\": \"^9.0.1\",\n \"typeorm\": \"^0.3.15\",\n // ...\n}\n```\n\n========================================\n\nCode:\n```text\nconst connectionOptions: ConnectionOptions = {\n type: 'postgres',\n host: config.host,\n port: config.port,\n username: config.user || 'postgres',\n // ...\n}\n@Module({\n imports: [\n ConfigModule.forRoot({\n isGlobal: true,\n cache: true,\n load: [configuration],\n }),\n\n TypeOrmModule.forRoot({\n ...connectionOptions,\n autoLoadEntities: true,\n }),\n```\n\n```text\nimport {getManager} from \"typeorm\";\nawait getManager().transaction(async transactionalEntityManager => {\n\n});\n```\n\n```text\nawait myDataSource.transaction(async (transactionalEntityManager) => {\n // execute queries using transactionalEntityManager\n})\n```\n\n```text\nexport const appDataSource = new DataSource({\n // ... options\n});\n```\n\n```text\n\"dependencies\": {\n \"@golevelup/ts-jest\": \"^0.3.6\",\n \"@nestjs/axios\": \"^3.0.0\",\n \"@nestjs/common\": \"^9.0.0\",\n \"@nestjs/config\": \"^2.3.1\",\n \"@nestjs/core\": \"^9.0.0\",\n \"@nestjs/jwt\": \"^10.0.3\",\n \"@nestjs/passport\": \"^9.0.3\",\n \"@nestjs/platform-express\": \"^9.0.0\",\n \"@nestjs/swagger\": \"^6.3.0\",\n \"@nestjs/typeorm\": \"^9.0.1\",\n \"typeorm\": \"^0.3.15\",\n // ...\n}\n```\n\n```text\ngetConnection\n```\n\n```text\ngetConnectionManager\n```\n\n```text\napp.module.ts\n```\n\n```text\ngetManager\n```\n\n```text\napp.module.ts\n```\n\n```text\npackage.json\n```\n\n```text\nimport { DataSource, Repository } from 'typeorm';\n\n@Injectable()\nexport class MyFancyService {\n constructor(\n private dataSource: DataSource\n ) {}\n```\n\n```text\nDataSource\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":185,"estimatedTokens":902}}353{"id":"stack-62228684","source":"stackoverflow","questionId":62228684,"title":"typeorm how to write to different databases?","tags":["javascript","sql","typescript","typeorm"],"text":"Title: typeorm how to write to different databases?\nTags: javascript, sql, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to create one table in one database and another table in another database. For this to work there are 2 entities that are addressing the correct database with the `@Entity` decorator. The problem is that `typeorm` or rather `SQL` throws an error that user x can't write in database y.\n\nHow to address the different databases correctly?\n\n```\n// src/entity/User.ts\nimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'\n\n@Entity({database: 'db1'})\nexport class User {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column()\n mame: string\n}\n```\n\n```\n// src/entity/Movie.ts\nimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'\n\n@Entity({database: 'db2'})\nexport class Movie {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column()\n title: string\n}\n```\n\nThe connections are created with their proper credentials:\n\n```\n// src/index.ts\n await createConnection({\n name: 'connection1',\n host: 'SERVER1',\n username: 'bob',\n password: 'xxx',\n type: 'mssql',\n database: 'db1',\n synchronize: true,\n entities: ['src/entity/**/*.ts'],\n migrations: ['src/migration/**/*.ts'],\n subscribers: ['src/subscriber/**/*.ts'],\n cli: {\n entitiesDir: 'src/entity',\n migrationsDir: 'src/migration',\n subscribersDir: 'src/subscriber',\n },\n })\n\n await createConnection({\n name: 'connection2',\n host: 'SERVER2',\n username: 'mike',\n password: 'xxx',\n type: 'mssql',\n database: 'db2',\n synchronize: true,\n entities: ['src/entity/**/*.ts'],\n migrations: ['src/migration/**/*.ts'],\n subscribers: ['src/subscriber/**/*.ts'],\n cli: {\n entitiesDir: 'src/entity',\n migrationsDir: 'src/migration',\n subscribersDir: 'src/subscriber',\n },\n })\n```\n\nWe do need to work with decorators because we also use `type-graphql` docrators in the class. The funny thing is that when the decorator for entity is left blank we see both tables created in both databases. So the credentials are correct.\n\nI found a similar issue here and requested help here.\n\nThank you for your help.\n\n========================================\n\nCode:\n```text\n// src/entity/User.ts\nimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'\n\n@Entity({database: 'db1'})\nexport class User {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column()\n mame: string\n}\n```\n\n```text\n// src/entity/Movie.ts\nimport { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'\n\n@Entity({database: 'db2'})\nexport class Movie {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column()\n title: string\n}\n```\n\n```text\n// src/index.ts\n await createConnection({\n name: 'connection1',\n host: 'SERVER1',\n username: 'bob',\n password: 'xxx',\n type: 'mssql',\n database: 'db1',\n synchronize: true,\n entities: ['src/entity/**/*.ts'],\n migrations: ['src/migration/**/*.ts'],\n subscribers: ['src/subscriber/**/*.ts'],\n cli: {\n entitiesDir: 'src/entity',\n migrationsDir: 'src/migration',\n subscribersDir: 'src/subscriber',\n },\n })\n\n await createConnection({\n name: 'connection2',\n host: 'SERVER2',\n username: 'mike',\n password: 'xxx',\n type: 'mssql',\n database: 'db2',\n synchronize: true,\n entities: ['src/entity/**/*.ts'],\n migrations: ['src/migration/**/*.ts'],\n subscribers: ['src/subscriber/**/*.ts'],\n cli: {\n entitiesDir: 'src/entity',\n migrationsDir: 'src/migration',\n subscribersDir: 'src/subscriber',\n },\n })\n```\n\n```text\n@Entity\n```\n\n```text\ntypeorm\n```\n\n```text\nSQL\n```\n\n```text\ntype-graphql\n```\n\n```js\n// src/index.ts\n await createConnections([\n {\n name: 'default',\n host: 'SERVER1',\n username: 'bob',\n password: 'kiwi',\n type: 'mssql',\n database: 'db1',\n ...\n \"synchronize\": true,\n \"entities\": [\"src/db1/entity/**/*.ts\"],\n },\n {\n name: 'connection2',\n host: 'SERVER2',\n username: 'Mike',\n password: 'carrot',\n type: 'mssql',\n database: 'db2',\n ...\n \"synchronize\": true,\n \"entities\": [\"src/db2/entity/**/*.ts\"],\n ])\n```\n\n```text\nimport { Fruit } from 'src/db1/entity/Fruit'\n fruits() {\n return Fruit.find()\n }\n```\n\n```text\nimport { getRepository } from 'typeorm'\nimport { Vegetable } from 'src/db2/entity/Vegetable'\n vegetables() {\n return async () => await getRepository(Vegetable).find()\n }\n```\n\n```text\nasync vegetables() {\n return await getRepository(vegetables, 'connection2').find()\n }\n```\n\n```text\nentities\n```\n\n```text\ndefault\n```\n\n```text\nsrc/db1/entity/Fruit.ts\n```\n\n```text\nsrc/db2/entity/Vegetables.ts\n```\n\n```text\n\"synchronize\": true\n```\n\n```text\ndefault\n```\n\n========================================\n\nComments:\n- Looks like both connections specify all entities, `entities: ['src/entity/**/*.ts']`. Not sure if that's why but it is suspicious.\n- You are correct, setting `entities: ['src/db1/entity/**/*.ts'],` on `connection1` and `entities: ['src/db2/entity/**/*.ts']` on `connection2` fixed this. If you post it as an answer I'll mark it as solved.\n- It was a complete guess. I've never even used TypeORM. Glad it worked!\n- Thx man! I've been staring myself blind at this as there's no real best practice documentation on how to really work with it when using multiple databases.","metadata":{"transformedAt":"2026-08-18T18:33:44.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":249,"estimatedTokens":1358}}354{"id":"stack-57155874","source":"stackoverflow","questionId":57155874,"title":"How to mock getMongoRepository in service nestjs","tags":["node.js","mongodb","typescript","nestjs","typeorm"],"text":"Title: How to mock getMongoRepository in service nestjs\nTags: node.js, mongodb, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI write unit test for my service in nestjs. In my function delete i use `getMongoRepository` to delete. But i stuck in write the unit test\n\nI've tried write the mock but it's not work\n\nmy service\n\n```\nasync delete(systemId: string): Promise {\n const systemRepository = getMongoRepository(Systems);\n return await systemRepository.deleteOne({ systemId });\n }\n```\n\nmy mock\n\n```\nimport { Mock } from './mock.type';\nimport { Repository, getMongoRepository } from 'typeorm';\n\n// @ts-ignore\nexport const mockRepositoryFactory: () => Mock> = jest.fn(\n () => ({\n save: jest.fn(Systems => Systems),\n delete: jest.fn(Systems => Systems),\n deleteOne: jest.fn(Systems => Systems),\n }),\n);\n```\n\nmy test\n\n```\nimport { ExternalSystemService } from '../external-system.service';\nimport { Systems } from '../entities/external-system.entity';\n\nmodule = await Test.createTestingModule({\n providers: [\n ExternalSystemService,\n {\n provide: getRepositoryToken(Systems),\n useFactory: mockRepositoryFactory,\n },\n ],\n }).compile();\n\n service = module.get(ExternalSystemService);\n mockRepository = module.get(getRepositoryToken(Systems));\n\n describe('delete', () => {\n it('should delete the system', async () => {\n mockRepository.delete.mockReturnValue(undefined);\n const deletedSystem = await service.delete(systemOne.systemId);\n\n expect(mockRepository.delete).toBeCalledWith({ systemId: systemOne.systemId });\n expect(deletedSystem).toBe(Object);\n });\n```\n\nI got this error\n\nExternalSystemService › delete › should not delete the system\n\n```\nConnectionNotFoundError: Connection \"default\" was not found.\n\n at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)\n at ConnectionManager.Object..ConnectionManager.get (connection/ConnectionManager.ts:40:19)\n at Object.getMongoRepository (index.ts:300:35)\n at Object. (external-system/tests/external-system.service.spec.ts:176:33)\n at external-system/tests/external-system.service.spec.ts:7:71\n at Object..__awaiter (external-system/tests/external-system.service.spec.ts:3:12)\n at Object. (external-system/tests/external-system.service.spec.ts:175:51)\n```\n\n========================================\n\nCode:\n```js\nasync delete(systemId: string): Promise<DeleteWriteOpResultObject> {\n const systemRepository = getMongoRepository(Systems);\n return await systemRepository.deleteOne({ systemId });\n }\n```\n\n```js\nimport { Mock } from './mock.type';\nimport { Repository, getMongoRepository } from 'typeorm';\n\n// @ts-ignore\nexport const mockRepositoryFactory: () => Mock<Repository<any>> = jest.fn(\n () => ({\n save: jest.fn(Systems => Systems),\n delete: jest.fn(Systems => Systems),\n deleteOne: jest.fn(Systems => Systems),\n }),\n);\n```\n\n```js\nimport { ExternalSystemService } from '../external-system.service';\nimport { Systems } from '../entities/external-system.entity';\n\nmodule = await Test.createTestingModule({\n providers: [\n ExternalSystemService,\n {\n provide: getRepositoryToken(Systems),\n useFactory: mockRepositoryFactory,\n },\n ],\n }).compile();\n\n service = module.get<ExternalSystemService>(ExternalSystemService);\n mockRepository = module.get(getRepositoryToken(Systems));\n\n describe('delete', () => {\n it('should delete the system', async () => {\n mockRepository.delete.mockReturnValue(undefined);\n const deletedSystem = await service.delete(systemOne.systemId);\n\n expect(mockRepository.delete).toBeCalledWith({ systemId: systemOne.systemId });\n expect(deletedSystem).toBe(Object);\n });\n```\n\n```text\nConnectionNotFoundError: Connection \"default\" was not found.\n\n at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)\n at ConnectionManager.Object.<anonymous>.ConnectionManager.get (connection/ConnectionManager.ts:40:19)\n at Object.getMongoRepository (index.ts:300:35)\n at Object.<anonymous> (external-system/tests/external-system.service.spec.ts:176:33)\n at external-system/tests/external-system.service.spec.ts:7:71\n at Object.<anonymous>.__awaiter (external-system/tests/external-system.service.spec.ts:3:12)\n at Object.<anonymous> (external-system/tests/external-system.service.spec.ts:175:51)\n```\n\n```text\ngetMongoRepository\n```\n\n```text\nconstructor(\n @InjectRepository(Systems)\n private readonly systemsRepository: MongoRepository<Systems>,\n) {}\n```\n\n```text\nasync delete(systemId: string): Promise<DeleteWriteOpResultObject> {\n return this.systemsRepository.deleteOne({ systemId });\n}\n```\n\n========================================\n\nComments:\n- But Repository cannot use deleteOne\n- Use the type `MongoRepository` instead: github.com/typeorm/typeorm/blob/master/src/repository/…","metadata":{"transformedAt":"2026-08-18T18:33:44.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":164,"estimatedTokens":1199}}355{"id":"stack-62470047","source":"stackoverflow","questionId":62470047,"title":"Typeorm Connection \"default\" was not found when connection is created in jest globalSetup","tags":["javascript","typescript","jestjs","typeorm","ts-jest"],"text":"Title: Typeorm Connection \"default\" was not found when connection is created in jest globalSetup\nTags: javascript, typescript, jestjs, typeorm, ts-jest\nSource: Stack Overflow\n\nQuestion:\nI'm having a similar problem as in #5164 and this question. Consider the following working test code:\n\n```\n// AccountResolver.test.ts\ndescribe('Account entity', () => {\n it('add account', async () => {\n await createConnections()\n const defaultConnection = getConnection('default')\n\n const actual = await callGraphql(\n `mutation {\n addAccount(options: {\n accountIdentifier: \"7csdcd8-8a5f-49c3-ab9a-0198d42dd253\"\n name: \"Jake, Bob (Braine-l’Alleud) JAM\"\n userName: \"Bob.Marley@contoso.com\"\n }) {\n accountIdentifier\n name\n userName\n }\n }`\n )\n expect(actual.data).toMatchObject({\n data: {\n addAccount: {\n accountIdentifier: '7csdcd8-8a5f-49c3-ab9a-0198d42dd253',\n name: 'Jake, Bob (Braine-l’Alleud) JAM',\n userName: 'Bob.Marley@contoso.com',\n },\n },\n })\n\n await defaultConnection.query(`DELETE FROM Account`)\n await defaultConnection.close()\n })\n})\n```\n\nThe code to create a connection and close it should be executed before all tests and after all tests are done, that's why we've added it to `globalSetup.ts` and `globalTeardown.ts`:\n\n```\n// globalSetup.ts\nrequire('ts-node/register')\nimport { createConnections } from 'typeorm'\n\nmodule.exports = async () => {\n // console.log('jest setup')\n await createConnections()\n}\n```\n\n```\n// globalTeardown.ts\nrequire('ts-node/register')\nimport { getConnection } from 'typeorm'\n\nmodule.exports = async () => {\n const defaultConnection = getConnection('default')\n await defaultConnection.close()\n}\n```\n\n```\n// AccountResolver.test.ts\ndescribe('Account entity', () => {\n it('add account', async () => {\n const defaultConnection = getConnection('default')\n await defaultConnection.query(`DELETE FROM Account`)\n\n const actual = await callGraphql(\n `mutation {\n addAccount(options: {\n accountIdentifier: \"7csdcd8-8a5f-49c3-ab9a-0198d42dd253\"\n name: \"Jake, Bob (Braine-l’Alleud) JAM\"\n userName: \"Bob.Marley@contoso.com\"\n }) {\n accountIdentifier\n name\n userName\n }\n }`\n )\n expect(actual.data).toMatchObject({\n data: {\n addAccount: {\n accountIdentifier: '7csdcd8-8a5f-49c3-ab9a-0198d42dd253',\n name: 'Jake, Bob (Braine-l’Alleud) JAM',\n userName: 'Bob.Marley@contoso.com',\n },\n },\n })\n })\n})\n```\n\nOmitting the line `require('ts-node/register')` from both files throws this error:\n\n T:\\Test\\src\\it-portal\\entity\\Account.ts:1\n import {\n ^^^^^^\n SyntaxError: Cannot use import statement outside a module\n\nKeeping the `require` line in throws:\n\n FAIL src/resolvers/AccountResolver.test.ts × add account (31 ms) ●\n Account entity › add account ConnectionNotFoundError: Connection\n \"default\" was not found.Account entity\n\n### Version\n\n```\n\"jest\": \"^26.0.1\",\n \"ts-jest\": \"^26.1.0\",\n \"ts-node-dev\": \"^1.0.0-pre.44\",\n \"typescript\": \"^3.9.5\"\n```\n\n### Config\n\n```\n// jest.config.js\nmodule.exports = {\n preset: 'ts-jest',\n globalSetup: './src/test-utils/config/globalSetup.ts',\n globalTeardown: './src/test-utils/config/globalTeardown.ts',\n setupFiles: ['./src/test-utils/config/setupFiles.ts'],\n moduleDirectories: ['node_modules', 'src'],\n globals: {\n 'ts-jest': {\n tsConfig: 'tsconfig.json',\n diagnostics: {\n warnOnly: true,\n },\n },\n },\n coverageThreshold: {\n global: {\n branches: 80,\n functions: 80,\n lines: 80,\n statements: 80,\n },\n },\n coverageReporters: ['json', 'lcov', 'text', 'clover'],\n}\n```\n\nThank you for pointing out my mistakes. As I'm new I tried googling but couldn't really find an answer if this is me not understanding the tool or a bug in the too. Found a similar issue here with a PR.\n\nIt seems like the tests are running in a fully isolated environment where they can't access the connection set up within `globalSetup`. \n\n### Workaround\n\nThe only workaround I have found thus far is to add the following code to every test file:\n\n```\nbeforeAll(async () => {\n await createConnections()\n})\n\nafterAll(async () => {\n const defaultConnection = getConnection('default')\n await defaultConnection.close()\n})\n```\n\n========================================\n\nCode:\n```js\n// AccountResolver.test.ts\ndescribe('Account entity', () => {\n it('add account', async () => {\n await createConnections()\n const defaultConnection = getConnection('default')\n\n const actual = await callGraphql(\n `mutation {\n addAccount(options: {\n accountIdentifier: \"7csdcd8-8a5f-49c3-ab9a-0198d42dd253\"\n name: \"Jake, Bob (Braine-l’Alleud) JAM\"\n userName: \"Bob.Marley@contoso.com\"\n }) {\n accountIdentifier\n name\n userName\n }\n }`\n )\n expect(actual.data).toMatchObject({\n data: {\n addAccount: {\n accountIdentifier: '7csdcd8-8a5f-49c3-ab9a-0198d42dd253',\n name: 'Jake, Bob (Braine-l’Alleud) JAM',\n userName: 'Bob.Marley@contoso.com',\n },\n },\n })\n\n await defaultConnection.query(`DELETE FROM Account`)\n await defaultConnection.close()\n })\n})\n```\n\n```js\n// globalSetup.ts\nrequire('ts-node/register')\nimport { createConnections } from 'typeorm'\n\nmodule.exports = async () => {\n // console.log('jest setup')\n await createConnections()\n}\n```\n\n```js\n// globalTeardown.ts\nrequire('ts-node/register')\nimport { getConnection } from 'typeorm'\n\nmodule.exports = async () => {\n const defaultConnection = getConnection('default')\n await defaultConnection.close()\n}\n```\n\n```js\n// AccountResolver.test.ts\ndescribe('Account entity', () => {\n it('add account', async () => {\n const defaultConnection = getConnection('default')\n await defaultConnection.query(`DELETE FROM Account`)\n\n const actual = await callGraphql(\n `mutation {\n addAccount(options: {\n accountIdentifier: \"7csdcd8-8a5f-49c3-ab9a-0198d42dd253\"\n name: \"Jake, Bob (Braine-l’Alleud) JAM\"\n userName: \"Bob.Marley@contoso.com\"\n }) {\n accountIdentifier\n name\n userName\n }\n }`\n )\n expect(actual.data).toMatchObject({\n data: {\n addAccount: {\n accountIdentifier: '7csdcd8-8a5f-49c3-ab9a-0198d42dd253',\n name: 'Jake, Bob (Braine-l’Alleud) JAM',\n userName: 'Bob.Marley@contoso.com',\n },\n },\n })\n })\n})\n```\n\n```text\n\"jest\": \"^26.0.1\",\n \"ts-jest\": \"^26.1.0\",\n \"ts-node-dev\": \"^1.0.0-pre.44\",\n \"typescript\": \"^3.9.5\"\n```\n\n```js\n// jest.config.js\nmodule.exports = {\n preset: 'ts-jest',\n globalSetup: './src/test-utils/config/globalSetup.ts',\n globalTeardown: './src/test-utils/config/globalTeardown.ts',\n setupFiles: ['./src/test-utils/config/setupFiles.ts'],\n moduleDirectories: ['node_modules', 'src'],\n globals: {\n 'ts-jest': {\n tsConfig: 'tsconfig.json',\n diagnostics: {\n warnOnly: true,\n },\n },\n },\n coverageThreshold: {\n global: {\n branches: 80,\n functions: 80,\n lines: 80,\n statements: 80,\n },\n },\n coverageReporters: ['json', 'lcov', 'text', 'clover'],\n}\n```\n\n```js\nbeforeAll(async () => {\n await createConnections()\n})\n\nafterAll(async () => {\n const defaultConnection = getConnection('default')\n await defaultConnection.close()\n})\n```\n\n```text\nglobalSetup.ts\n```\n\n```text\nglobalTeardown.ts\n```\n\n```text\nrequire('ts-node/register')\n```\n\n```text\nrequire\n```\n\n```text\nglobalSetup\n```\n\n```text\n// jest.setup.ts\n...\nbeforeAll(async () => {\n await createConnections()\n})\n\nafterAll(async () => {\n const defaultConnection = getConnection('default')\n await defaultConnection.close()\n})\n```\n\n```text\nrequire('ts-node/register')\n```\n\n```text\nglobalSetup\n```\n\n```text\nglobalTeardown\n```\n\n```text\nsetupFilesAfterEnv\n```\n\n```text\nrunInBand\n```\n\n```text\nsetupFilesAfterEnv\n```\n\n```text\nbeforeAll\n```\n\n```text\nafterAll\n```\n\n========================================\n\nComments:\n- This does indeed work. But as I understand it is executed before each test file and after each test file. Is there a way to have code executed only one before all test files and after all test files and still be able to consume the database connection in the test files?\n- Yes, it's executed for each file. As I mentioned, files run in different processes. There are limited ways in which Node processes can exchange data, DB connection object cannot be shared between multiple processes. This isn't specific to Jest. No, there's no way besides making tests run in a single process (e.g. import all test suites in one index.test.js file).\n- Thanks for the clarification. Accepted your answer.\n- @EstusFlask is is possible to create a seperate database for each test. I'm trying to use the in memory database from sqlite. But I keep getting error that default already exists\n- @Elias See the remark regarding `runInBand`. You can set up dbs in before/afterEach then.\n- @EstusFlask Yes, I'm using `--run-in-band` as a workaround for now, but it is significantly slower than running the tests in parallel. Is there no way to tell typeorm to create a whole new DB for each file?\n- @Elias Can't say, don't use typeorm much, the answer was primarily on Jest part. Consider asking a new question that reflects your case.\n- @EstusFlask I will do that when (and if...) I have time. Anyway, thank you for your time, have an upvote :)\n- @Elias FWIW, `getConnection` can be mocked per test file by means of Jest to replace `'default'` arg with `'default' + uid`, this is a general approach for dbs to allow concurrent tests, in-memory or not. But I'd expect some level of abstraction from ORM that could make this less hacky.","metadata":{"transformedAt":"2026-08-18T18:33:44.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":388,"estimatedTokens":2376}}356{"id":"stack-57570837","source":"stackoverflow","questionId":57570837,"title":"How to delete nested entities in TypeORM and Nest.js","tags":["nestjs","typeorm"],"text":"Title: How to delete nested entities in TypeORM and Nest.js\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have one-to-many relation:\n\n```\nclass User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToMany(() => Phone, phone => phone.user, {cascade: true})\n phones?: Phone[];\n}\n```\n\nAssume current data in database is following: user has two phone numbers:\n\n```\n{\n \"id\": 1,\n \"name\": \"Jhon\",\n \"phones\": [\n {\"id\": 1, \"phone\": \"123456\"},\n {\"id\": 2, \"phone\": \"567809\"}\n ]\n}\n```\n\nI build UI (web-interface) and from web-interface I want to have possibility to delete a phone number from user profile. So I do it and following POST request comes from UI: second phone number deleted\n\n```\n{\n \"id\": 1,\n \"name\": \"Jhon\",\n \"phones\": [\n {\"id\": 1, \"phone\": \"123456\"}\n ]\n}\n```\n\nHow to delete phone number id=2 from database?\nI use Nest CRUD module, as I understand from source code it just merges a new data from request with current data from database, so merging two phone numbers from database with the only phone number from request gives us array of tho phone numbers again and nothing deleted :frowning:\nI tried to do it manually and there are a lot of code!\n\n```\n@Override()\n async updateOne(\n @ParsedRequest() req: CrudRequest,\n @ParsedBody() dto: UpdateUserDto,\n @Param('id') id: number,\n ): Promise {\n\n // use standart Nest.js way to save new user data into database\n await this.service.updateOne(req, dto);\n\n // load fresh user data from database\n const user = await this.service.findOne(id);\n\n const phonesFromUi = dto.phones;\n const phonesToBeDeleted = [];\n // loop phone numbers from database - detect which to be deleted\n user.phones.forEach((phoneFromDb) => {\n const hasThisPhoneOnUi = phonesFromUi.find((phoneFromUi) => phoneFromUi.id === phoneFromDb.id);\n if (!hasThisPhoneOnUi) {\n // looks like this phone number was deleted on ui, so delete it from database too\n phonesToBeDeleted.push(phoneFromDb);\n }\n });\n // actually delete phone numbers from database\n await this.connection.getRepositoryFor(Phone).remove(phonesToBeDeleted);\n\n // reload fresh user data from database to get fresh list of phone numbers after delition some of them\n const user = await this.service.findOne(id);\n\n return user;\n }\n```\n\nIs there any way to do it via TypeORM build in functions or methods? How to delete some elements from nested array?\n\n========================================\n\nCode:\n```text\nclass User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToMany(() => Phone, phone => phone.user, {cascade: true})\n phones?: Phone[];\n}\n```\n\n```text\n{\n \"id\": 1,\n \"name\": \"Jhon\",\n \"phones\": [\n {\"id\": 1, \"phone\": \"123456\"},\n {\"id\": 2, \"phone\": \"567809\"}\n ]\n}\n```\n\n```text\n{\n \"id\": 1,\n \"name\": \"Jhon\",\n \"phones\": [\n {\"id\": 1, \"phone\": \"123456\"}\n ]\n}\n```\n\n```text\n@Override()\n async updateOne(\n @ParsedRequest() req: CrudRequest,\n @ParsedBody() dto: UpdateUserDto,\n @Param('id') id: number,\n ): Promise<Shipment> {\n\n // use standart Nest.js way to save new user data into database\n await this.service.updateOne(req, dto);\n\n // load fresh user data from database\n const user = await this.service.findOne(id);\n\n const phonesFromUi = dto.phones;\n const phonesToBeDeleted = [];\n // loop phone numbers from database - detect which to be deleted\n user.phones.forEach((phoneFromDb) => {\n const hasThisPhoneOnUi = phonesFromUi.find((phoneFromUi) => phoneFromUi.id === phoneFromDb.id);\n if (!hasThisPhoneOnUi) {\n // looks like this phone number was deleted on ui, so delete it from database too\n phonesToBeDeleted.push(phoneFromDb);\n }\n });\n // actually delete phone numbers from database\n await this.connection.getRepositoryFor(Phone).remove(phonesToBeDeleted);\n\n // reload fresh user data from database to get fresh list of phone numbers after delition some of them\n const user = await this.service.findOne(id);\n\n return user;\n }\n```\n\n```text\nconst phones = await this.phoneRepository.find({userId:1});\nconst toDeletePhones = phones.filter((element)) => {\n return updatePhones.indexOf(element) === -1;\n}\nthis.phoneRepository.remove(toDeletePhones);\n```\n\n========================================\n\nComments:\n- Thank you for response. I am actually do the same for now - manually filter array of phones and delete those are not in request from UI. So, at least now I know that there is no better way in TypeORM.\n- This would get even harder if your phone entity had a OneToMany relationship as well","metadata":{"transformedAt":"2026-08-18T18:33:44.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":169,"estimatedTokens":1139}}357{"id":"stack-59727358","source":"stackoverflow","questionId":59727358,"title":"Typeorm don't use ormconfig.json file","tags":["nestjs","typeorm"],"text":"Title: Typeorm don't use ormconfig.json file\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\ni'am configuring nestjs ormconfig.json but typeorm don't connect to mysql 8 database, it display this in cli\n\n```\n[Nest] 13324 - 2020-01-14 4:15:32 [NestFactory] Starting Nest application...\n[Nest] 13324 - 2020-01-14 4:15:32 [InstanceLoader] AppModule dependencies initialized +513ms\n[Nest] 13324 - 2020-01-14 4:15:32 [InstanceLoader] TypeOrmModule dependencies initialized +5ms\n[Nest] 13324 - 2020-01-14 4:15:36 [TypeOrmModule] Unable to connect to the database. Retrying (1)... +4061ms\nError: Cannot find module 'src/user/user.entity'\nRequire stack:\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\appel\\appel.entity.ts\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\platform\\PlatformTools.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\driver\\sqlserver\\SqlServerDriver.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\migration\\MigrationExecutor.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\connection\\Connection.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\connection\\ConnectionManager.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\common\\typeorm.utils.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\common\\typeorm.decorators.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\common\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\app.module.ts\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\main.ts\n at Function.Module._resolveFilename (internal/modules/cjs/loader.js:797:15)\n at Function.Module._load (internal/modules/cjs/loader.js:690:27)\n at Module.require (internal/modules/cjs/loader.js:852:19)\n at require (internal/modules/cjs/helpers.js:74:18)\n at Object. (C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\appel\\appel.entity.ts:3:1)\n at Module._compile (internal/modules/cjs/loader.js:959:30)\n at Module.m._compile (C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\ts-node\\src\\index.ts:806:23)\n at Module._extensions..js (internal/modules/cjs/loader.js:995:10)\n at Object.require.extensions. [as .ts] (C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\ts-node\\src\\index.ts:809:12)\n at Module.load (internal/modules/cjs/loader.js:815:32)\n```\n\nall entities are in src folder but the console still say the're not\n\nand this is my code\n\n```\napp.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot(),\n ],\n})\nexport class AppModule {}\n```\n\normconfig.json\n\n```\n{\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"admin\",\n \"password\": \"\",\n \"database\": \"kissing_db\",\n \"synchronize\": true,\n \"logging\": true,\n \"entities\": [\n \"src/**/*.entity.ts\",\n \"dist/**/*.entity.js\"\n ],\n \"migrationsTableName\": \"migration\",\n \"migrations\": [\n \"src/migration/*.ts\"\n ],\n \"cli\": {\n \"migrationsDir\": \"./src/migration\"\n },\n \"ssl\": false\n}\n```\n\nI don't post it with password for security reason hope you'll understand.\n\n========================================\n\nTop Answer:\nI think i've found a solution i've just create a `ormconfig.js` withouth `entities` field like this \n\n```\nmodule.exports = {\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"admin\",\n \"password\": \"\",\n \"database\": \"kissing_db\",\n \"synchronize\": true,\n \"logging\": true,\n};\n```\n\nand edit my `package.json` start scripts with `ts-node`, it seem like ts-node automatically find entity files.\n\n========================================\n\nCode:\n```text\n[Nest] 13324 - 2020-01-14 4:15:32 [NestFactory] Starting Nest application...\n[Nest] 13324 - 2020-01-14 4:15:32 [InstanceLoader] AppModule dependencies initialized +513ms\n[Nest] 13324 - 2020-01-14 4:15:32 [InstanceLoader] TypeOrmModule dependencies initialized +5ms\n[Nest] 13324 - 2020-01-14 4:15:36 [TypeOrmModule] Unable to connect to the database. Retrying (1)... +4061ms\nError: Cannot find module 'src/user/user.entity'\nRequire stack:\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\appel\\appel.entity.ts\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\platform\\PlatformTools.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\driver\\sqlserver\\SqlServerDriver.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\migration\\MigrationExecutor.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\connection\\Connection.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\connection\\ConnectionManager.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\typeorm\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\common\\typeorm.utils.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\common\\typeorm.decorators.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\common\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\dist\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\@nestjs\\typeorm\\index.js\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\app.module.ts\n- C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\main.ts\n at Function.Module._resolveFilename (internal/modules/cjs/loader.js:797:15)\n at Function.Module._load (internal/modules/cjs/loader.js:690:27)\n at Module.require (internal/modules/cjs/loader.js:852:19)\n at require (internal/modules/cjs/helpers.js:74:18)\n at Object.<anonymous> (C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\src\\appel\\appel.entity.ts:3:1)\n at Module._compile (internal/modules/cjs/loader.js:959:30)\n at Module.m._compile (C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\ts-node\\src\\index.ts:806:23)\n at Module._extensions..js (internal/modules/cjs/loader.js:995:10)\n at Object.require.extensions.<computed> [as .ts] (C:\\Users\\redwolf\\Labs\\projets-pro\\kissing-api\\node_modules\\ts-node\\src\\index.ts:809:12)\n at Module.load (internal/modules/cjs/loader.js:815:32)\n```\n\n```text\napp.module.ts\n\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot(),\n ],\n})\nexport class AppModule {}\n```\n\n```text\n{\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"admin\",\n \"password\": \"\",\n \"database\": \"kissing_db\",\n \"synchronize\": true,\n \"logging\": true,\n \"entities\": [\n \"src/**/*.entity.ts\",\n \"dist/**/*.entity.js\"\n ],\n \"migrationsTableName\": \"migration\",\n \"migrations\": [\n \"src/migration/*.ts\"\n ],\n \"cli\": {\n \"migrationsDir\": \"./src/migration\"\n },\n \"ssl\": false\n}\n```\n\n```text\n.ts\n```\n\n```text\nsrc\n```\n\n```text\n.js\n```\n\n```text\ndist\n```\n\n```text\ndist\n```\n\n```text\ndist\n```\n\n```text\ndist/src/user/user.entity\n```\n\n```text\nsrc/**/*.entity.ts\n```\n\n```text\normconfig.json\n```\n\n```text\nmodule.exports = {\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"admin\",\n \"password\": \"\",\n \"database\": \"kissing_db\",\n \"synchronize\": true,\n \"logging\": true,\n};\n```\n\n```text\normconfig.js\n```\n\n```text\nentities\n```\n\n```text\npackage.json\n```\n\n```text\nts-node\n```\n\n========================================\n\nComments:\n- but how do i do for development mode?\n- I've change remove the `src/**/*.entity.ts` from my `ormconfig.json` file but i still have this error in cli `Entity metadata for CaracteristiqueUser#photos was not found. Check if you specified a correct entity object and if it's connected in the connection options`\n- that's my package.json start scripts `\"scripts\": { \"start\": \"tsc-watch -r tsconfig-paths/register src/main.ts\", \"start:dev\": \"nodemon\", \"start:debug\": \"nest start --debug --watch\", \"start:prod\": \"node dist/main\", },`\n- With your `nodemon`, are you also compiling the ts or are you using `ts-node`?\n- i use a nodemon.json file `{ \"watch\": [\"src\"], \"ext\": \"ts\", \"ignore\": [\"src/**/*.spec.ts\"], \"exec\": \"node --inspect=127.0.0.1:9223 -r ts-node/register -- src/main.ts\", \"env\": {} }`\n- Ah, so it is using `ts-node`. I would suggest trying to move towards `tsc-watch` and `tsc` in general as it will make configurations easier. Otherwise, you would need to change the `ormconfig.json` each time you want to move between dev and prod. It's super annoying, I know. The other option is to use `ormconfig.js` instead and use `__dirname` to dynamically change between `dist` and `src`","metadata":{"transformedAt":"2026-08-18T18:33:44.711Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":256,"estimatedTokens":2229}}358{"id":"stack-51860432","source":"stackoverflow","questionId":51860432,"title":"TypeORM repository create not setting values","tags":["mysql","typescript","typeorm"],"text":"Title: TypeORM repository create not setting values\nTags: mysql, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nHere is my entity:\n\n```\n@Entity()\nexport class Game extends BaseEntity {\n\n @PrimaryGeneratedColumn({\n name: \"id\",\n })\n private _id: number;\n\n @Column({\n name: \"name\",\n type: \"varchar\",\n nullable: false,\n })\n private _name: string;\n\n get id(): number {\n return this._id;\n }\n\n set id(id: number) {\n this._id = id;\n }\n\n get name(): string {\n return this._name;\n }\n\n set name(name: string) {\n this._name = name;\n }\n}\n```\n\nAnd when I try to create a new Game, I want to use Repository API.\n\nSo what I do is:\n\n```\nimport { getRepository } from \"typeorm\";\nimport { Game } from \"../entities/game.entity\";\nimport { InsertGameConfig } from \"../interfaces/entities/game\";\n\npublic async insert(config: InsertGameConfig) {\n return await getRepository(Game).create(config).save();\n}\n```\n\nAnd calling insert function like this:\n\n```\nawait insert({\n name: \"test\",\n});\n```\n\nBut when I check mysql query log, I find this:\n\n```\nINSERT INTO `game`(`id`, `name`) VALUES (DEFAULT, DEFAULT)\n```\n\nHowever, if I create the instance and set every value like this:\n\n```\nconst game = new Game();\ngame.name = config.name;\nreturn await game.save();\n```\n\nAnd then it works correctly, so:\n\n```\nINSERT INTO `game`(`id`, `name`) VALUES (DEFAULT, \"test\")\n```\n\nFrom TypeOrm doc:\n\n`create` - Creates a new instance of User. Optionally accepts an object literal with user properties which will be written into newly created user object.\n\n```\nconst user = repository.create(); // same as const user = new User();\nconst user = repository.create({\n id: 1,\n firstName: \"Timber\",\n lastName: \"Saw\"\n}); // same as const user = new User(); user.firstName = \"Timber\"; user.lastName = \"Saw\";\n```\n\n### Note\n\nI tried setting class's attributes public, and then `create` works correctly, but when they're private and I use getters/setters, it does not work.\n\n========================================\n\nCode:\n```js\n@Entity()\nexport class Game extends BaseEntity {\n\n @PrimaryGeneratedColumn({\n name: \"id\",\n })\n private _id: number;\n\n @Column({\n name: \"name\",\n type: \"varchar\",\n nullable: false,\n })\n private _name: string;\n\n\n get id(): number {\n return this._id;\n }\n\n set id(id: number) {\n this._id = id;\n }\n\n get name(): string {\n return this._name;\n }\n\n set name(name: string) {\n this._name = name;\n }\n}\n```\n\n```js\nimport { getRepository } from \"typeorm\";\nimport { Game } from \"../entities/game.entity\";\nimport { InsertGameConfig } from \"../interfaces/entities/game\";\n\npublic async insert(config: InsertGameConfig) {\n return await getRepository(Game).create(config).save();\n}\n```\n\n```js\nawait insert({\n name: \"test\",\n});\n```\n\n```text\nINSERT INTO `game`(`id`, `name`) VALUES (DEFAULT, DEFAULT)\n```\n\n```js\nconst game = new Game();\ngame.name = config.name;\nreturn await game.save();\n```\n\n```text\nINSERT INTO `game`(`id`, `name`) VALUES (DEFAULT, \"test\")\n```\n\n```js\nconst user = repository.create(); // same as const user = new User();\nconst user = repository.create({\n id: 1,\n firstName: \"Timber\",\n lastName: \"Saw\"\n}); // same as const user = new User(); user.firstName = \"Timber\"; user.lastName = \"Saw\";\n```\n\n```text\ncreate\n```\n\n```text\ncreate\n```\n\n```text\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n firstName: string;\n\n @Column()\n lastName: string;\n}\n```\n\n```text\n_name\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":203,"estimatedTokens":879}}359{"id":"stack-74888503","source":"stackoverflow","questionId":74888503,"title":"How to add a typeorm in nuxt 3","tags":["orm","nuxt.js","typeorm","nuxt3.js"],"text":"Title: How to add a typeorm in nuxt 3\nTags: orm, nuxt.js, typeorm, nuxt3.js\nSource: Stack Overflow\n\nQuestion:\nI create an typeorm ESM project by running the command\n\nnpx typeorm init --name MyProject --database sqlite--module esm\n\nas explained on https://typeorm.io. Running the project, everything works fine.\nThen I create a nuxt 3 project: \"npx nuxi init nuxt-project\". Then I supplement the contents of the package.json and tsconfig.json files in the nuxt project with the appropriate typeorm values.\n\n```\npackage.json:\n {\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\",\n \"postinstall\": \"nuxt prepare\",\n \"start\": \"node --loader ts-node/esm src/index.ts\",\n \"typeorm\": \"typeorm-ts-node-esm\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^18.11.17\",\n \"nuxt\": \"3.0.0\",\n \"ts-node\": \"10.9.1\",\n \"typescript\": \"4.9.4\"\n },\n \"dependencies\": {\n \"@npmcli/fs\": \"^3.1.0\",\n \"reflect-metadata\": \"^0.1.13\",\n \"sqlite3\": \"^5.1.4\",\n \"typeorm\": \"^0.3.11\"\n }\n }\ntsconfig.json:\n {\n // https://nuxt.com/docs/guide/concepts/typescript\n \"extends\": \"./.nuxt/tsconfig.json\",\n \"compilerOptions\": {\n \"lib\": [\n \"es2021\"\n ],\n \"target\": \"es2021\",\n \"module\": \"es2022\",\n \"moduleResolution\": \"node\",\n \"allowSyntheticDefaultImports\": true,\n \"outDir\": \"./build\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"sourceMap\": true\n }\n }\n```\n\nI copy the entity, the configured data-source, the base and add code to the App.vue.\n\n```\n\nimport \"reflect-metadata\"\nimport { User } from \"./db/entity/User.js\"\nimport { AppDataSource } from \"./db/data-source\";\n\nAppDataSource.initialize().then(async () => {\n const user = new User()\n user.firstName = \"Timber\"\n user.lastName = \"Saw\"\n user.age = 25\n await AppDataSource.manager.save(user)\n const users = await AppDataSource.manager.find(User)\n console.log(\"Loaded users: \", users)\n}).catch(error => console.log(error))\n\n \n \n \n\n```\n\nI run a nuxt project and get an error:\n\n[nuxt] [request error] [unhandled] [500] Column type for\nUser#firstName is not defined and cannot be guessed. Make sure you\nhave turned on an \"emitDecoratorMetadata\": true option in\ntsconfig.json. Also make sure you have imported \"reflect-metadata\" on\ntop of the main entry file in your application (before any entity\nimported).If you are using JavaScript instead of TypeScript you must\nexplicitly provide a column type.\n\nJust in case, I add import reflect-metadata before the entity, but the error doesn't go away. I wonder if there is a good wizard who will guide me to the right path?\n\nBy the way, before that I tried to work with Sequelize, and also failed. It didn't fail on reflect-metadata, but:\n\n```\nCould not resolve \"pg-hstore\": const hstore = require(\"pg-hstore\")\n```\n\nAny orm will work for me (that allows working with oracle, so Prisma is unfortunately out of the question). Any advice or an example?\n\n========================================\n\nCode:\n```text\npackage.json:\n {\n \"private\": true,\n \"scripts\": {\n \"build\": \"nuxt build\",\n \"dev\": \"nuxt dev\",\n \"generate\": \"nuxt generate\",\n \"preview\": \"nuxt preview\",\n \"postinstall\": \"nuxt prepare\",\n \"start\": \"node --loader ts-node/esm src/index.ts\",\n \"typeorm\": \"typeorm-ts-node-esm\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^18.11.17\",\n \"nuxt\": \"3.0.0\",\n \"ts-node\": \"10.9.1\",\n \"typescript\": \"4.9.4\"\n },\n \"dependencies\": {\n \"@npmcli/fs\": \"^3.1.0\",\n \"reflect-metadata\": \"^0.1.13\",\n \"sqlite3\": \"^5.1.4\",\n \"typeorm\": \"^0.3.11\"\n }\n }\ntsconfig.json:\n {\n // https://nuxt.com/docs/guide/concepts/typescript\n \"extends\": \"./.nuxt/tsconfig.json\",\n \"compilerOptions\": {\n \"lib\": [\n \"es2021\"\n ],\n \"target\": \"es2021\",\n \"module\": \"es2022\",\n \"moduleResolution\": \"node\",\n \"allowSyntheticDefaultImports\": true,\n \"outDir\": \"./build\",\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"sourceMap\": true\n }\n }\n```\n\n```text\n<script setup lang=\"ts\">\nimport \"reflect-metadata\"\nimport { User } from \"./db/entity/User.js\"\nimport { AppDataSource } from \"./db/data-source\";\n\nAppDataSource.initialize().then(async () => {\n const user = new User()\n user.firstName = \"Timber\"\n user.lastName = \"Saw\"\n user.age = 25\n await AppDataSource.manager.save(user)\n const users = await AppDataSource.manager.find(User)\n console.log(\"Loaded users: \", users)\n}).catch(error => console.log(error))\n</script>\n<template>\n <div>\n <NuxtWelcome />\n </div>\n</template>\n```\n\n```text\nCould not resolve \"pg-hstore\": const hstore = require(\"pg-hstore\")\n```\n\n```text\n@Column('text',{nullable:true})\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.711Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":181,"estimatedTokens":1200}}360{"id":"stack-50822710","source":"stackoverflow","questionId":50822710,"title":"GraphQL query using TypeORM entity","tags":["javascript","graphql","typeorm"],"text":"Title: GraphQL query using TypeORM entity\nTags: javascript, graphql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am learning `graphql` and combining it with `typeorm`. I wrote a query with `graphql` and was wondering if this is the correct way to combine the `typeorm` entity and the `graphql` type for the same entity. Or is there a way for me to use the `typeorm` entity instead of the `graphql` type as the return value?\n\nThe `typeorm` entity and the `graphql` type have the exact same fields, essentially the are exactly the same. Just one is defined as a `graphql` type and the other is using the `typeorm` decorators.\n\nI am also not sure how this magic is returning a `TestType` from a `Promise`. Where `TestType` is a `graphql` type and `` is a `typeorm` entity.\n\n```\nimport {GraphQLFieldConfig, GraphQLNonNull} from \"graphql/type/definition\";\nimport {TestType} from \"../type/TestType\";\nimport {GraphQLID} from \"graphql\";\nimport {IGraphQLContext} from \"../IGraphQLContext\";\n\nexport const Test: GraphQLFieldConfig = {\n // notice the type to return here is the graphql type\n type: new GraphQLNonNull(TestType),\n description: \"A query for a test\",\n args: {\n id: {\n type: new GraphQLNonNull(GraphQLID),\n description: \"The ID for the desired test\"\n }\n },\n async resolve (source, args, context) {\n // getTest(...) here returns a promise where Test is a typeorm entity\n return context.db.testDAO.getTest(args.id);\n }\n};\n```\n\n========================================\n\nTop Answer:\nIf you’re looking for the magic of Prisma (autogenerated DB and schema), but also the flexibility of hosting your APIs and having access to the models and resolvers so that you can perform custom actions, you should check out Warthog. It’s a Node.js GraphQL API framework written in TypeScript where you set up resolvers and data models, and it auto-generates your entire schema with opinionated pagination, filtering, etc... similar to Prisma’s conventions. It’s not as feature-rich as Prisma, but it gives you a lot more control. You can check out warthog-starter, which will get you up and running quickly.\n\nDisclaimer: I’m the author of Warthog\n\n========================================\n\nCode:\n```text\nimport {GraphQLFieldConfig, GraphQLNonNull} from \"graphql/type/definition\";\nimport {TestType} from \"../type/TestType\";\nimport {GraphQLID} from \"graphql\";\nimport {IGraphQLContext} from \"../IGraphQLContext\";\n\nexport const Test: GraphQLFieldConfig<any, IGraphQLContext, any> = {\n // notice the type to return here is the graphql type\n type: new GraphQLNonNull(TestType),\n description: \"A query for a test\",\n args: {\n id: {\n type: new GraphQLNonNull(GraphQLID),\n description: \"The ID for the desired test\"\n }\n },\n async resolve (source, args, context) {\n // getTest(...) here returns a promise<Test> where Test is a typeorm entity\n return context.db.testDAO.getTest(args.id);\n }\n};\n```\n\n```text\ngraphql\n```\n\n```text\ntypeorm\n```\n\n```text\ngraphql\n```\n\n```text\ntypeorm\n```\n\n```text\ngraphql\n```\n\n```text\ntypeorm\n```\n\n```text\ngraphql\n```\n\n```text\ntypeorm\n```\n\n```text\ngraphql\n```\n\n```text\ngraphql\n```\n\n```text\ntypeorm\n```\n\n```text\nTestType\n```\n\n```text\nPromise<Test>\n```\n\n```text\nTestType\n```\n\n```text\ngraphql\n```\n\n```text\n<Test>\n```\n\n```text\ntypeorm\n```\n\n========================================\n\nComments:\n- Thanks, i will check it out.","metadata":{"transformedAt":"2026-08-18T18:33:44.711Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":139,"estimatedTokens":847}}361{"id":"stack-60448116","source":"stackoverflow","questionId":60448116,"title":"Foreign key constraint »FK_0e4022833a9efc062c01637e552« cannot be implemented - problem with composite primary key?","tags":["sql","postgresql","typeorm"],"text":"Title: Foreign key constraint »FK_0e4022833a9efc062c01637e552« cannot be implemented - problem with composite primary key?\nTags: sql, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using TypeORM and want to design my database with currently three entities. I created a repository for reproduction\n\nGithub reproduction repository\n\n**Update**\n\nI was able to reproduce it with only two small entities\n\nVery small reproduction repo\n\nmore information to this down below\n\nSo first of all I have a **module** entity. This one is a small one because it only stores some basic fields.\n\n```\n@Entity()\nexport class Module extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n public id: string;\n\n // some other fields without references\n}\n```\n\nNext I have a **graph** entity. This one is holding multiple **graphNodes**. So you can have multiple graphs and each one has its own graphNodes. The graph itself needs to know which graphNode is the first one in the graph. So I tried to setup a foreign key reference to the graphNode entity.\n\n- there can be multiple graphs\n\n- each graph has one graphNode as a starting node\n\n- there are multiple graphNodes per graph\n\n.\n\n```\n@Entity()\nexport class Graph extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n public id: string;\n\n @Column({ nullable: true })\n public startNodeId?: string;\n\n @ManyToOne(\n () => GraphNode,\n graphNode => graphNode.id,\n )\n @JoinColumn({ name: 'startNodeId' })\n public startNode: GraphNode;\n}\n```\n\nThe last entity is the **graphNodes** entity. Each graphNode represents a module in one graph. It also knows about its successors *successGraphNodeId* and *errorGraphNodeId*. It's important to node that this entity has a composite primary key because if you want to fetch a graphNode you have to pass in the graph id too. Basically these are the use cases\n\n- a graphNode represents one module\n\n- there are multiple graphNodes per graph\n\n- a graphNode can reference itself as a successor (success/error)\n\n- a graphNode successor can be null (success/error)\n\n- a graphNode successor must be a graphNode that already exists in **this** graph\n\n.\n\n```\n@Entity()\nexport class GraphNode extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n public id: string;\n\n @PrimaryColumn()\n public graphId: string; // composite key https://github.com/typeorm/typeorm/blob/master/sample/sample27-composite-primary-keys/entity/Post.ts\n\n @ManyToOne(\n () => Graph,\n graph => graph.id,\n )\n @JoinColumn({ name: 'graphId' })\n public graph: Graph;\n\n @Column()\n public moduleId: string;\n\n @ManyToOne(\n () => Module,\n module => module.id,\n )\n @JoinColumn({ name: 'moduleId' })\n public module: Module;\n\n @Column({ nullable: true })\n public successGraphNodeId?: string;\n\n @ManyToOne(\n () => GraphNode,\n graphNode => graphNode.id,\n )\n @JoinColumn({ name: 'successGraphNodeId' })\n public successGraphNode?: GraphNode;\n\n @Column({ nullable: true })\n public errorGraphNodeId?: string;\n\n @ManyToOne(\n () => GraphNode,\n graphNode => graphNode.id,\n )\n @JoinColumn({ name: 'errorGraphNodeId' })\n public errorGraphNode?: GraphNode;\n}\n```\n\nWhen running the application I'm unfortunately getting this error\n\n```\nQueryFailedError: Foreign key constraint »FK_0e4022833a9efc062c01637e552« cannot be implemented\n at new QueryFailedError (...\\references-reproduction\\node_modules\\typeorm\\error\\QueryFailedError.js:11:28)\n at Query.callback (...\\references-reproduction\\node_modules\\typeorm\\driver\\postgres\\PostgresQueryRunner.js:176:38)\n at Query.handleError (...\\references-reproduction\\node_modules\\pg\\lib\\query.js:145:17)\n at Connection.connectedErrorMessageHandler (...\\references-reproduction\\node_modules\\pg\\lib\\client.js:214:17)\n at Connection.emit (events.js:223:5)\n at Socket. (...\\references-reproduction\\node_modules\\pg\\lib\\connection.js:134:12)\n at Socket.emit (events.js:223:5)\n at addChunk (_stream_readable.js:309:12)\n at readableAddChunk (_stream_readable.js:290:11)\n at Socket.Readable.push (_stream_readable.js:224:10)\n```\n\nIt seems my entity design is not correct. Does someone know what's wrong or missing here? Please let me know if you need more information or if I should update my reproduction repository.\n\nThanks in advance\n\n**Update**\n\nI was able to reproduce it with two small entities. There only is a relation between a graph\n\n```\n@Entity()\nexport class Graph extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n public id: string;\n\n @Column({ nullable: true })\n public startNodeId?: string;\n\n @ManyToOne(\n () => Node,\n node => node.id,\n )\n @JoinColumn({ name: 'startNodeId' })\n public node: Node;\n}\n```\n\nand its nodes\n\n```\n@Entity()\nexport class Node extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n public id: string;\n\n @PrimaryColumn()\n public graphId: string;\n\n @ManyToOne(\n () => Graph,\n graph => graph.id,\n )\n @JoinColumn({ name: 'graphId' })\n public graph: Graph;\n}\n```\n\nAs mentioned before the problem seems to rely on the composite primary key. I don't want to convert the Node's graphId primary column to a basic column because this would be bad database design...\n\n========================================\n\nTop Answer:\nYou have two primary keys on GraphNode\n\n```\n@PrimaryGeneratedColumn('uuid')\npublic id: string;\n\n@PrimaryColumn()\npublic graphId: string;\n```\n\nthat's why the fk's on self-referenced success- and errorGraphNode won't work.\nRemove one PK and work with the other.\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class Module extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n public id: string;\n\n // some other fields without references\n}\n```\n\n```text\n@Entity()\nexport class Graph extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n public id: string;\n\n @Column({ nullable: true })\n public startNodeId?: string;\n\n @ManyToOne(\n () => GraphNode,\n graphNode => graphNode.id,\n )\n @JoinColumn({ name: 'startNodeId' })\n public startNode: GraphNode;\n}\n```\n\n```text\n@Entity()\nexport class GraphNode extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n public id: string;\n\n @PrimaryColumn()\n public graphId: string; // composite key https://github.com/typeorm/typeorm/blob/master/sample/sample27-composite-primary-keys/entity/Post.ts\n\n @ManyToOne(\n () => Graph,\n graph => graph.id,\n )\n @JoinColumn({ name: 'graphId' })\n public graph: Graph;\n\n @Column()\n public moduleId: string;\n\n @ManyToOne(\n () => Module,\n module => module.id,\n )\n @JoinColumn({ name: 'moduleId' })\n public module: Module;\n\n @Column({ nullable: true })\n public successGraphNodeId?: string;\n\n @ManyToOne(\n () => GraphNode,\n graphNode => graphNode.id,\n )\n @JoinColumn({ name: 'successGraphNodeId' })\n public successGraphNode?: GraphNode;\n\n @Column({ nullable: true })\n public errorGraphNodeId?: string;\n\n @ManyToOne(\n () => GraphNode,\n graphNode => graphNode.id,\n )\n @JoinColumn({ name: 'errorGraphNodeId' })\n public errorGraphNode?: GraphNode;\n}\n```\n\n```text\nQueryFailedError: Foreign key constraint »FK_0e4022833a9efc062c01637e552« cannot be implemented\n at new QueryFailedError (...\\references-reproduction\\node_modules\\typeorm\\error\\QueryFailedError.js:11:28)\n at Query.callback (...\\references-reproduction\\node_modules\\typeorm\\driver\\postgres\\PostgresQueryRunner.js:176:38)\n at Query.handleError (...\\references-reproduction\\node_modules\\pg\\lib\\query.js:145:17)\n at Connection.connectedErrorMessageHandler (...\\references-reproduction\\node_modules\\pg\\lib\\client.js:214:17)\n at Connection.emit (events.js:223:5)\n at Socket.<anonymous> (...\\references-reproduction\\node_modules\\pg\\lib\\connection.js:134:12)\n at Socket.emit (events.js:223:5)\n at addChunk (_stream_readable.js:309:12)\n at readableAddChunk (_stream_readable.js:290:11)\n at Socket.Readable.push (_stream_readable.js:224:10)\n```\n\n```text\n@Entity()\nexport class Graph extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n public id: string;\n\n @Column({ nullable: true })\n public startNodeId?: string;\n\n @ManyToOne(\n () => Node,\n node => node.id,\n )\n @JoinColumn({ name: 'startNodeId' })\n public node: Node;\n}\n```\n\n```text\n@Entity()\nexport class Node extends BaseEntity {\n @PrimaryGeneratedColumn('uuid')\n public id: string;\n\n @PrimaryColumn()\n public graphId: string;\n\n @ManyToOne(\n () => Graph,\n graph => graph.id,\n )\n @JoinColumn({ name: 'graphId' })\n public graph: Graph;\n}\n```\n\n```text\n@OneToMany(() => Node)\npublic nodes: Node[];\n```\n\n```text\nclass Graph {\n @OneToMany(() => Node, node => node.graph)\n public nodes: Node[];\n}\n\nclass Node {\n @ManyToOne(() => Graph, graph => graph.nodes)\n public graph: Graph;\n}\n```\n\n```text\nGraph\n```\n\n```text\nNode\n```\n\n```text\nManyToOne\n```\n\n```text\nGraph\n```\n\n```text\nOneToMany\n```\n\n```text\nNodes\n```\n\n```text\nManyToOne\n```\n\n```text\nJoinColumn\n```\n\n```text\n@PrimaryGeneratedColumn('uuid')\npublic id: string;\n\n@PrimaryColumn()\npublic graphId: string;\n```\n\n```text\n@ManyToOne(\n () => GraphNode,\n graphNode => graphNode.id,\n)\n```\n\n========================================\n\nComments:\n- I think this is not the problem. This is a composite key, TypeORM provides an example for those here github.com/typeorm/typeorm/blob/master/sample/…\n- Is there no way to reference a composite key?\n- I cloned the reproduction repository, deleted the database, created a new one and started the application. The error still remains ...","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":18,"totalLines":398,"estimatedTokens":2340}}362{"id":"stack-63954856","source":"stackoverflow","questionId":63954856,"title":"Typeorm performance issues with many relations","tags":["typeorm"],"text":"Title: Typeorm performance issues with many relations\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI have the following query:\n\n```\nconst foundAllOrders = await orderRepository.find({\n relations: ['inventoryItemType', 'inventoryItemType.quality',\n 'inventory', 'inventory.proveDocuments',\n 'inventory.proveDocuments.storage',\n 'account',\n 'inventory.labAttestationDocs',\n 'inventory.labAttestationDocs.storage',\n 'inventory.productPicture',\n 'inventory.productPicture.storage',\n 'inventory.inventoryItemSavedFields',\n 'inventory.inventoryItemSavedFields.proveDocuments',\n 'inventory.inventoryItemSavedFields.proveDocuments.storage',\n 'orderSavedFields'],\n});\n```\n\nExecution time is about 2sec.\n\nMaybe anyone know the way to optimize it?\n\n========================================\n\nCode:\n```text\nconst foundAllOrders = await orderRepository.find({\n relations: ['inventoryItemType', 'inventoryItemType.quality',\n 'inventory', 'inventory.proveDocuments',\n 'inventory.proveDocuments.storage',\n 'account',\n 'inventory.labAttestationDocs',\n 'inventory.labAttestationDocs.storage',\n 'inventory.productPicture',\n 'inventory.productPicture.storage',\n 'inventory.inventoryItemSavedFields',\n 'inventory.inventoryItemSavedFields.proveDocuments',\n 'inventory.inventoryItemSavedFields.proveDocuments.storage',\n 'orderSavedFields'],\n});\n```\n\n========================================\n\nComments:\n- Checkout this github issue: github.com/typeorm/typeorm/issues/3857. Did you try running that query as a raw query and not a generated one?","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":52,"estimatedTokens":389}}363{"id":"stack-65608223","source":"stackoverflow","questionId":65608223,"title":"the find function in typeorm return field with __underscores__","tags":["javascript","node.js","typescript","typeorm"],"text":"Title: the find function in typeorm return field with __underscores__\nTags: javascript, node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have entity in typeorm defined as:\n\n```\n@Entity('foo', { schema: 'dbo' })\nexport class Foo extends BaseEntity {\n\n ...\n @ManyToMany(() => Bar, (bar) => bar.some, { lazy: true })\n bars: Promise\n}\n```\n\nwhen I using `find` the results come out with underscore instead the normal object (`bars`):\n\n```\nconst results = await Foo.find({ relations: ['bars'] });\n\nresults.__bars__ // This is normal behavior of typeorm? if not how to fix that?\n\n========================================\n\nCode:\n```text\n@Entity('foo', { schema: 'dbo' })\nexport class Foo extends BaseEntity {\n\n ...\n @ManyToMany(() => Bar, (bar) => bar.some, { lazy: true })\n bars: Promise<Bar[]>\n}\n```\n\n```text\nconst results = await Foo.find({ relations: ['bars'] });\n\nresults.__bars__ // <--------- this should be just `bars`.\n```\n\n```text\nfind\n```\n\n```text\nbars\n```\n\n```text\n{ lazy: true }\n```\n\n```text\nbars\n```\n\n```text\nresults.bars\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":62,"estimatedTokens":263}}364{"id":"stack-61407959","source":"stackoverflow","questionId":61407959,"title":"Is there an elegant way using TypeORM to find one record in an array of OneToMany relation and assign it to another field in the entitiy?","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: Is there an elegant way using TypeORM to find one record in an array of OneToMany relation and assign it to another field in the entitiy?\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm looking for a way to implement a function, using NestJS and TypeORM, that will find in OneToMany array a specific element and assign that value to another field in the object.\nAnd most important: implemented in a single place in the code.\n\nFor example:\n\nThe Entity `profile` have an array of `photos`, one of the photos is the profile picture. \nI would like to find that photo in the array and assign it to `profilePicture` if exist, on every select query.\nis there a way in typeORM to implement that in a single place in the code?\n\n```\n@Entity('profile')\nexport class Profile extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @OneToMany(type => Photo, photo => photo.profile)\n photos?: Photo[];\n\n profilePicture?: Photo;\n}\n```\n\n========================================\n\nCode:\n```text\n@Entity('profile')\nexport class Profile extends BaseEntity {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @OneToMany(type => Photo, photo => photo.profile)\n photos?: Photo[];\n\n profilePicture?: Photo;\n}\n```\n\n```text\nprofile\n```\n\n```text\nphotos\n```\n\n```text\nprofilePicture\n```\n\n```text\nconst user = await createQueryBuilder(\"user\")\n.leftJoinAndMapOne(\"user.profilePhoto\", \"user.photos\", \"photo\", \"photo.isForProfile = TRUE\")\n.where(\"user.name = :name\", { name: \"Timber\" })\n.getOne();\n```\n\n```text\n@AfterLoad()\nprivate setProfile(): void {\n this.photos.forEach((photo) => {\n if (photo.isForProfile) {\n this.photo = value;\n }\n });\n}\n```\n\n========================================\n\nComments:\n- I edited the question, I'm looking for a solution to implement in a single place in the code. So that the assignment will happen on automatically on every select query like TypeORM's `transformer`. I'll use leftJoinAndMapOne if there's no solution as I am looking for.","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":79,"estimatedTokens":510}}365{"id":"stack-65407405","source":"stackoverflow","questionId":65407405,"title":"How to tell TypeORM to use different logger (pino in this case)?","tags":["node.js","logging","nestjs","typeorm","pinojs"],"text":"Title: How to tell TypeORM to use different logger (pino in this case)?\nTags: node.js, logging, nestjs, typeorm, pinojs\nSource: Stack Overflow\n\nQuestion:\nI am using NestJS, TypeORM, pino and nestjs-pino.\n\nI need pino for my logs to be in JSON format, so that Google Cloud Logging can parse the logs.\n\nHowever, TypeORM logs are not in JSON format. They still somehow use their own logger.\n\nIs it possible to tell TypeORM to use the nestjs-pino logger instead of its own?\n\n========================================\n\nComments:\n- Dead links.....","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":17,"estimatedTokens":135}}366{"id":"stack-67011436","source":"stackoverflow","questionId":67011436,"title":"Check if connection was successful using NestJs and Mysql","tags":["mysql","connection","nestjs","typeorm"],"text":"Title: Check if connection was successful using NestJs and Mysql\nTags: mysql, connection, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThe title speaks for itself, I am starting to learn NestJS and I would like to know if it's possible to, for example console.log or other way, know if a connection with a database was successful.\n\nWhen I run the `npm run start:dev` , everything compile fine but I am still not sure if I was able to connect to the database or not.\n\nNote: I am using `import { TypeOrmModule } from '@nestjs/typeorm/dist/typeorm.module';`\n\nEdit: If you have this line after running your app (on your terminal)\n\n```\nTypeOrmModule dependencies initialized\n```\n\nThat means that you have successfuly estabilished a conection with your database\n\n========================================\n\nTop Answer:\n```\nimport { Connection, createConnection, getConnectionManager } from 'typeorm';\n```\n\n```\nconst connectionManager = getConnectionManager();\n```\n\n```\ntry {\n getConnection(connection.name);\n } catch (error) {\n await createConnection(connection);\n }\n```\n\n========================================\n\nCode:\n```text\nTypeOrmModule dependencies initialized\n```\n\n```text\nnpm run start:dev\n```\n\n```text\nimport { TypeOrmModule } from '@nestjs/typeorm/dist/typeorm.module';\n```\n\n```text\n[Nest] 1274 - 04/09/2021, 11:24:52 AM [TypeOrmModule] Unable to connect to the database. Retrying (1)... +2042ms\nError: getaddrinfo ENOTFOUND localhast\n at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26)\n```\n\n```text\nUnable to connect to the database. Retrying (2)... +3009ms\nerror: password authentication failed for user \"mysql\"\n at Parser.parseErrorMessage (nest/node_modules/pg-protocol/src/parser.ts:357:11)\n at Parser.handlePacket (nest/node_modules/pg-protocol/src/parser.ts:186:21)\n at Parser.parse (nest/node_modules/pg-protocol/src/parser.ts:101:30)\n at Socket.<anonymous> (nest/node_modules/pg-protocol/src/index.ts:7:48)\n at Socket.emit (events.js:315:20)\n at Socket.EventEmitter.emit (domain.js:483:12)\n at addChunk (_stream_readable.js:295:12)\n at readableAddChunk (_stream_readable.js:271:9)\n at Socket.Readable.push (_stream_readable.js:212:10)\n at TCP.onStreamRead (internal/stream_base_commons.js:186:23)\n```\n\n```text\n[Nest] 1412 - 04/09/2021, 11:32:36 AM [TypeOrmModule] Unable to connect to the database. Retrying (2)... +3008ms\nerror: database \"example\" does not exist\n at Parser.parseErrorMessage (nest/node_modules/pg-protocol/src/parser.ts:357:11)\n at Parser.handlePacket (nest/node_modules/pg-protocol/src/parser.ts:186:21)\n at Parser.parse (nest/node_modules/pg-protocol/src/parser.ts:101:30)\n at Socket.<anonymous> (nest/node_modules/pg-protocol/src/index.ts:7:48)\n at Socket.emit (events.js:315:20)\n at Socket.EventEmitter.emit (domain.js:483:12)\n at addChunk (_stream_readable.js:295:12)\n at readableAddChunk (_stream_readable.js:271:9)\n at Socket.Readable.push (_stream_readable.js:212:10)\n at TCP.onStreamRead (internal/stream_base_commons.js:186:23)\n```\n\n```text\nimport { Connection, createConnection, getConnectionManager } from 'typeorm';\n```\n\n```text\nconst connectionManager = getConnectionManager();\n```\n\n```text\ntry {\n getConnection(connection.name);\n } catch (error) {\n await createConnection(connection);\n }\n```\n\n```text\nDB CONNECTION NAME ${this.dataSource.driver.database}\n```\n\n========================================\n\nComments:\n- What I know is that you can get the database connection obj by doing something like `constructor(private readonly connection: Connection)` (`Connection` class imported from `'typeorm'`), and check the `this.connection.isConnected` prop\n- That's what I tought, because I wasn't able to fetch data from my db, I wasn't sure. But manage to make it work, so everything is fine!","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":114,"estimatedTokens":959}}367{"id":"stack-73105792","source":"stackoverflow","questionId":73105792,"title":"NestJS/Typeorm ormconfig.json is not being used","tags":["nestjs","typeorm"],"text":"Title: NestJS/Typeorm ormconfig.json is not being used\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI was just using typeorm with NestJS as usual. But it installed version 8.1.4 instead of my previously used 8.0.3. With the newer version I couldn't get the ormconfig.json working. I then checked and installed 8.0.3 and it worked again.\nI have also tried with 9.0.0 and I couldn't get it to work their either.\nDoes somebody else has the same issue and maybe a temporary fix?\nThanks!\n\n========================================\n\nCode:\n```text\n@nestjs/typeorm@8.1.0\n```\n\n```text\ntypeorm@^.3.0\n```\n\n```text\normconfig.json\n```\n\n========================================\n\nComments:\n- how exacly does this work? I tried creating a ormconfig.js but it gives the same error, and I'm using \"@nestjs/typeorm\": \"^9.0.1\"\n- As TypeORM's docs say you need to have a default export of a datasource, if this is to be used with the typeorm CLI. Otherwise, pass the config to `TypeormModule.forRoot/forRootAsync()`","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":30,"estimatedTokens":252}}368{"id":"stack-58230517","source":"stackoverflow","questionId":58230517,"title":"Not able to update data in one-to-one relation in TypeORM","tags":["node.js","typeorm"],"text":"Title: Not able to update data in one-to-one relation in TypeORM\nTags: node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to update my `productDetails` table and `productMaster` table.\n\nHere is my relation:\n\nProductMaster.ts:\n\n```\n@OneToOne(type => ProductDetails, productDetails => productDetails.productMaster,{\n cascade: [\"insert\", \"update\"]\n})\nproductDetails: ProductDetails;\n```\n\nProductDetails.ts:\n\n```\n@OneToOne(type => ProductMaster, productMaster => productMaster.productDetails,{\n cascade: [\"insert\", \"update\"]\n})\n@JoinColumn({name: 'prd_id', referencedColumnName: 'prd_id'})\nproductMaster: ProductMaster;\n```\n\nNow I have to update my `productMaster` and `productDetails` using TypeORM relations.\n\nHere is what I tried:\n\n```\nproductMasterRepository\n .createQueryBuilder()\n .update()\n .set({\n prd_name : 'my Product Name'\n productDetails : {\n prd_brand : 'My Product Brand Name'\n }\n })\n .where(\"prd_id = :prd_id\", {prd_id: 1})\n .execute();\n```\n\nBut it doesn't update.\n\n========================================\n\nCode:\n```text\n@OneToOne(type => ProductDetails, productDetails => productDetails.productMaster,{\n cascade: [\"insert\", \"update\"]\n})\nproductDetails: ProductDetails;\n```\n\n```text\n@OneToOne(type => ProductMaster, productMaster => productMaster.productDetails,{\n cascade: [\"insert\", \"update\"]\n})\n@JoinColumn({name: 'prd_id', referencedColumnName: 'prd_id'})\nproductMaster: ProductMaster;\n```\n\n```text\nproductMasterRepository\n .createQueryBuilder()\n .update()\n .set({\n prd_name : 'my Product Name'\n productDetails : {\n prd_brand : 'My Product Brand Name'\n }\n })\n .where(\"prd_id = :prd_id\", {prd_id: 1})\n .execute();\n```\n\n```text\nproductDetails\n```\n\n```text\nproductMaster\n```\n\n```text\nproductMaster\n```\n\n```text\nproductDetails\n```\n\n```text\njoins\n```\n\n```text\nraw queries\n```\n\n========================================\n\nComments:\n- Hi Can you please complete model for both ProductMaster and ProductDetails","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":108,"estimatedTokens":506}}369{"id":"stack-69195175","source":"stackoverflow","questionId":69195175,"title":"TypeORM View Entity synchronization (creation) order problems","tags":["sql","node.js","typescript","orm","typeorm"],"text":"Title: TypeORM View Entity synchronization (creation) order problems\nTags: sql, node.js, typescript, orm, typeorm\nSource: Stack Overflow\n\nQuestion:\nUsing TypeORM, I'm trying to create ViewEntities that depend on each other, for example \"View B\" select from \"View A\". No matter what I do I can't get the ViewEntities to get created in the order of dependency. Sometimes \"View B\" is created first, and the synchronization process fails, because it can't find \"View A\", since it's not created yet.\n\nThe error:\n\nQueryFailedError: relation \"public.course_item_view\" does not exist\n\n**Solutions I have tried:**\n\n- Renaming the ViewEntity files (to check if the system uses ABC ordering on file names)\n\n- Renaming the ViewEntity classes (to check if the system uses ABC ordering on class names)\n\n- Renaming the ViewEntity's \"name\" property (to check if the system uses ABC ordering on the final SQL view names)\n\n- Reordering the ViewEntity class references in the \"entities: []\" array of the connection options\n\n- Reordering the ViewEntity class imports in the file where I declare the connection options\n\n- Removing/Adding the file again (to check if the system uses Creation Date based ordering)\n\n- Modifying the files (to check if the system uses Modification Date based ordering)\n\nAll of these failed. I cannot figure out how the system determines the order in which the view's are created.\nAny help would be GREATLY appreciated!!\n\n**Expected Behavior**\n\nThe view's should be created in an order that is either specified by a property inside the views, or the order should be resolved automatically from the SELECT statements (dependency array), or it should be based on the order in which I reference the ViewEntities in the \"entities: []\" array of the connection options, or any other solution would be perfect where one could determine the order in which the ViewEntities are created.\n\n**Actual Behavior**\n\nThe ViewEntites are created in an order that I honestly can't understand. Sometimes a dependent ViewEntity is created before the ViewEntitiy it depends on. This causes the synchronization to fail.\n\nFile name: \"CourseItemView\" which resolves to: \"course_item_view\"\n\n```\n@ViewEntity({\n expression: `\nSELECT\n \"uvcv\".\"userId\",\n \"uvcv\".\"courseId\",\n \"uvcv\".\"videoId\",\n CAST (null AS integer) AS \"examId\",\n \"uvcv\".\"isComplete\" AS \"isComplete\"\nFROM public.video_completed_view AS \"uvcv\"\nUNION ALL\nSELECT \n \"uecv\".\"userId\",\n \"uecv\".\"courseId\",\n CAST (null AS integer) AS \"videoId\",\n \"uecv\".\"examId\",\n \"uecv\".\"isCompleted\" AS \"isComplete\"\nFROM public.user_exam_completed_view AS \"uecv\"\n.\n.\n```\n\nFile name: \"CourseItemStateView\" which resolves to: \"course_item_state_view\"\nThis DEPENDS on the \"course_item_view\", as you can see in the SQL\n\n```\n@ViewEntity({\n expression: `\nSELECT \n \"course\".\"id\" AS \"courseId\",\n \"user\".\"id\" AS \"userId\",\n \"civ\".\"videoId\" AS \"videoId\",\n \"civ\".\"isComplete\" AS \"isVideoCompleted\",\n \"civ\".\"examId\" AS \"examId\",\n \"civ\".\"isComplete\" AS \"isExamCompleted\"\n \nFROM public.\"course\"\n\nLEFT JOIN public.\"user\" \nON 1 = 1\n\nLEFT JOIN public.course_item_view AS \"civ\" ------------------- HERE\nON \"civ\".\"courseId\" = \"course\".\"id\"\n AND \"civ\".\"userId\" = \"user\".\"id\"\n\nORDER BY \"civ\".\"videoId\",\"civ\".\"examId\"\n`\n})\n.\n.\n```\n\nMy connection options:\n\n```\nconst postgresOptions = {\n // properties, passwords etc...\n entities: [\n // entities....\n // ...\n // ...\n\n // views\n VideoCompletedView,\n UserExamCompletedView,\n UserExamAnswerSessionView,\n UserVideoMaxWatchedSecondsView,\n CourseItemView, --------------------------------HERE\n CourseItemStateView ---------------------------HERE\n ],\n } as ConnectionOptions;\n\ncreateConnection(postgresOptions )\n```\n\n**Steps to Reproduce**\n\nCreate ViewEntites that depend on each other\nYou will run into this issue, but is hard to say exactly why and when, this is the main problem.\n\n========================================\n\nCode:\n```text\n@ViewEntity({\n expression: `\nSELECT\n \"uvcv\".\"userId\",\n \"uvcv\".\"courseId\",\n \"uvcv\".\"videoId\",\n CAST (null AS integer) AS \"examId\",\n \"uvcv\".\"isComplete\" AS \"isComplete\"\nFROM public.video_completed_view AS \"uvcv\"\nUNION ALL\nSELECT \n \"uecv\".\"userId\",\n \"uecv\".\"courseId\",\n CAST (null AS integer) AS \"videoId\",\n \"uecv\".\"examId\",\n \"uecv\".\"isCompleted\" AS \"isComplete\"\nFROM public.user_exam_completed_view AS \"uecv\"\n.\n.\n```\n\n```text\n@ViewEntity({\n expression: `\nSELECT \n \"course\".\"id\" AS \"courseId\",\n \"user\".\"id\" AS \"userId\",\n \"civ\".\"videoId\" AS \"videoId\",\n \"civ\".\"isComplete\" AS \"isVideoCompleted\",\n \"civ\".\"examId\" AS \"examId\",\n \"civ\".\"isComplete\" AS \"isExamCompleted\"\n \nFROM public.\"course\"\n\nLEFT JOIN public.\"user\" \nON 1 = 1\n\nLEFT JOIN public.course_item_view AS \"civ\" ------------------- HERE\nON \"civ\".\"courseId\" = \"course\".\"id\"\n AND \"civ\".\"userId\" = \"user\".\"id\"\n\nORDER BY \"civ\".\"videoId\",\"civ\".\"examId\"\n`\n})\n.\n.\n```\n\n```text\nconst postgresOptions = {\n // properties, passwords etc...\n entities: [\n // entities....\n // ...\n // ...\n\n // views\n VideoCompletedView,\n UserExamCompletedView,\n UserExamAnswerSessionView,\n UserVideoMaxWatchedSecondsView,\n CourseItemView, --------------------------------HERE\n CourseItemStateView ---------------------------HERE\n ],\n } as ConnectionOptions;\n\ncreateConnection(postgresOptions )\n```\n\n```js\n@ViewEntity({\n expression: `SELECT * FROM 1`,\n dependsOn:[CourseItemView]\n})\n```\n\n```text\nViewEntity\n```\n\n```text\n@ViewEntity()\n```\n\n```text\nname\n```\n\n```text\ndatabase\n```\n\n```text\nschema\n```\n\n```text\nexpression\n```\n\n```text\ndependsOn\n```\n\n========================================\n\nComments:\n- Have you found a solution to this yet? I've got the same problem\n- Yes and no. It turns out TypeORM doesn't require you to specify a view creation script. What I've done, is to let TypeORM create the tables, but afterwards I'm connecting to Postgres by it's own client, and run all my view creation scripts. I've also done this with constraints, functions, indices, etc. It's even easier this way. Views that you create this way will still be queryable trugh TypeORM since it just uses their names when querying them. I used a const called dbSchema to store all the names of the views (and the creation order). Cheers","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":233,"estimatedTokens":1579}}370{"id":"stack-63565951","source":"stackoverflow","questionId":63565951,"title":"How to convert this oracle query to typeorm?","tags":["oracle-database","typescript","nestjs","typeorm"],"text":"Title: How to convert this oracle query to typeorm?\nTags: oracle-database, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI was building an application in NestJS and I need to get the date from the Oracle, but I don't know how convert this query:\n\n```\nSELECT TO_CHAR\n (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') \"NOW\"\n FROM DUAL;\n```\n\nIn a TypeORM query.\n\nCan you help me?\n\n========================================\n\nCode:\n```text\nSELECT TO_CHAR\n (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') \"NOW\"\n FROM DUAL;\n```\n\n```text\nawait getManager().query(`SELECT TO_CHAR(SYSDATE, 'MM-DD-YYYY HH24:MI:SS') \"NOW\" FROM DUAL`);\n```\n\n========================================\n\nComments:\n- The date must come from database?","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":34,"estimatedTokens":178}}371{"id":"stack-67270374","source":"stackoverflow","questionId":67270374,"title":"FInd with Array TypeOrm","tags":["typescript","typeorm"],"text":"Title: FInd with Array TypeOrm\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a Mysql DataBase, and I need to make a consult for return all the relations (I'm consulting to relation table) that matches with an array of Ids, so for that I'll receive the array by body and I'm planing do the next consult:\n\n```\nconst taskRelationFound = await getRepository(TaskRelation).findOne({ where: { ProjectId: ProjectIds , IsActive: true } });\n```\n\nit is into a async method, and the value of projectsIds is the next: `[ \"ccb79423-ed2b-4650-acb4-567c5e2a6cff\", \"68ff86e2-1c81-4487-bc7e-dddf1507f99e\" ]`\n\nProjectIds is an array with all the Id's where I'm looking for get the relations where each Id's matches with the ProjectId column, but I'm getting an error in the consult, and I'm not sure why\n\nMy entity works with this structure:\n\n```\nTaskRelationId: string;\n TaskId: string;\n UserId: string;\n ProjectId: string;\n IsResponsable: boolean;\n IsActive: boolean;\n```\n\nso how can I get all relations where ProjectId Matches with any ProjectId that I'm giving throw the array?\n\n========================================\n\nCode:\n```text\nconst taskRelationFound = await getRepository(TaskRelation).findOne({ where: { ProjectId: ProjectIds , IsActive: true } });\n```\n\n```text\nTaskRelationId: string;\n TaskId: string;\n UserId: string;\n ProjectId: string;\n IsResponsable: boolean;\n IsActive: boolean;\n```\n\n```text\n[ \"ccb79423-ed2b-4650-acb4-567c5e2a6cff\", \"68ff86e2-1c81-4487-bc7e-dddf1507f99e\" ]\n```\n\n```text\nimport { In } from 'typeorm';\nconst taskRelationFound = await getRepository(TaskRelation).findOne({ where: { ProjectId: In(ProjectIds) , IsActive: true } });\n```\n\n```text\nwhere\n```\n\n```text\nprojectIds\n```\n\n```text\nIn\n```\n\n========================================\n\nComments:\n- How to do this with query builder?\n- This GitHub issue link will be of help: github.com/typeorm/typeorm/issues/1239 ..It illustrates how to construct such queries using a query builder","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":70,"estimatedTokens":497}}372{"id":"stack-61221423","source":"stackoverflow","questionId":61221423,"title":"Column name as variable in typeorm querybuilder","tags":["typeorm"],"text":"Title: Column name as variable in typeorm querybuilder\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nThis is my original code which does not work.\n\n```\nthis.createQueryBuilder().where(\n 'LOWER(:column) LIKE LOWER(:name)',\n { column: 'itemName', name: `%${options.name}%` }\n );\n```\n\n```\n{ \"total\": 0, \"results\": [] }\n```\n\nI get no results from the above query but when I explicitly place the column name in the query like this, it works:\n\n```\nthis.createQueryBuilder().where(\n 'LOWER(itemName) LIKE LOWER(:name)',\n { name: `%${options.name}%` }\n );\n```\n\n```\n{\"total\":9, \"results\": [] }\n```\n\nIs it possible to use a variable in the column name for typeorm?\n\n========================================\n\nTop Answer:\nI was attempting something similar and stumbled a (not particularly well written) explanation here: https://www.tutorialspoint.com/typeorm/typeorm_query_builder.htm\n\nBasically, parameters are intended to prevent SQL injection, so while it's hard to see what's going on under the hood, I'm guessing that any string parameter automatically gets wrapped in single quotes in the final query so it can't be interpreted as anything other than a value.\n\nI even tried surrounding the parameter in single quotes, e.g.\n\n```\nthis.createQueryBuilder.where(\n '\":columnName\" = :value',\n { columnName: 'my_column': value: 'my_value' }\n);\n```\n\nNo good. This prevents parameter substitution entirely and gives the error `QueryFailedError: column \"$1\" does not exist` and seems to confirm that this feature is designed to prevent SQL injection.\n\nThis does leave template strings or string concatenation if you want to dynamically set column names, table names, etc. However, for the very same reason this safeguard exists in the first place, I would avoid doing that with user input.\n\n========================================\n\nCode:\n```text\nthis.createQueryBuilder().where(\n 'LOWER(:column) LIKE LOWER(:name)',\n { column: 'itemName', name: `%${options.name}%` }\n );\n```\n\n```text\n{ \"total\": 0, \"results\": [] }\n```\n\n```text\nthis.createQueryBuilder().where(\n 'LOWER(itemName) LIKE LOWER(:name)',\n { name: `%${options.name}%` }\n );\n```\n\n```text\n{\"total\":9, \"results\": [<RESULTS GOES HERE>] }\n```\n\n```text\nconst query = `{ \"${field}\": ${value} }`\nthis.createQueryBuilder.where( JSON.parse(query) )\n```\n\n```text\nthis.createQueryBuilder.where(\n '\":columnName\" = :value',\n { columnName: 'my_column': value: 'my_value' }\n);\n```\n\n```text\nQueryFailedError: column \"$1\" does not exist\n```\n\n========================================\n\nComments:\n- See Erics answer above. This risks a SQL injection if implemented this way.\n- What i did was to use string concatenation for the column name. But before that I validated the field variable if it is one of the valid strings I accept. for the value I used :name.","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":99,"estimatedTokens":705}}373{"id":"stack-68690562","source":"stackoverflow","questionId":68690562,"title":"How to exclude a column from typeorm entity and could be optional to get the column using Find method","tags":["node.js","typescript","postgresql","nestjs","typeorm"],"text":"Title: How to exclude a column from typeorm entity and could be optional to get the column using Find method\nTags: node.js, typescript, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\n```\nimport {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\";\n\n@Entity()\nexport class User {\n\n@PrimaryGeneratedColumn()\nid: number;\n\n@Column()\nname: string;\n\n@Column()\npassword: string;\n}\n```\n\ni dont want password here because i want to return to client:\n\n```\nconst user = await User.find({where:{name:\"test\"}})\n```\n\nwhen i want to modify password i need password:\n\n```\nconst user = await User.findOne({where:{name:\"test\"}})\nuser.password=\"password\";\nawait user.save()\n```\n\nis there any solution with Find,FindAndCount or even FindOne methods?\n\n**How should i do?**\n\n========================================\n\nTop Answer:\nIf you don't want to apply `select: false` to column in entity, then other option is to selectively type columns in find method only which you need\n\n```\nthis.ManagementUnitRepository.find({\n select: [\"id\", \"name\"]\n});\n```\n\n========================================\n\nCode:\n```text\nimport {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\";\n\n@Entity()\nexport class User {\n\n@PrimaryGeneratedColumn()\nid: number;\n\n@Column()\nname: string;\n\n@Column()\npassword: string;\n}\n```\n\n```text\nconst user = await User.find({where:{name:\"test\"}})\n```\n\n```text\nconst user = await User.findOne({where:{name:\"test\"}})\nuser.password=\"password\";\nawait user.save()\n```\n\n```text\nimport {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\";\n\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @Column({select: false})\n password: string;\n}\n```\n\n```text\n@Column\n```\n\n```text\nfind\n```\n\n```text\naddSelect\n```\n\n```text\nQueryBuilder\n```\n\n```text\nthis.ManagementUnitRepository.find({\n select: [\"id\", \"name\"]\n});\n```\n\n```text\nselect: false\n```\n\n========================================\n\nComments:\n- thanks for your answer. is it possible to pass args of Find Method to `createQueryBuilder().where(args)` ? because i wrote some functionality for sorting and filtering dynamicly Find Method's Options. @rahul-sharma\n- `find` and `QueryBuillder`'s `where` accept arguments in different manners. Passing the json you wrote for `find` in `createQueryBuilder().where` won't be possible, I guess. You can always write any query that you wrote using `find` with `QueryBuilder`. You'll have to specify the filters in `where` and sort using `sort` method.\n- yes completely correct ,i finally remove the password field from returned array in Find() by using RXJS's map operator technically after get all the fields from database\n- Thank you for your solution @Awais Nasir","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":131,"estimatedTokens":679}}374{"id":"stack-63024634","source":"stackoverflow","questionId":63024634,"title":"Typeorm .loadRelationCountAndMap returns zeros","tags":["sql-server","typeorm"],"text":"Title: Typeorm .loadRelationCountAndMap returns zeros\nTags: sql-server, typeorm\nSource: Stack Overflow\n\nQuestion:\nplease help.\nI am trying to execute the following typeorm query:\n\n```\nreturn await getRepository(Company)\n .createQueryBuilder(\"Company\")\n .leftJoinAndSelect(\"Company.plants\", \"Plant\")\n .leftJoinAndSelect(\"Plant.documents\", \"Document\")\n .leftJoinAndSelect(\"Plant.notes\", \"Note\")\n .loadRelationCountAndMap(\"Plant.documentsCount\", \"Plant.documents\")\n .loadRelationCountAndMap(\"Plant.notesCount\", \"Plant.notes\")\n .getMany();\n```\n\nThe idea was to select counts of documents and notes per each plant along with all plants for all companies.\n(Actually selecting notes and documents themselves was not needed, but i did it to prove that relations do work).\n\nAlso I have specified the placeholder variables to keep counts in Plant entity:\n\n```\n@OneToMany(() => Document, (document) => document.plant)\n documents: Document[];\n documentsCount: number;\n\n @OneToMany(() => Note, (note) => note.plant)\n notes: Note[];\n notesCount: number;\n```\n\nStrangely the returned Plant.documentsCount and Plant.notesCount are 0 (while the collections of documents and notes are not empty and are being selected).\n\nAnother strange thing is that i don't see in SQL querires any attempts to select these counts, thus i hope typeorm itself would do counting (since it has collections selected correctly).\n\nCould anybody please give some advise on how to select these counts?\n\n========================================\n\nTop Answer:\nUnfortunately, my project is forced to use `typeorm`. You can try the following:\n\n```\n@Expose()\nget documentsCount() {\n return this.documents.length;\n}\n\n@Expose()\nget notesCount() {\n return this.notes.length;\n}\n```\n\n**Discuss:**\nBut it looks like you're doing an API? You should return this array (documents & notes by `leftjoin`), and then, frontend can seft-caculate by use `.length`. Frontend is currently quite powerful, will the burden with the server.\n\n```\n.leftJoinAndSelect(\"Plant.documents\", \"Document\")\n.leftJoinAndSelect(\"Plant.notes\", \"Note\")\n```\n\n========================================\n\nCode:\n```text\nreturn await getRepository(Company)\n .createQueryBuilder(\"Company\")\n .leftJoinAndSelect(\"Company.plants\", \"Plant\")\n .leftJoinAndSelect(\"Plant.documents\", \"Document\")\n .leftJoinAndSelect(\"Plant.notes\", \"Note\")\n .loadRelationCountAndMap(\"Plant.documentsCount\", \"Plant.documents\")\n .loadRelationCountAndMap(\"Plant.notesCount\", \"Plant.notes\")\n .getMany();\n```\n\n```text\n@OneToMany(() => Document, (document) => document.plant)\n documents: Document[];\n documentsCount: number;\n\n @OneToMany(() => Note, (note) => note.plant)\n notes: Note[];\n notesCount: number;\n```\n\n```text\n.leftJoinAndSelect(\"Plant.documents\", \"Document\")\n .leftJoinAndSelect(\"Plant.notes\", \"Note\")\n```\n\n```text\n@AfterLoad()\n getDocumentsCount() {\n this.documentsCount = this.documents.length;\n delete this.documents;\n }\n\n @AfterLoad()\n getNotesCount() {\n this.notesCount = this.notes.length;\n delete this.notes;\n }\n```\n\n```text\n@Expose()\nget documentsCount() {\n return this.documents.length;\n}\n\n@Expose()\nget notesCount() {\n return this.notes.length;\n}\n```\n\n```text\n.leftJoinAndSelect(\"Plant.documents\", \"Document\")\n.leftJoinAndSelect(\"Plant.notes\", \"Note\")\n```\n\n```text\ntypeorm\n```\n\n```text\nleftjoin\n```\n\n```text\n.length\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":136,"estimatedTokens":843}}375{"id":"stack-70963321","source":"stackoverflow","questionId":70963321,"title":"TypeORM composite foreign key","tags":["mysql","typescript","nestjs","typeorm"],"text":"Title: TypeORM composite foreign key\nTags: mysql, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn a first class, the primary key is composite:\n\n```\n@Entity({\n name: 'ClassA',\n database: Constants.DATABASE_NAME,\n})\nexport class ClassA {\n @PrimaryColumn({\n name: 'Field1',\n type: 'varchar',\n length: 4,\n })\n field1: string;\n\n @PrimaryColumn({\n name: 'Field2',\n type: 'varchar',\n length: 2,\n })\n field2: string;\n\n @PrimaryColumn({\n name: 'Field3',\n type: 'integer',\n })\n field3: number;\n\n @OneToMany(() => ClassB, (classB) => classB.classA)\n classB: ClassB[];\n}\n```\n\nIn another class, the first class is used as a foreign key:\n\n```\n@Entity({\n name: 'ClassB',\n database: Constants.DATABASE_NAME,\n})\nexport class ClassB {\n\n ...\n\n @ManyToOne(() => ClassA, (classA) => classA.classB, {\n cascade: true,\n })\n @JoinColumn([\n { name: 'Field1', referencedColumnName: 'field1' },\n { name: 'Field2', referencedColumnName: 'field2' },\n { name: 'Field3', referencedColumnName: 'field3' },\n ])\n classA: ClassA;\n}\n```\n\nWhen I start NestJS using `nest start`, I get the error\n\n```\ncode: \"ER_FK_NO_INDEX_PARENT\"\nerrno: 1822\nsqlMessage: Failed to add the foreign key constraint. Missing index for constraint 'FK_1d19fe001872b5ee9ab545c18f8' in the referenced table 'ClassA'\nsqlState: \"HY000\n```\n\nI tried to alter the ClassA table and add indexes on each column of the primary key, and then an index of all columns of the primary key, but the error is still the same.\n\nIs this possible to manage this case with TypeORM?\n\nRelevant packages:\n\n- typeorm: `0.2.41`\n\n- @nestjs/core: `8.0.0`\n\n- @nestjs/typeorm: `8.0.3`\n\n- mysql: `2.18.1`\n\nDB: `MySQL v8.0` in a Docker container (`mysql:latest`)\n\nThank you.\n\n### Edit\n\nIt seems that the issue is that the table is created in more than one step with TypeORM. The table looks like this after the error message.\n\n```\nCREATE TABLE `ClassB` (\n `Date` datetime NOT NULL,\n `ClassAField1` varchar(4) NOT NULL,\n `ClassAField2` varchar(2) NOT NULL,\n `ClassAField3` int NOT NULL,\n PRIMARY KEY (`Date`,`ClassAField1`,`ClassAField2`,`ClassAField3`),\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci\n```\n\nThe error happens on the following query, where TypeORM tries to add the foreign key:\n\n```\nALTER TABLE `ClassB`\nADD CONSTRAINT `FK_479eaf779e0d5f0d0a83bb9e30d`\nFOREIGN KEY (`ClassAField1`, `ClassAField2`, `ClassAField3`)\nREFERENCES `LandPlots`(`Field1`,`Field2`,`Field3`) ON DELETE NO ACTION ON UPDATE NO ACTION\n```\n\nI made a few tests, and the following query works as intended:\n\n```\nCREATE TABLE `ClassB` (\n `Date` datetime NOT NULL,\n `ClassAField1` varchar(4) NOT NULL,\n `ClassAField2` varchar(2) NOT NULL,\n `ClassAField3` int NOT NULL,\n PRIMARY KEY (`Date`),\n KEY `FK_e6b2926df2c758d8d8810e4345a` (`ClassAField1`, `ClassAField2`, `ClassAField3`),\n CONSTRAINT `FK_e6b2926df2c758d8d8810e4345a`\n FOREIGN KEY (`ClassAField1`, `ClassAField2`, `ClassAField3`)\n REFERENCES `ClassA` (`Field1`, `Field2`, `Field3`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci\n```\n\nThe difference seems to be the line `KEY `FK_e6b2926df2c758d8d8810e4345a` (`ClassAField1`, `ClassAField2`, `ClassAField3`),`, which is missing from the generated SQL by TypeORM.\n\nFrom MySQL documentation, the `KEY` statement is synonymous to `INDEX`:\n\n```\nKEY | INDEX\n\nKEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.\n```\n\nSo I tried to add the `@Index` decorator to the column but it did not change anything. I added logging of all executed queries, and it seems that the `@Index` decorator is not executed, so, maybe the `@JoinColumn` decorator has priority over it? (Tried to sort decorators different ways just in case).\n\nThe only solution that I can think of with TypeORM would be to generate a hash or concatenation of all 3 primary keys, and make it the sole primary key. Two drawbacks: Data duplication and CPU usage when parsing entities before insertion.\n\nIf someone has a better suggestion I would like to hear it.\n\n### Edit 2 following questions from @RickJames\n\nUpdate statement:\n\n```\nUPDATE cb\nSET cb.SomeField = 'NewValue'\nFROM ClassB cb\nJOIN ClassA ca\nON cb.Field1 = ca.Field1\nAND cb.Field2 = ca.Field2\nAND cb.Field3 = ca.Field3\nWHERE ca.SomeOtherField LIKE '%partialvalue%'\nAND cb.otherPK = 1\n```\n\n========================================\n\nCode:\n```js\n@Entity({\n name: 'ClassA',\n database: Constants.DATABASE_NAME,\n})\nexport class ClassA {\n @PrimaryColumn({\n name: 'Field1',\n type: 'varchar',\n length: 4,\n })\n field1: string;\n\n @PrimaryColumn({\n name: 'Field2',\n type: 'varchar',\n length: 2,\n })\n field2: string;\n\n @PrimaryColumn({\n name: 'Field3',\n type: 'integer',\n })\n field3: number;\n\n @OneToMany(() => ClassB, (classB) => classB.classA)\n classB: ClassB[];\n}\n```\n\n```js\n@Entity({\n name: 'ClassB',\n database: Constants.DATABASE_NAME,\n})\nexport class ClassB {\n\n ...\n\n @ManyToOne(() => ClassA, (classA) => classA.classB, {\n cascade: true,\n })\n @JoinColumn([\n { name: 'Field1', referencedColumnName: 'field1' },\n { name: 'Field2', referencedColumnName: 'field2' },\n { name: 'Field3', referencedColumnName: 'field3' },\n ])\n classA: ClassA;\n}\n```\n\n```text\ncode: \"ER_FK_NO_INDEX_PARENT\"\nerrno: 1822\nsqlMessage: Failed to add the foreign key constraint. Missing index for constraint 'FK_1d19fe001872b5ee9ab545c18f8' in the referenced table 'ClassA'\nsqlState: \"HY000\n```\n\n```sql\nCREATE TABLE `ClassB` (\n `Date` datetime NOT NULL,\n `ClassAField1` varchar(4) NOT NULL,\n `ClassAField2` varchar(2) NOT NULL,\n `ClassAField3` int NOT NULL,\n PRIMARY KEY (`Date`,`ClassAField1`,`ClassAField2`,`ClassAField3`),\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci\n```\n\n```sql\nALTER TABLE `ClassB`\nADD CONSTRAINT `FK_479eaf779e0d5f0d0a83bb9e30d`\nFOREIGN KEY (`ClassAField1`, `ClassAField2`, `ClassAField3`)\nREFERENCES `LandPlots`(`Field1`,`Field2`,`Field3`) ON DELETE NO ACTION ON UPDATE NO ACTION\n```\n\n```sql\nCREATE TABLE `ClassB` (\n `Date` datetime NOT NULL,\n `ClassAField1` varchar(4) NOT NULL,\n `ClassAField2` varchar(2) NOT NULL,\n `ClassAField3` int NOT NULL,\n PRIMARY KEY (`Date`),\n KEY `FK_e6b2926df2c758d8d8810e4345a` (`ClassAField1`, `ClassAField2`, `ClassAField3`),\n CONSTRAINT `FK_e6b2926df2c758d8d8810e4345a`\n FOREIGN KEY (`ClassAField1`, `ClassAField2`, `ClassAField3`)\n REFERENCES `ClassA` (`Field1`, `Field2`, `Field3`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci\n```\n\n```text\nKEY | INDEX\n\nKEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.\n```\n\n```sql\nUPDATE cb\nSET cb.SomeField = 'NewValue'\nFROM ClassB cb\nJOIN ClassA ca\nON cb.Field1 = ca.Field1\nAND cb.Field2 = ca.Field2\nAND cb.Field3 = ca.Field3\nWHERE ca.SomeOtherField LIKE '%partialvalue%'\nAND cb.otherPK = 1\n```\n\n```text\nnest start\n```\n\n```text\n0.2.41\n```\n\n```text\n8.0.0\n```\n\n```text\n8.0.3\n```\n\n```text\n2.18.1\n```\n\n```text\nMySQL v8.0\n```\n\n```text\nmysql:latest\n```\n\n```text\nKEY `FK_e6b2926df2c758d8d8810e4345a` (`ClassAField1`, `ClassAField2`, `ClassAField3`),\n```\n\n```text\nKEY\n```\n\n```text\nINDEX\n```\n\n```text\n@Index\n```\n\n```text\n@Index\n```\n\n```text\n@JoinColumn\n```\n\n```text\ncb: INDEX(otherPK, Field1, Field2, Field3)\nca: INDEX(Field1, Field2, Field3, SomeOtherField)\n```\n\n========================================\n\nComments:\n- Before helping with *how to* index, I would like to critique *what to* index. Please provide sample `SELECTs/UPDATEs`/DELETEs` that you are hoping the add indexes for.\n- Hello @RickJames . The index ('KEY' in the 6th code snippet) on the composite foreign key because otherwise, from my tests, it finally works. But TypeORM does not seem to process both the primary key + \\@ManyToOne + \\@JoinColumn + \\@Index, it only processes the PK and tries afterward to alter the column into a composite FK, which does not work. I add an update statement but I'm not sure I understood your question well.\n- `` Too much of my time is spent trying to *work around* deficiencies in the products (ORMs, etc) that try to hide MySQL from the user. The users ends up having to understand *both* abstractions and write \"raw\" queries to get performance. ``\n- @RickJames I agree with you. For simple operations ORM are cool, and I wanted also to make the process cleaner by not manipulating SQL, but in the end a work that would have taken a few hours took days of my personal time.\n- Thank you for your help. It does not solve the TypeORM specific issue, but I think that in the end it's a TypeORM limit which cannot be solved using this ORM. I accept your answer because it'll be helpful optimizing queries on the database.","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":22,"totalLines":335,"estimatedTokens":2214}}376{"id":"stack-57408935","source":"stackoverflow","questionId":57408935,"title":"Not able to search through character varying[] array column","tags":["postgresql","nestjs","typeorm"],"text":"Title: Not able to search through character varying[] array column\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nMy postgres database table has a column location which is character `varying[]`. In my nestjs entity of the table I have following for the location column-\n\n```\n@Column(\"character varying\",{array:true})\n location: string[];\n```\n\nWhat I am trying to do is search the rows having passed parameter as locations.\nThis is the raw query which is giving me appropriate results-\n\n```\nselect * from blogs where language @> '{\"Spanish\",\"English\"}'\n```\n\nIn my nestjs service, how can I achieve the above query?\nI tried doing this-\n\n```\nreturn await this.blogsRepo.find({\n where: [\n {\n location: Any(body.locations)\n }\n ]\n})\n```\n\n`body.locations` is an array like this-\n\n```\nbody.locations = [\"Spanish\",\"English\"]\n```\n\nThe above typeorm solution gives me following error-\n\n 'could not find array type for data type character varying[]'\n\nWhat could be the possible solution for this? I will love a typeorm solution as I have kept raw query execution as my last option.\n\nThanks in advance,\n\n========================================\n\nTop Answer:\nYou could try this:\n\n```\nawait this.blogsRepo.find({\n where: `${body.locations} = ANY (location)`,\n});\n```\n\n========================================\n\nCode:\n```text\n@Column(\"character varying\",{array:true})\n location: string[];\n```\n\n```text\nselect * from blogs where language @> '{\"Spanish\",\"English\"}'\n```\n\n```text\nreturn await this.blogsRepo.find({\n where: [\n {\n location: Any(body.locations)\n }\n ]\n})\n```\n\n```text\nbody.locations = [\"Spanish\",\"English\"]\n```\n\n```text\nvarying[]\n```\n\n```text\nbody.locations\n```\n\n```text\n@>\n```\n\n```text\nRepository.query()\n```\n\n```text\nawait this.blogsRepo.find({\n where: `${body.locations} = ANY (location)`,\n});\n```\n\n```text\nimport { Raw } from 'typeorm';\n```\n\n```text\n{value1, value2, value3}\n```\n\n```text\nconst searchKey = 'value3'\n\nsampleRepo.find({\n where: {\n columnName: Raw((alias) => ` '${searchKey}' = ANY (${alias})`),\n }\n})\n```\n\n```text\n[{key1: 'value1', key2: 'value2'}, {key1: 'value21', key2: 'value22'}])\n```\n\n```text\nconst searchKey = 'value1'\n\nsampleRepo.find({\n where: {\n columnName: Raw((alias) => ` ${alias} @> '[{\"key1\": \"${searchKey}\"}]'`)\n }\n})\n```\n\n```text\nRaw\n```\n\n```text\ncharacter varying\n```\n\n```text\njsonb\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":148,"estimatedTokens":593}}377{"id":"stack-64242423","source":"stackoverflow","questionId":64242423,"title":"Typeorm. use only the date part while querying via date and exclude the timestamp part","tags":["node.js","orm","nestjs","typeorm"],"text":"Title: Typeorm. use only the date part while querying via date and exclude the timestamp part\nTags: node.js, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a use case where I have to retrieve a users record from the database via his date of birth.\nThe thing is that we have stored the date of birth of the user as datetime object which makes it very difficult to retrieve the users data, as we can not provide the exact date with timestamp.\n\nI tried looking for a functions support in typeorm using which I can just compare the provided date with only the date part of the birth date in database but did not find any reference anywhere.\n\n========================================\n\nTop Answer:\nDon't convert your column to a string. Here's how to do it with a date/datetime/timestamp.\n\n```\nimport { startOfDay, endOfDay } from 'date-fns';\nimport { Between, Equal } from \"typeorm\";\n//...\nlet findArgs = { \n where:{\n date: Between(startOfDay(webInputArgs.date).toISOString(), endOfDay(webInputArgs.date).toISOString()), \n userId: Equal(ctx.req.session.userId)\n }\n};\nreturn entity.find(findArgs) as any;\n```\n\n========================================\n\nCode:\n```text\ndate_of_birth::text LIKE '2011-01-%'\n```\n\n```text\nimport { startOfDay, endOfDay } from 'date-fns';\nimport { Between, Equal } from \"typeorm\";\n//...\nlet findArgs = { \n where:{\n date: Between(startOfDay(webInputArgs.date).toISOString(), endOfDay(webInputArgs.date).toISOString()), \n userId: Equal(ctx.req.session.userId)\n }\n};\nreturn entity.find(findArgs) as any;\n```\n\n```js\nconst usersBornToday = await getManager()\n .createQueryBuilder(User, \"user\")\n .where(`DATE_TRUNC('day', \"birthdatetime\") = :date`, {date: '2021-03-27'})\n .getMany()\n```\n\n```text\nDATE_TRUNC()\n```\n\n```text\nlet date = '2022-01-25'; //yyyy-mm-dd, for Regex validation - /\\d{4}\\-\\d{2}\\-\\d{2}/\ndate = `${date}%`;\nqueryResult.where('CONVERT(date_of_birth, char) LIKE :date', { date });\n```\n\n```text\nMySQL\n```\n\n```text\nCONVERT\n```\n\n```text\nTodo:only show today stock list\n const start = moment().startOf('day').toDate();\n const end = moment().endOf('day').toDate();\n \n const query=getManger()\n .createQueryBuilder(stocks, 'stocks')\n .andWhere('stocks.createdAt BETWEEN :start AND :end', { start, end })\n```\n\n========================================\n\nComments:\n- The question is not clear, on one hand you're saying: \"I have to retrieve a users record from the database via his date of birth\" which implies you have the DOB, but then you say you don't. What are you trying exactly to do? fetch all users that were born on a specific date? what if two users were born on the same date?\n- @NirAlfasi We have DOB in database in datetime format but when we are querying it from front end, we are just sending the dd-mm-yy. So the query is not filtering the records out. Anyhow, I found the solution and added it as an answer down below.\n- This cannot be the solution to the problem (the way it's stated) since, as I mentioned above, there may be multiple customers with the same DOB.\n- I dont think this is a good solution. Converting your date to string only to query it with a LIKE operation prevents you from running any date function like between or greater/less than operations.\n- This is exactly what I needed, Thanks! Also if anyone is looking to make the date param dynamic from a javascript Date object, you can use `.where(`DATE_TRUNC('day', \"birthdatetime\") = :date`, {date: yourDateObject.toISOString().split('T')[0] })`\n- I applied same logic but not working, `WHERE CONVERT(`transactions`.`created_at`, char) LIKE '2023-05-01'`, I am using mysql, typeorm\n- You should add an explanation along code snippet to make it clearer.","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":93,"estimatedTokens":931}}378{"id":"stack-70525343","source":"stackoverflow","questionId":70525343,"title":"Error TypeOrmModule Unable to connect to database with \"ETIMEDOUT\" or \"Handshake inactivity timeout\"","tags":["mysql","node.js","nestjs","typeorm","amazon-aurora"],"text":"Title: Error TypeOrmModule Unable to connect to database with \"ETIMEDOUT\" or \"Handshake inactivity timeout\"\nTags: mysql, node.js, nestjs, typeorm, amazon-aurora\nSource: Stack Overflow\n\nQuestion:\nI have a NestJS (v8.2.x) server application which I'm attempting to connect to an AWS Arura 3.x (MySQL 8.x protocol) using TypeORM (v0.2.41) and either the mysql (v2.18.1) or mysql2 (v2.3.3) driver. The application is running in a GitHub Codespace.\n\nWhen following the NestJS TypeORM documentation I'm getting the following errors:\n\nWith `mysql2` driver I'm getting:\n\n```\nERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)...\n Error: connect ETIMEDOUT\n ...\n```\n\nWith `mysql` driver I'm getting:\n\n```\n[TypeOrmModule] Error: Handshake inactivity timeout\n ...\n```\n\nThe code creating the connection looks as follows:\n\n```\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\n\nconst MYSQL_HOST = '....rds.amazonaws.com';\nconst MYSQL_USERNAME = '...';\nconst MYSQL_PASSWORD = '...';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mysql',\n host: MYSQL_HOST,\n port: 3306,\n username: MYSQL_USERNAME,\n password: MYSQL_PASSWORD,\n database: 'kitchen',\n // entities: [__dirname + '/**/*.entity{.ts,.js}'],\n debug: true,\n logging: true,\n }),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n### Initial Troubleshooting\n\nFirst, I validated the credentials I'm utilizing in the server application. I affirmed they worked correctly to connect via TablePlus. Thus, I ruled out \"invalid credentials\" and determined I had another issue.\n\nSecondly, when creating the AWS Arura database I'd selected **Yes** to **Public Access**:\n\nAmazon EC2 instances and devices outside the VPC can connect to your database. Choose one or more VPC security groups that specify which EC2 instances and devices inside the VPC can connect to the database.\n\n========================================\n\nTop Answer:\nFor anyone struggling with this error, this help me:\n\n```\nreturn mysql.createPool({\nuser: process.env.DB_USER, // e.g. 'my-db-user'\npassword: process.env.DB_PASS, // e.g. 'my-db-password'\ndatabase: process.env.DB_NAME, // e.g. 'my-database'\nsocketPath: process.env.INSTANCE_UNIX_SOCKET, // e.g. '/cloudsql/project:region:instance' --> I was missing socketPath\n// Specify additional properties here.\n...config,\n});\n```\n\nGoogle cloud docs\n\n========================================\n\nCode:\n```text\nERROR [TypeOrmModule] Unable to connect to the database. Retrying (1)...\n Error: connect ETIMEDOUT\n ...\n```\n\n```text\n[TypeOrmModule] Error: Handshake inactivity timeout\n ...\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\n\nconst MYSQL_HOST = '....rds.amazonaws.com';\nconst MYSQL_USERNAME = '...';\nconst MYSQL_PASSWORD = '...';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n type: 'mysql',\n host: MYSQL_HOST,\n port: 3306,\n username: MYSQL_USERNAME,\n password: MYSQL_PASSWORD,\n database: 'kitchen',\n // entities: [__dirname + '/**/*.entity{.ts,.js}'],\n debug: true,\n logging: true,\n }),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nmysql2\n```\n\n```text\nmysql\n```\n\n```text\nsource: \"0.0.0.0/0\"\n```\n\n```text\nsource: \"76.202.164.21/32\"\n```\n\n```text\nmysql2\n```\n\n```text\nmysql2\n```\n\n```text\nmysql\n```\n\n```text\nmysql\n```\n\n```text\nadd an inbound rule\n```\n\n```text\nAWS\n```\n\n```text\nadd an inbound rule\n```\n\n```text\nsource\n```\n\n```text\nsource: \"0.0.0.0/0\"\n```\n\n```text\nreturn mysql.createPool({\nuser: process.env.DB_USER, // e.g. 'my-db-user'\npassword: process.env.DB_PASS, // e.g. 'my-db-password'\ndatabase: process.env.DB_NAME, // e.g. 'my-database'\nsocketPath: process.env.INSTANCE_UNIX_SOCKET, // e.g. '/cloudsql/project:region:instance' --> I was missing socketPath\n// Specify additional properties here.\n...config,\n});\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.712Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":17,"totalLines":188,"estimatedTokens":1036}}379{"id":"stack-62747670","source":"stackoverflow","questionId":62747670,"title":"TypeORM CLI doesn't print any output when I run migration commands","tags":["node.js","typescript","database-migration","typeorm","ts-node"],"text":"Title: TypeORM CLI doesn't print any output when I run migration commands\nTags: node.js, typescript, database-migration, typeorm, ts-node\nSource: Stack Overflow\n\nQuestion:\nI created a TypeORM-based project intended for running migrations scripts only; I'm using the TypeORM CLI to `run`, `show` or `revert` them, but not getting any output when do it.\n\nThe only case in which I'm getting output is when I run `typeorm migration:create` or `npm run migration:create`, but in the other cases the output is the same as the following:\n\nThis is the content of my `package.json` so that you can see the `scripts` and dependencies I'm using:\n\n```\n{\n \"name\": \"bgt-data-import\",\n \"version\": \"0.0.1\",\n \"description\": \"BGT Data Import\",\n \"devDependencies\": {\n \"ts-node\": \"^8.10.2\",\n \"@types/node\": \"^9.6.5\",\n \"typescript\": \"^3.9.6\"\n },\n \"dependencies\": {\n \"aws-sdk\": \"^2.709.0\",\n \"axios\": \"^0.19.2\",\n \"dotenv\": \"^8.2.0\",\n \"npm\": \"^6.14.5\",\n \"pg\": \"^7.3.0\",\n \"reflect-metadata\": \"^0.1.10\",\n \"typeorm\": \"0.2.25\"\n },\n \"scripts\": {\n \"start\": \"ts-node src/index.ts\",\n \"typeorm\": \"node -r ts-node/register ./node_modules/typeorm/cli.js\",\n \"migration:generate\": \"npm run typeorm migration:generate --config ./ormconfig.json --name\",\n \"migration:run\": \"npm run typeorm migration:run --config ./ormconfig.json\",\n \"migration:revert\": \"npm run typeorm migration:revert --config ./ormconfig.json\",\n \"migration:show\": \"npm run typeorm migration:show --config ./ormconfig.json\"\n }\n}\n```\n\nAnd this one is the `ormconfig.json` content:\n\n```\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5656,\n \"username\": \"bgt_admin\",\n \"password\": \"jnppem\",\n \"database\": \"bgt\",\n \"synchronize\": false,\n \"logging\": true,\n \"maxQueryExecutionTime\": 100000,\n \"migrationsTableName\": \"data_import_migrations\",\n \"entities\": [\n \"src/entity/**/*.ts\"\n ],\n \"migrations\": [\n \"src/migration/**/*.ts\"\n ],\n \"subscribers\": [\n \"src/subscriber/**/*.ts\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\nSee the result of run `npm run migration:show`\n\nI have the following packages installed, both locally and globally:\n\n- TypeScript: `v3.9.6` (same version locally and globally)\n\n- ts-node: `v8.10.2` (same version locally and globally)\n\n- TypeORM: `v0.2.25` (same version locally and globally)\n\nAlso, I have NodeJS(`v14.5.0`) and NPM(`v6.14.5`) running on Ubuntu 18.04.\n\nWhat could be the reason why I'm not getting any output when I run `typeorm migration:[run|show|revert]`?\n\n========================================\n\nCode:\n```text\n{\n \"name\": \"bgt-data-import\",\n \"version\": \"0.0.1\",\n \"description\": \"BGT Data Import\",\n \"devDependencies\": {\n \"ts-node\": \"^8.10.2\",\n \"@types/node\": \"^9.6.5\",\n \"typescript\": \"^3.9.6\"\n },\n \"dependencies\": {\n \"aws-sdk\": \"^2.709.0\",\n \"axios\": \"^0.19.2\",\n \"dotenv\": \"^8.2.0\",\n \"npm\": \"^6.14.5\",\n \"pg\": \"^7.3.0\",\n \"reflect-metadata\": \"^0.1.10\",\n \"typeorm\": \"0.2.25\"\n },\n \"scripts\": {\n \"start\": \"ts-node src/index.ts\",\n \"typeorm\": \"node -r ts-node/register ./node_modules/typeorm/cli.js\",\n \"migration:generate\": \"npm run typeorm migration:generate --config ./ormconfig.json --name\",\n \"migration:run\": \"npm run typeorm migration:run --config ./ormconfig.json\",\n \"migration:revert\": \"npm run typeorm migration:revert --config ./ormconfig.json\",\n \"migration:show\": \"npm run typeorm migration:show --config ./ormconfig.json\"\n }\n}\n```\n\n```text\n{\n \"type\": \"postgres\",\n \"host\": \"localhost\",\n \"port\": 5656,\n \"username\": \"bgt_admin\",\n \"password\": \"jnppem\",\n \"database\": \"bgt\",\n \"synchronize\": false,\n \"logging\": true,\n \"maxQueryExecutionTime\": 100000,\n \"migrationsTableName\": \"data_import_migrations\",\n \"entities\": [\n \"src/entity/**/*.ts\"\n ],\n \"migrations\": [\n \"src/migration/**/*.ts\"\n ],\n \"subscribers\": [\n \"src/subscriber/**/*.ts\"\n ],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\n```text\nrun\n```\n\n```text\nshow\n```\n\n```text\nrevert\n```\n\n```text\ntypeorm migration:create\n```\n\n```text\nnpm run migration:create\n```\n\n```text\npackage.json\n```\n\n```text\nscripts\n```\n\n```text\normconfig.json\n```\n\n```text\nnpm run migration:show\n```\n\n```text\nv3.9.6\n```\n\n```text\nv8.10.2\n```\n\n```text\nv0.2.25\n```\n\n```text\nv14.5.0\n```\n\n```text\nv6.14.5\n```\n\n```text\ntypeorm migration:[run|show|revert]\n```\n\n========================================\n\nComments:\n- Please add `ormconfig.json` file as well.\n- @이준형 Added to the question\n- Thanks, I spent around 4hrs to figure out the issue.\n- Thank you, this is really helpful. In my case pg was correct version but the other person was using Node 14 vs Node 12 so it was just silently crashing somewhere\n- I'm glad this has helped you @AvinashMaurya","metadata":{"transformedAt":"2026-08-18T18:33:44.713Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":216,"estimatedTokens":1204}}380{"id":"stack-58961540","source":"stackoverflow","questionId":58961540,"title":"TypeOrm ViewEntity query is incorrect","tags":["mysql","typeorm"],"text":"Title: TypeOrm ViewEntity query is incorrect\nTags: mysql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am following the TypeOrm documents on how to create a ViewEntity so I can generate and query a custom view of my database. However at runtime, the SQL generated is not what I expected. The docs mention that the expression fed to `@ViewEntity()` can be a query. Here is my model:\n\n```\n@ViewEntity({\n expression: `\nSELECT t1.*, t1.CountOfA + t1.CountOfB AS Total\nFROM (\nSELECT q.CountOfA, q.CountOfB\nFROM questions q\n) AS t1`\n})\nexport class CountViewEntity {\n @ViewColumn()\n CountOfA: number;\n\n @ViewColumn()\n CountOfB: number;\n\n @ViewColumn()\n Total: number;\n}\n```\n\nSo I expected that the `Repository` would give me one record with CountOfA, CountOfB and Total for each row in my `questions` table. So I execute this:\n\n```\nthis.countViewRepository.find();\n```\n\nHowever the following SQL gets generated:\n\nSELECT `CountViewEntity`.`CountOfA` AS `CountViewEntity_CountOfA`, `CountViewEntity`.`CountOfB` AS `CountViewEntity_CountOfB`, `CountViewEntity`.`Total` AS `CountViewEntity_Total` FROM `count_view_entity` `CountViewEntity`\n\nAnd I get an error about table `count_view_entity` not existing.\n\nWhat am I doing wrong?\n\n### Edit:\n\nhmm... It's been a day since I put up a bounty and the answer/comment I received got me thinking: I'm a MySQL newbie as well as a TypeORM newbie so maybe I just overlooked an assumption the TypeORM docs make. I thought that the SQL generated would query actual DB tables, but I just reread the docs, in particular this part:\n\nView entity is a class that maps to a database view\n\nIt meant nothing to me before but I've just come across something called a Database View. Maybe I should create one first and then query against that? Feeling optimistic once again...\n\n========================================\n\nTop Answer:\nI encountered this same issue and found that it was a configuration problem so I wanted to what fixed it for me.\n\nI had \"synchronize: false\" on my DB connection because DB objects are typically handled outside of TypeORM but I wanted to define an expression for ViewEntities inside the code. But when you disable synchronize on the DB connection it doesn't allow you override it for specific entities. \n\nSo I changed my DB connection to allow synchronize and defined a constant that I use on all of my entities with \"synchronize: false\" then override it with \"synchronize: true\" on only the ViewEntity.\n\nconstants.ts:\n\n```\nexport const entityDefaults = { \n database: 'my_db', \n schema: 'my_schema', \n synchronize: false\n};\n```\n\nmy-entity.ts:\n\n```\nimport { Entity } from 'typeorm';\nimport { entityDefaults } from './constants';\n\n@Entity('my_entity', { ...entityDefaults })\nexport class MyEntity {\n...\n```\n\nmy-view-entity.ts:\n\n```\nimport { ViewEntity } from 'typeorm';\nimport { entityDefaults } from './constants';\n\n@ViewEntity('my_view_entity', { ...entityDefaults, synchronize: true, expression: 'SELECT ...' })\nexport class MyViewEntity {\n...\n```\n\nThen when you start the application you should see a message that the view was created.\n\n========================================\n\nCode:\n```text\n@ViewEntity({\n expression: `\nSELECT t1.*, t1.CountOfA + t1.CountOfB AS Total\nFROM (\nSELECT q.CountOfA, q.CountOfB\nFROM questions q\n) AS t1`\n})\nexport class CountViewEntity {\n @ViewColumn()\n CountOfA: number;\n\n @ViewColumn()\n CountOfB: number;\n\n @ViewColumn()\n Total: number;\n}\n```\n\n```text\nthis.countViewRepository.find();\n```\n\n```text\n@ViewEntity()\n```\n\n```text\nRepository<CountViewEntity>\n```\n\n```text\nquestions\n```\n\n```text\nCountViewEntity\n```\n\n```text\nCountOfA\n```\n\n```text\nCountViewEntity_CountOfA\n```\n\n```text\nCountViewEntity\n```\n\n```text\nCountOfB\n```\n\n```text\nCountViewEntity_CountOfB\n```\n\n```text\nCountViewEntity\n```\n\n```text\nTotal\n```\n\n```text\nCountViewEntity_Total\n```\n\n```text\ncount_view_entity\n```\n\n```text\nCountViewEntity\n```\n\n```text\ncount_view_entity\n```\n\n```text\n@ViewEntity({\n expression: `\n SELECT t1.*, t1.CountOfA + t1.CountOfB AS Total\n FROM (\n SELECT q.CountOfA, q.CountOfB\n FROM questions q\n ) AS t1`\n })\n\nexport class CountViewEntity {\n\n @ViewColumn()\n CountOfA: number;\n\n @ViewColumn()\n CountOfB: number;\n\n @ViewColumn()\n Total: number;\n}\n```\n\n```text\n@ViewEntity({\n expression: `\n SELECT \"t1\".\"CountOfA\" AS \"CountOfA\", \"t1\".\"CountOfB\" AS \"CountOfB\",\n \"t1\".\"CountOfA\" + \"t1\".\"CountOfB\" AS \"Total\"\n FROM \"questions\" \"t1\"\n `\n })\n```\n\n```text\n@ViewEntity({ \n expression: (connection: Connection) => connection.createQueryBuilder()\n .select(\"t1.CountOfA\", \"CountOfA\")\n .addSelect(\"t1.CountOfB\", \"CountOfB\")\n .addSelect(\"t1.CountOfA\" + \"t1.CountOfB\", \"Total\")\n .from(questions, \"t1\")\n})\n```\n\n```text\n@ViewEntity()\n```\n\n```text\nTypeORM\n```\n\n```text\ncount_view_entity not existing\n```\n\n```text\n@ViewEntity()\n```\n\n```text\nname\n```\n\n```text\ndatabase\n```\n\n```text\nschema\n```\n\n```text\nexpression\n```\n\n```text\nexpression\n```\n\n```text\nSub Query\n```\n\n```text\nQueryBuilder\n```\n\n```text\nexport const entityDefaults = { \n database: 'my_db', \n schema: 'my_schema', \n synchronize: false\n};\n```\n\n```text\nimport { Entity } from 'typeorm';\nimport { entityDefaults } from './constants';\n\n@Entity('my_entity', { ...entityDefaults })\nexport class MyEntity {\n...\n```\n\n```text\nimport { ViewEntity } from 'typeorm';\nimport { entityDefaults } from './constants';\n\n@ViewEntity('my_view_entity', { ...entityDefaults, synchronize: true, expression: 'SELECT ...' })\nexport class MyViewEntity {\n...\n```\n\n========================================\n\nComments:\n- Perhaps `CountViewEntity`, not `count_view_entity?\n- Don't think I get your suggestion: `count_view_entity` is generated dynamically by TypeORM when it makes the SQL query; it's not something I input anywhere.\n- Thanks for your suggestions; all 3 of them give me the same result as I see in my original post; the resulting SQL tries to query a table called `count_view_entity` which doesn't exist. The actual query I want to run is quite a bit more complicated than what I posted; that's why it has a subquery, and also why I didn't use query builder\n- Your answer did get me thinking though, and I've posted an update to my original Q\n- I can't credit your answer as is because it didn't solve my problem, but you got me thinking about the right things and I eventually got there. I would be happy to give you the bounty if you revised your answer to one that actually solves my problem. Basically I had to move my SQL to a database view (i looked up the code to create a view), and then inside the `@ViewEntity()` config, set the view name and change the query to just `SELECT *`\n- @BeetleJuice Are you facing issues again? Probably it should solve your problem if not post me the error.\n- Hi Vignesh; no I fixed my issue; I was writing to tell you how I fixed it so you can adjust your answer to explain the fix and get the bounty. Basically your answer tells me to adjust the `expression` argument but the problem was that I needed to first create a database view on the MySQL server, and then query against that with the expression: `SELECT *`\n- @BeetleJuice Happy that your issue resolved. Obviously, you must create the database views first before calling it from `TypeORM`, which cause the error `count_view_entity not existing`. I have updated my answer as per your suggestion. If is is not right, can you update my answer.","metadata":{"transformedAt":"2026-08-18T18:33:44.713Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":34,"totalLines":305,"estimatedTokens":1882}}381{"id":"stack-71891420","source":"stackoverflow","questionId":71891420,"title":"NestJS/TypeORM: Cannot set property metadata of # which has only a getter","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: NestJS/TypeORM: Cannot set property metadata of # which has only a getter\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI try to run my nestjstutorial app, the below error is showing. My backend is connected to a PostgreSQL db.\n\nTypeError: Cannot set property metadata of # which has only a getter\nat EntityManager.getCustomRepository (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\src\\entity-manager\\EntityManager.ts:1404:59)\nat DataSource.getCustomRepository (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\src\\data-source\\DataSource.ts:465:29)\nat InstanceWrapper.useFactory [as metatype] (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\node_modules@nestjs\\typeorm\\dist\\typeorm.providers.js:13:35)\nat Injector.instantiateClass (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\node_modules@nestjs\\core\\injector\\injector.js:333:55)\nat callback (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\node_modules@nestjs\\core\\injector\\injector.js:48:41)\nat processTicksAndRejections (node:internal/process/task_queues:96:5)\nat Injector.resolveConstructorParams (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\node_modules@nestjs\\core\\injector\\injector.js:122:24)\nat Injector.loadInstance (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\node_modules@nestjs\\core\\injector\\injector.js:52:9)\nat Injector.loadProvider (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\node_modules@nestjs\\core\\injector\\injector.js:74:9)\nat Injector.lookupComponentInImports (D:\\Ganesh\\MyDrive\\nestjs\\nestjs_tutorial\\nestjsturorial\\node_modules@nestjs\\core\\injector\\injector.js:265:17)\n\nMy code looks like this:\n\n**app.module**\n\n```\nimport { Module } from '@nestjs/common';\n import { AppController } from './app.controller';\n import { AppService } from './app.service';\n import { UserController } from './user/user.controller';\n import { UserModule } from './user/user.module';\n import { UserService } from './user/user.services';\n import { QuizModule } from './modules/quiz/quiz.module';\n //import { QuizController } from './modules/quiz/quiz.controller';\n //import { QuizService } from './modules/quiz/quiz.services';\n import { TypeOrmModule } from '@nestjs/typeorm';\n import { typeOrmConfig } from './config/typeorm.config';\n //import { QuizRepository } from './modules/quiz/quiz.repository';\n \n @Module({\n imports: [UserModule, QuizModule, TypeOrmModule.forRoot(typeOrmConfig)],\n controllers: [AppController],\n providers: [AppService],\n })\n export class AppModule {}\n```\n\n**quiz.controller**\n\n```\nimport {\n Body,\n Controller,\n Get,\n HttpCode,\n Post,\n UsePipes,\n ValidationPipe,\n } from '@nestjs/common';\n import { QuizService } from './quiz.services';\n import { CreateQuizDto } from '../dto/CreateQuiz.dto';\n \n @Controller('quiz')\n export class QuizController {\n constructor(private readonly quizService: QuizService) {}\n \n @Get('/')\n getAllQuiz() {\n return this.quizService.getAllQuiz();\n }\n \n @Post('/create')\n @HttpCode(200)\n @UsePipes(ValidationPipe)\n async createQuiz(@Body() quizData: CreateQuizDto) {\n return await this.quizService.createNewQuiz(quizData);\n }\n }\n```\n\n**quiz.services**\n\n```\nimport { Injectable } from '@nestjs/common';\n import { InjectRepository } from '@nestjs/typeorm';\n import { QuizRepository } from './quiz.repository';\n import { CreateQuizDto } from '../dto/CreateQuiz.dto';\n \n @Injectable()\n export class QuizService {\n constructor(\n @InjectRepository(QuizRepository) private quizRepository: QuizRepository,\n ) {}\n \n getAllQuiz() {\n return [1, 2, 'from service', 3];\n }\n async createNewQuiz(quiz: CreateQuizDto) {\n return await this.quizRepository.save(quiz);\n }\n }\n```\n\n**quiz.module**\n\n```\nimport { Module } from '@nestjs/common';\n import { TypeOrmModule } from '@nestjs/typeorm';\n import { QuizController } from './quiz.controller';\n import { QuizService } from './quiz.services';\n import { QuizRepository } from './quiz.repository';\n \n @Module({\n controllers: [QuizController],\n imports: [TypeOrmModule.forFeature([QuizRepository])],\n providers: [QuizService],\n })\n export class QuizModule {}\n```\n\n**quiz.repository**\n\n```\nimport { EntityRepository, Repository } from 'typeorm';\n import { Quiz } from './quiz.entity';\n \n @EntityRepository(Quiz)\n export class QuizRepository extends Repository {\n // means Quiz module\n }\n```\n\n**typeorm.config**\n\n```\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\n export const typeOrmConfig: TypeOrmModuleOptions = {\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: '123456',\n database: 'quiz',\n entities: [__dirname + '/../**/*.entity{.ts,.js}'],\n synchronize: true,\n };\n```\n\n**dto**\n\n```\nimport { isNotEmpty, IsNotEmpty, Length } from 'class-validator';\n\nexport class CreateQuizDto {\n @IsNotEmpty({ message: 'Title mandatory' })\n @Length(3, 255)\n title: string;\n\n @IsNotEmpty()\n @Length(3)\n description: string;\n}\n```\n\n**entity**\n\n```\nimport { BaseEntity, Entity, PrimaryGeneratedColumn, Column } from 'typeorm';\n\n@Entity('quizes')\nexport class Quiz extends BaseEntity {\n @PrimaryGeneratedColumn({\n comment: 'The quiz unique identifier',\n })\n id: number;\n\n @Column({\n type: 'varchar',\n })\n title: string;\n\n @Column({\n type: 'text',\n })\n description: string;\n\n @Column({\n type: 'varchar',\n })\n usernmae: string;\n\n @Column({\n type: 'date',\n })\n createddate: Date;\n\n @Column({\n type: 'boolean',\n default: 1,\n })\n isActive: boolean;\n}\n```\n\nSomebody know how can I fix this?\n\n========================================\n\nTop Answer:\nWhich version of **@nestjs/typeorm** and **typeorm** are you using? If you are using typeorm > 0.3 this is a known issue and using the required typeorm will solve the issue.\n\n========================================\n\nCode:\n```text\nimport { Module } from '@nestjs/common';\n import { AppController } from './app.controller';\n import { AppService } from './app.service';\n import { UserController } from './user/user.controller';\n import { UserModule } from './user/user.module';\n import { UserService } from './user/user.services';\n import { QuizModule } from './modules/quiz/quiz.module';\n //import { QuizController } from './modules/quiz/quiz.controller';\n //import { QuizService } from './modules/quiz/quiz.services';\n import { TypeOrmModule } from '@nestjs/typeorm';\n import { typeOrmConfig } from './config/typeorm.config';\n //import { QuizRepository } from './modules/quiz/quiz.repository';\n \n @Module({\n imports: [UserModule, QuizModule, TypeOrmModule.forRoot(typeOrmConfig)],\n controllers: [AppController],\n providers: [AppService],\n })\n export class AppModule {}\n```\n\n```text\nimport {\n Body,\n Controller,\n Get,\n HttpCode,\n Post,\n UsePipes,\n ValidationPipe,\n } from '@nestjs/common';\n import { QuizService } from './quiz.services';\n import { CreateQuizDto } from '../dto/CreateQuiz.dto';\n \n @Controller('quiz')\n export class QuizController {\n constructor(private readonly quizService: QuizService) {}\n \n @Get('/')\n getAllQuiz() {\n return this.quizService.getAllQuiz();\n }\n \n @Post('/create')\n @HttpCode(200)\n @UsePipes(ValidationPipe)\n async createQuiz(@Body() quizData: CreateQuizDto) {\n return await this.quizService.createNewQuiz(quizData);\n }\n }\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\n import { InjectRepository } from '@nestjs/typeorm';\n import { QuizRepository } from './quiz.repository';\n import { CreateQuizDto } from '../dto/CreateQuiz.dto';\n \n @Injectable()\n export class QuizService {\n constructor(\n @InjectRepository(QuizRepository) private quizRepository: QuizRepository,\n ) {}\n \n getAllQuiz() {\n return [1, 2, 'from service', 3];\n }\n async createNewQuiz(quiz: CreateQuizDto) {\n return await this.quizRepository.save(quiz);\n }\n }\n```\n\n```text\nimport { Module } from '@nestjs/common';\n import { TypeOrmModule } from '@nestjs/typeorm';\n import { QuizController } from './quiz.controller';\n import { QuizService } from './quiz.services';\n import { QuizRepository } from './quiz.repository';\n \n @Module({\n controllers: [QuizController],\n imports: [TypeOrmModule.forFeature([QuizRepository])],\n providers: [QuizService],\n })\n export class QuizModule {}\n```\n\n```text\nimport { EntityRepository, Repository } from 'typeorm';\n import { Quiz } from './quiz.entity';\n \n @EntityRepository(Quiz)\n export class QuizRepository extends Repository<Quiz> {\n //<Quiz> means Quiz module\n }\n```\n\n```text\nimport { TypeOrmModuleOptions } from '@nestjs/typeorm';\n\n export const typeOrmConfig: TypeOrmModuleOptions = {\n type: 'postgres',\n host: 'localhost',\n port: 5432,\n username: 'postgres',\n password: '123456',\n database: 'quiz',\n entities: [__dirname + '/../**/*.entity{.ts,.js}'],\n synchronize: true,\n };\n```\n\n```text\nimport { isNotEmpty, IsNotEmpty, Length } from 'class-validator';\n\nexport class CreateQuizDto {\n @IsNotEmpty({ message: 'Title mandatory' })\n @Length(3, 255)\n title: string;\n\n @IsNotEmpty()\n @Length(3)\n description: string;\n}\n```\n\n```text\nimport { BaseEntity, Entity, PrimaryGeneratedColumn, Column } from 'typeorm';\n\n@Entity('quizes')\nexport class Quiz extends BaseEntity {\n @PrimaryGeneratedColumn({\n comment: 'The quiz unique identifier',\n })\n id: number;\n\n @Column({\n type: 'varchar',\n })\n title: string;\n\n @Column({\n type: 'text',\n })\n description: string;\n\n @Column({\n type: 'varchar',\n })\n usernmae: string;\n\n @Column({\n type: 'date',\n })\n createddate: Date;\n\n @Column({\n type: 'boolean',\n default: 1,\n })\n isActive: boolean;\n}\n```\n\n```js\nconstructor(\n private quizRepository: QuizRepository,\n) {}\n```\n\n```text\nCustomRepository\n```\n\n```text\nInjectRepository\n```\n\n```text\nNestJS\n```\n\n```text\ntypeorm.config\n```\n\n```text\nQuiz\n```\n\n```text\nTypeORM\n```\n\n========================================\n\nComments:\n- Tried remove InjectRepository still error remains the same. Also edited the posted with typeorm.config\n- this solution worked for me as well, I also had exact problem.\n- It also solved other issues I was experiencing","metadata":{"transformedAt":"2026-08-18T18:33:44.713Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":415,"estimatedTokens":2577}}382{"id":"stack-76592521","source":"stackoverflow","questionId":76592521,"title":"How to automatically update and get a relation column based on other relation","tags":["typescript","postgresql","rxjs","nestjs","typeorm"],"text":"Title: How to automatically update and get a relation column based on other relation\nTags: typescript, postgresql, rxjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to connect 3 relations - Photo, PhotoComment and PhotoRating. I want to let my users to have a possibility to rate a photo. These photos can have multiple comments by many users and multiple rates by many users (but only 1 rate per specific user). And I want to show that user rate on all comments that belongs to photos. However, I cannot make things work to show a rate inside comment and update it automatically whenever user change photo rate (uses `ratePhoto` method)\n\nWhen I call `ratePhoto` method I can see in PGAdmin that `photoRatingId` is not connected with `PhotoComment` and it's not updating rate there. However, `ratePhoto` method works fine and saves rate of `Photo` correctly\n\nI'm using NestJS, TypeORM, PostgreSQL and RxJS. I highly prefer to work on repository instead of queryBuilder\n\n`photos.service.ts`\n\n```\npublic ratePhoto(photoId: number, ratePhotoDto: RatePhotoDto, user: User): Observable {\n return this.getPhoto(photoId).pipe(\n switchMap((photo: Photo) => from(this.photoRatingRepository.findOneBy({ photo: { id: photo.id }, user: { id: user.id } })).pipe(\n map((photoRating: PhotoRating) => {\n if (!photoRating) {\n const newRating: PhotoRating = new PhotoRating();\n\n newRating.rate = ratePhotoDto.rate;\n newRating.user = user;\n newRating.photo = photo;\n\n return this.photoRatingRepository.save(newRating);\n }\n\n photoRating.rate = ratePhotoDto.rate;\n\n return this.photoRatingRepository.save(photoRating);\n }),\n )),\n );\n }\n```\n\n`photo.entity.ts`\n\n```\n@Entity()\nexport class Photo {\n //...\n\n @OneToMany(() => PhotoComment, (photoComment: PhotoComment) => photoComment.photo)\n public photoComments: PhotoComment[];\n\n @OneToMany(() => PhotoRating, (photoRating: PhotoRating) => photoRating.photo)\n public photoRatings: PhotoRating[];\n}\n```\n\n`photo-comment.entity.ts`\n\n```\n@Entity()\nexport class PhotoComment {\n //...\n\n @ManyToOne(() => Photo, (photo: Photo) => photo.photoComments, { onDelete: 'CASCADE' })\n public photo: Photo;\n\n @ManyToOne(() => PhotoRating, (photoRating: PhotoRating) => photoRating.photoComment)\n @JoinColumn({ name: 'rate' })\n public photoRating: PhotoRating;\n}\n```\n\n`photo-rating.entity.ts`\n\n```\n@Entity()\n@Unique(['user', 'photo'])\nexport class PhotoRating {\n //...\n \n @Transform(({ value }) => +value)\n @Column({ type: 'decimal', precision: 3, scale: 2, default: 0 })\n public rate: number;\n\n @ManyToOne(() => Photo, (photo: Photo) => photo.photoRatings, { onDelete: 'CASCADE' })\n public photo: Photo;\n\n @OneToMany(() => PhotoComment, (photoComment: PhotoComment) => photoComment.photoRating, { cascade: true })\n public photoComment: PhotoComment;\n}\n```\n\nWhat am I doing wrong?\n\n========================================\n\nTop Answer:\nIn my opinion, the problem is that you have not set the *photoComment*\n\nproperty on the photoRating entity. To do this, add the following code to the *ratePhoto method*\n\n```\nphotoRating.photoComment = photoComment;\n```\n\nThis will ensure that the *photoComment* property of the *photoRating* entity is set correctly.\n\n**The method should be as follows**\n\n```\npublic ratePhoto(photoId: number, ratePhotoDto: RatePhotoDto, user: User): Observable {\n return this.getPhoto(photoId).pipe(\n switchMap((photo: Photo) => from(this.photoRatingRepository.findOneBy({ photo: { id: photo.id }, user: { id: user.id } })).pipe(\n map((photoRating: PhotoRating) => {\n if (!photoRating) {\n const newRating: PhotoRating = new PhotoRating();\n newRating.rate = ratePhotoDto.rate;\n newRating.user = user;\n newRating.photo = photo;\n return this.photoRatingRepository.save(newRating);\n }\n photoRating.rate = ratePhotoDto.rate;\n photoRating.photoComment = photoComment;\n return this.photoRatingRepository.save(photoRating);\n }),\n )),\n );\n}\n```\n\n========================================\n\nCode:\n```text\npublic ratePhoto(photoId: number, ratePhotoDto: RatePhotoDto, user: User): Observable<any> {\n return this.getPhoto(photoId).pipe(\n switchMap((photo: Photo) => from(this.photoRatingRepository.findOneBy({ photo: { id: photo.id }, user: { id: user.id } })).pipe(\n map((photoRating: PhotoRating) => {\n if (!photoRating) {\n const newRating: PhotoRating = new PhotoRating();\n\n newRating.rate = ratePhotoDto.rate;\n newRating.user = user;\n newRating.photo = photo;\n\n return this.photoRatingRepository.save(newRating);\n }\n\n photoRating.rate = ratePhotoDto.rate;\n\n return this.photoRatingRepository.save(photoRating);\n }),\n )),\n );\n }\n```\n\n```text\n@Entity()\nexport class Photo {\n //...\n\n @OneToMany(() => PhotoComment, (photoComment: PhotoComment) => photoComment.photo)\n public photoComments: PhotoComment[];\n\n @OneToMany(() => PhotoRating, (photoRating: PhotoRating) => photoRating.photo)\n public photoRatings: PhotoRating[];\n}\n```\n\n```text\n@Entity()\nexport class PhotoComment {\n //...\n\n @ManyToOne(() => Photo, (photo: Photo) => photo.photoComments, { onDelete: 'CASCADE' })\n public photo: Photo;\n\n @ManyToOne(() => PhotoRating, (photoRating: PhotoRating) => photoRating.photoComment)\n @JoinColumn({ name: 'rate' })\n public photoRating: PhotoRating;\n}\n```\n\n```text\n@Entity()\n@Unique(['user', 'photo'])\nexport class PhotoRating {\n //...\n \n @Transform(({ value }) => +value)\n @Column({ type: 'decimal', precision: 3, scale: 2, default: 0 })\n public rate: number;\n\n @ManyToOne(() => Photo, (photo: Photo) => photo.photoRatings, { onDelete: 'CASCADE' })\n public photo: Photo;\n\n @OneToMany(() => PhotoComment, (photoComment: PhotoComment) => photoComment.photoRating, { cascade: true })\n public photoComment: PhotoComment;\n}\n```\n\n```text\nratePhoto\n```\n\n```text\nratePhoto\n```\n\n```text\nphotoRatingId\n```\n\n```text\nPhotoComment\n```\n\n```text\nratePhoto\n```\n\n```text\nPhoto\n```\n\n```text\nphotos.service.ts\n```\n\n```text\nphoto.entity.ts\n```\n\n```text\nphoto-comment.entity.ts\n```\n\n```text\nphoto-rating.entity.ts\n```\n\n```text\npublic async ratePhoto(photoId: number, ratePhotoDto: RatePhotoDto, user: User): Promise<void> {\n await this.entityManager.transaction(async (entityManager: EntityManager) => {\n const photo: Photo = await this.photoRepository.findOne({ where: { photo: { id: photoId } } });\n const photoRating: PhotoRating = await this.photoRatingRepository.findOne({ where: { photo: { id: photo.id }, user: { id: user.id } } });\n \n if (!photoRating) {\n const newRating: PhotoRating = await entityManager.save( // Saving new rate of photo\n PhotoRating, \n { ...ratePhotoDto, user, photo }\n );\n \n await entityManager.update( // Fast update all comments that should be updated\n PhotoComment,\n { addedBy: { id: user.id }, photo: { id: photo.id } },\n { photoRating: newRating }\n );\n \n return;\n }\n \n await entityManager.save( // Saving rate of photo\n PhotoRating, \n { ...photoRating, ...ratePhotoDto }\n );\n \n await entityManager.update( // Fast update all comments that should be updated\n PhotoComment,\n { addedBy: { id: user.id }, photo: { id: photo.id } },\n { photoRating }\n );\n });\n }\n```\n\n```text\n@Entity()\nexport class Photo { // No changes here\n //...\n\n @OneToMany(() => PhotoComment, (photoComment: PhotoComment) => photoComment.photo)\n public photoComments: PhotoComment[];\n\n @OneToMany(() => PhotoRating, (photoRating: PhotoRating) => photoRating.photo)\n public photoRatings: PhotoRating[];\n}\n```\n\n```text\n@Entity()\nexport class PhotoComment { // Deleted JoinColumn because I don't need that\n //...\n\n @ManyToOne(() => Photo, (photo: Photo) => photo.photoComments, { onDelete: 'CASCADE' })\n public photo: Photo;\n\n @ManyToOne(() => PhotoRating, (photoRating: PhotoRating) => photoRating.photoComment)\n public photoRating: PhotoRating;\n}\n```\n\n```text\n@Entity()\n@Unique(['user', 'photo'])\nexport class PhotoRating { // Deleted { cascade: true | from PhotoComment because I don't want it\n //...\n \n @Transform(({ value }) => +value)\n @Column({ type: 'decimal', precision: 3, scale: 2, default: 0 })\n public rate: number;\n\n @ManyToOne(() => Photo, (photo: Photo) => photo.photoRatings, { onDelete: 'CASCADE' })\n public photo: Photo;\n\n @OneToMany(() => PhotoComment, (photoComment: PhotoComment) => photoComment.photoRating)\n public photoComment: PhotoComment;\n}\n```\n\n```text\n.update()\n```\n\n```text\ntransaction\n```\n\n```text\nRxJS\n```\n\n```text\nphotos.service.ts\n```\n\n```text\nphoto.entity.ts\n```\n\n```text\nphoto-comment.entity.ts\n```\n\n```text\nphoto-rating.entity.ts\n```\n\n```text\n.update()\n```\n\n```text\nphotoRating.photoComment = photoComment;\n```\n\n```text\npublic ratePhoto(photoId: number, ratePhotoDto: RatePhotoDto, user: User): Observable<any> {\n return this.getPhoto(photoId).pipe(\n switchMap((photo: Photo) => from(this.photoRatingRepository.findOneBy({ photo: { id: photo.id }, user: { id: user.id } })).pipe(\n map((photoRating: PhotoRating) => {\n if (!photoRating) {\n const newRating: PhotoRating = new PhotoRating();\n newRating.rate = ratePhotoDto.rate;\n newRating.user = user;\n newRating.photo = photo;\n return this.photoRatingRepository.save(newRating);\n }\n photoRating.rate = ratePhotoDto.rate;\n photoRating.photoComment = photoComment;\n return this.photoRatingRepository.save(photoRating);\n }),\n )),\n );\n}\n```\n\n========================================\n\nComments:\n- Why does `PhotoComment` entity has that `photoRating` property, and why does `PhotoRating` has that `photoComment`. Is it required to have a `photoRating` for a `photo` record or `photoComment` record?\n- I've set these entities with relations between themselves. Maybe I'm wrong, cause I'm still newbie in NestJS and TypeORM, however I think if I want to show a `rate` (which comes from `photoRating` in my comments (`PhotoComment` entity) and automatically adjust this rate on comments whenever user changes it (`ratePhoto` method on `Photo` entity), I have to set these relations. Correct me if I'm wrong\n- I don't have a `photoComment` data here. I need that rate to be visible for all comments of specific user so, maybe I'm wrong, but I don't think that getting all these comments here and manually setting rate to them every time user changes rate is a good approach\n- There are some indications that you may have used an AI tool (e.g., ChatGPT) to assist with this answer. If so, I'd encourage you to delete it since [posting of AI-generated content is not permitted on Stack Overflow].","metadata":{"transformedAt":"2026-08-18T18:33:44.713Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":28,"totalLines":381,"estimatedTokens":2781}}383{"id":"stack-54684928","source":"stackoverflow","questionId":54684928,"title":"How to use Parameterized query using TypeORM for postgres database and nodejs as the application's back-end server","tags":["node.js","postgresql","typeorm"],"text":"Title: How to use Parameterized query using TypeORM for postgres database and nodejs as the application's back-end server\nTags: node.js, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to fetch the rows from a postgres table where name = SUPREME INT'L,\nNote: this string has a single quote in between the name characters.\nI am using TypeORM as an ORM, POSTGRESQL as the database.\n\nMy query:\n\n```\nimport { getConnection } from 'typeorm';\n const connection = getConnection();\n\n var query = `SELECT * from skusimulations where \"name\"= ? `;\n const output =await connection.query(query, ['SUPREME INT'L'])\n```\n\nI am getting error while executing this, I want to escape the single quote by using stored proc.\n\nAny help would be highly appreciated.\n\n========================================\n\nTop Answer:\nfor mysql `await getEntityManager().query('SELECT * FROM tbl_1 WHERE name = ?', [ p_name ])`\n\nfor mssql `await getEntityManager().query('SELECT * FROM tbl_1 WHERE name = @0', [ p_name ])`\n\nfor postgres `.query('SELECT * FROM test WHERE id = ANY($1)', [[1,2,4]]`\n\nbelow worked for me in case of mssql driver\n\nhttps://i.sstatic.net/eJuau.png\n\nfor more info https://github.com/typeorm/typeorm/issues/556\n\n========================================\n\nCode:\n```text\nimport { getConnection } from 'typeorm';\n const connection = getConnection();\n\n var query = `SELECT * from skusimulations where \"name\"= ? `;\n const output =await connection.query(query, ['SUPREME INT'L'])\n```\n\n```text\nvar name = \"SUPREME INT'L\" ;\n var query = `SELECT * from skusimulations where \"skuId\"= $1 `;\n var skuData =await connection.query(query, [name])\n```\n\n```text\ntypeorm.io\n```\n\n```text\nawait getEntityManager().query('SELECT * FROM tbl_1 WHERE name = ?', [ p_name ])\n```\n\n```text\nawait getEntityManager().query('SELECT * FROM tbl_1 WHERE name = @0', [ p_name ])\n```\n\n```text\n.query('SELECT * FROM test WHERE id = ANY($1)', [[1,2,4]]\n```\n\n========================================\n\nComments:\n- What error? Are you referring to your failure to escape the single quote in your literal, because the query itself looks like it is already using parameter escaping.\n- @RichardHuxton, yes indeed I used stored proc to escape the single quote. Btw I solved it by storing the \"name\" in a variable and passing the variable in the replacement array, another modification was instead of '?' changed it to $1.\n- this was really helpful, thanks! , if someone need this for mssql (like me) you just need to change the $ for @ and the position parameter start with 0","metadata":{"transformedAt":"2026-08-18T18:33:44.713Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":77,"estimatedTokens":634}}384{"id":"stack-61214198","source":"stackoverflow","questionId":61214198,"title":"TypeOrm query builder","tags":["nestjs","typeorm"],"text":"Title: TypeOrm query builder\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI can't figure out how to write the following MySql statement using TypeOrm Query Builder\n\n SELECT reg.id FROM farm.reg WHERE grpId = 'ABC';\n\nthis select is returning just the id's but my query builder is returning the entire objects.\n\nIn this moment I have this function in my NestJs service but I need to use 'map' and I don't want to..\n\n```\nasync getGrupIds(entity: string, grpId: string) {\n\n console.log(entity, grpId);\n const ids = await getRepository(reg)\n .createQueryBuilder(entity)\n .where('reg.grpId = :grpId', {grpId: grpId})\n .getMany();\n console.log(ids);\n return ids.map(o => o.id);\n\n }\n```\n\nThank you\n\n========================================\n\nCode:\n```text\nasync getGrupIds(entity: string, grpId: string) {\n\n console.log(entity, grpId);\n const ids = await getRepository(reg)\n .createQueryBuilder(entity)\n .where('reg.grpId = :grpId', {grpId: grpId})\n .getMany();\n console.log(ids);\n return ids.map(o => o.id);\n\n }\n```\n\n```text\n//I suppose you have a *grpId* variable in your function \n\nconst ids = await getRepository(Reg)\n .createQueryBuilder('reg')\n .select('reg.grpId', 'id')\n .where('reg.grpId = :grpId', { grpId } )\n .getRawMany();\n console.log(ids);\n return ids \n}\n```\n\n========================================\n\nComments:\n- async getGroupIds(entity: string, grpId: string) { const ids = await getRepository(reg) .createQueryBuilder(entity) .select('reg.id') .where('reg.grpId = :grpId', {grpId: grpId}) .getRawMany(); console.log(ids); // return ids.map(o => o.id); return ids } works like a charm, many thanks!","metadata":{"transformedAt":"2026-08-18T18:33:44.713Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":63,"estimatedTokens":423}}385{"id":"stack-74346176","source":"stackoverflow","questionId":74346176,"title":"TypeORM query builder conditional where clause","tags":["javascript","sql","node.js","typescript","typeorm"],"text":"Title: TypeORM query builder conditional where clause\nTags: javascript, sql, node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to attach a conditional where clause to the query.\n\nI need some link to documentation or any hint how can I acheive that.\n\n**Query:**\n\n```\nconst usersQuery = await connection\n.getRepository(User)\n.createQueryBuilder(\"user\")\n.getMany();\n```\n\nNow here I want to add if I get a userId paramater, I want to inject where clause into the query instance.\n\ne.g:\n\n```\nif(params.userId){\n usersQuery.where(\"user.id = :id\", { id: params.userId });\n}\n\nif(params.email){\n usersQuery.where(\"user.email= :email\", { email: params.email});\n}\n```\n\nThis is something I want to achieve but some how I am unable to find this in the docs. Can anyone provide me the docs or reference.\n\n========================================\n\nTop Answer:\ncheck a npm package called typeorm-difo. The plugin's goal is to facilitate writing \"relations\", \"where\" and \"order\" arguments for any find method of an entity repository. With this plugin, it is not necessary to manually write the \"relation\" argument, it is inferred from the \"where\" argument. It is also possible to reduce nested objects by concatenating them with \".\" (period).\n\n```\nuserRepository.find({\n where: getWhere([\n {\n field: \"firstName\",\n searchTerm:\"John\",\n },\n {\n field: \"company.name\",\n searchTerm:\"company\",\n }\n ])\n });\n```\n\n========================================\n\nCode:\n```text\nconst usersQuery = await connection\n.getRepository(User)\n.createQueryBuilder(\"user\")\n.getMany();\n```\n\n```text\nif(params.userId){\n usersQuery.where(\"user.id = :id\", { id: params.userId });\n}\n\nif(params.email){\n usersQuery.where(\"user.email= :email\", { email: params.email});\n}\n```\n\n```text\nconst usersQuery = await connection\n .getRepository(User)\n .createQueryBuilder(\"user\")\n\nif(params.userId){\n usersQuery.andWhere(\"user.id = :id\", { id: params.userId });\n}\n\nif(params.email){\n usersQuery.andWhere(\"user.email= :email\", { email: params.email});\n}\n\nconst users = await usersQuery.getRawMany();\n```\n\n```text\nuserRepository.find({\n where: getWhere([\n {\n field: \"firstName\",\n searchTerm:\"John\",\n },\n {\n field: \"company.name\",\n searchTerm:\"company\",\n }\n ])\n });\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.713Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":4,"totalLines":104,"estimatedTokens":582}}386{"id":"stack-58632489","source":"stackoverflow","questionId":58632489,"title":"typeOrm unique row","tags":["nestjs","typeorm"],"text":"Title: typeOrm unique row\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a Entity using typeOrm on my NestJS, and it's not working as I expected.\n\nI have the following entity\n\n```\n@Entity('TableOne')\nexport class TableOneModel {\n @PrimaryGeneratedColumn()\n id: number\n\n @PrimaryColumn()\n tableTwoID: number\n\n @PrimaryColumn()\n tableThreeID: number\n\n @CreateDateColumn()\n createdAt?: Date\n}\n```\n\nThis code generate a migration that generates a table like the example below\n\n```\n+--------------+-------------+------+-----+----------------------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------+-------------+------+-----+----------------------+-------+\n| id | int(11) | NO | | NULL | |\n| tableTwoID | int(11) | NO | | NULL | |\n| tableThreeID | int(11) | NO | | NULL | |\n| createdAt | datetime(6) | NO | | CURRENT_TIMESTAMP(6) | |\n+--------------+-------------+------+-----+----------------------+-------+\n```\n\nThat's ok, the problem is, that I want to the table only allow one row with `tableTwoID` and `tableThreeID`, what should I use in the Entity to generated the table as I expected it to be?\n\nExpected to not allow rows like the example below\n\n```\n+----+------------+--------------+----------------------------+\n| id | tableTwoID | tableThreeID | createdAt |\n+----+------------+--------------+----------------------------+\n| 1 | 1 | 1 | 2019-10-30 19:27:43.054844 |\n| 2 | 1 | 1 | 2019-10-30 19:27:43.819174 | <- should not allow the insert of this row\n+----+------------+--------------+----------------------------+\n```\n\n========================================\n\nTop Answer:\nThis is currently expected behavior from TypeORM. According to the documentation if you have multiple `@PrimaryColumn()` decorators you create a composite key. The combination of the composite key columns must be unique (in your above `'1' + '1' + '1' = '111'` vs `'2' + '1' + '1' = '211'`). If you are looking to make each column unique along with being a composite primary key, you should be able to do something like `@PrimaryColumn({ unique: true })`\n\n========================================\n\nCode:\n```js\n@Entity('TableOne')\nexport class TableOneModel {\n @PrimaryGeneratedColumn()\n id: number\n\n @PrimaryColumn()\n tableTwoID: number\n\n @PrimaryColumn()\n tableThreeID: number\n\n @CreateDateColumn()\n createdAt?: Date\n}\n```\n\n```text\n+--------------+-------------+------+-----+----------------------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------+-------------+------+-----+----------------------+-------+\n| id | int(11) | NO | | NULL | |\n| tableTwoID | int(11) | NO | | NULL | |\n| tableThreeID | int(11) | NO | | NULL | |\n| createdAt | datetime(6) | NO | | CURRENT_TIMESTAMP(6) | |\n+--------------+-------------+------+-----+----------------------+-------+\n```\n\n```text\n+----+------------+--------------+----------------------------+\n| id | tableTwoID | tableThreeID | createdAt |\n+----+------------+--------------+----------------------------+\n| 1 | 1 | 1 | 2019-10-30 19:27:43.054844 |\n| 2 | 1 | 1 | 2019-10-30 19:27:43.819174 | <- should not allow the insert of this row\n+----+------------+--------------+----------------------------+\n```\n\n```text\ntableTwoID\n```\n\n```text\ntableThreeID\n```\n\n```text\n@PrimaryColumn()\n```\n\n```text\n'1' + '1' + '1' = '111'\n```\n\n```text\n'2' + '1' + '1' = '211'\n```\n\n```text\n@PrimaryColumn({ unique: true })\n```\n\n========================================\n\nComments:\n- I got the message \"Error: Sqlite does not support AUTOINCREMENT on composite primary key\" when using multiple `@PrimaryColumn()` decorators with TypeORM and \"sqlite3\".\n- Thanks, this tip helped to solve my problem, I've used this like this `@Unique('uniqueTableTwoIDTableThreeID', ['tableTwoID', 'tableThreeID'])`\n- Annotating the entity class not the column will yield a composite key","metadata":{"transformedAt":"2026-08-18T18:33:44.713Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":127,"estimatedTokens":1015}}387{"id":"stack-76921431","source":"stackoverflow","questionId":76921431,"title":"TypeOrm-Postgres-NestJs @Column('decimal') is returning string","tags":["typescript","postgresql","nestjs","typeorm","nestjs-typeorm"],"text":"Title: TypeOrm-Postgres-NestJs @Column('decimal') is returning string\nTags: typescript, postgresql, nestjs, typeorm, nestjs-typeorm\nSource: Stack Overflow\n\nQuestion:\nI have some columns with type decimal. I am using query builder for aggregation. The only problem is after aggregating the result the fields that have decimal values are returning as string after executing the query.\n\nI want to set it globally across my project to consider decimal numbers in entity as decimal numbers only while executing queries and not string.\n\nI have tried using transformer with @Column() but it is not working.\n\n```\n@Column('decimal', {\n transformer: {\n to(value) {\n return value;\n },\n from(value) {\n return parseFloat(value);\n },\n },\n })\n price: number;\n```\n\nbut even if it works I don't want to write same thing for all columns.\nI want to make this setting globally.\n\n========================================\n\nCode:\n```text\n@Column('decimal', {\n transformer: {\n to(value) {\n return value;\n },\n from(value) {\n return parseFloat(value);\n },\n },\n })\n price: number;\n```\n\n```text\n// transformer\nexport class DecimalColumnTransformer {\n to(data: number): number {\n return data;\n }\n from(data: string): number {\n return parseFloat(data);\n }\n}\n```\n\n```text\n// entity\n@Column('decimal', {\n precision: 5,\n scale: 2,\n transformer: new DecimalColumnTransformer(),\n})\nprice: number;\n```\n\n```text\nnumber\n```\n\n```text\nstring\n```\n\n```text\nmysql\n```\n\n```text\nsupportBigNumbers: false\n```\n\n```text\nnode-mysql\n```\n\n```text\nprecision\n```\n\n```text\nscale\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.713Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":94,"estimatedTokens":402}}388{"id":"stack-55240553","source":"stackoverflow","questionId":55240553,"title":"What is wrong with the parameters in my TypeORM WHERE clause for the QueryBuilder?","tags":["typescript","query-builder","typeorm"],"text":"Title: What is wrong with the parameters in my TypeORM WHERE clause for the QueryBuilder?\nTags: typescript, query-builder, typeorm\nSource: Stack Overflow\n\nQuestion:\nCan someone explain to me what I am doing wrong when using the parameters for my where clause?\n\nThis next block gives me the error below it:\n\n```\n@EntityRepository(Something)\nexport class SomethingRepository extends Repository{\n\n findByUserAndSomethingById(userId: number, spotId: number){\n const thing = this.createQueryBuilder('something')\n .where('something.userId = :id', {id: userId})\n .andWhere('something.id = :id',{id: spotId}).getOne();\n return thing;\n }\n}\n```\n\n```\nQueryFailedError: column something.userid does not exist\n```\n\nThis request gives me the right result.\n\n```\n@EntityRepository(Something)\nexport class SomethingRepository extends Repository{\n\n findByUserAndSomethingById(userId: number, spotId: number){\n const thing = this.createQueryBuilder('something')\n .where(`\"something\".\"userId\" = ${userId}`)\n .andWhere('something.id = :id',{id: spotId}).getOne();\n return thing;\n }\n}\n```\n\nUpdate: \nExample repo for reproduction and typeorm issue on github.\n\n========================================\n\nTop Answer:\nThe issue with the original query is that the parameter name `id` was used more than once:\n\n```\n.where('something.userId = :id', {id: userId})\n .andWhere('something.id = :id',{id: spotId}).getOne();\n```\n\nThese need to be unique according to this note in the docs.\n\n========================================\n\nCode:\n```text\n@EntityRepository(Something)\nexport class SomethingRepository extends Repository<Something>{\n\n findByUserAndSomethingById(userId: number, spotId: number){\n const thing = this.createQueryBuilder('something')\n .where('something.userId = :id', {id: userId})\n .andWhere('something.id = :id',{id: spotId}).getOne();\n return thing;\n }\n}\n```\n\n```sh\nQueryFailedError: column something.userid does not exist\n```\n\n```text\n@EntityRepository(Something)\nexport class SomethingRepository extends Repository<Something>{\n\n findByUserAndSomethingById(userId: number, spotId: number){\n const thing = this.createQueryBuilder('something')\n .where(`\"something\".\"userId\" = ${userId}`)\n .andWhere('something.id = :id',{id: spotId}).getOne();\n return thing;\n }\n}\n```\n\n```text\nfindByUserAndSomethingById(userId: number, spotId: number) {\n const thing = this.createQueryBuilder('something')\n .innerJoin('something.user', 'user')\n .where('user.id = :uid', { uid: userId })\n .andWhere('something.id = :sid', { sid: spotId }).getOne();\n return thing;\n}\n```\n\n```text\n.where('\"something\".\"userId\"' = :id', {id: userId})\n```\n\n```text\n.where('\"something\".\"userId\"' = ${userId})\n```\n\n```text\n.where('something.userId = :id', {id: userId})\n .andWhere('something.id = :id',{id: spotId}).getOne();\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- Are you able to read which query being executed in your project?\n- Yes I can. Take a look at this gist gist.github.com/fabianmoronzirfas/…\n- I think I know where this is coming from. Error message is `'column bathingspot.userid does not exist'` the hint for that is `'Perhaps you meant to reference the column \"bathingspot.userId\"` It seems like the camelcase in the string where the parameters are applied is beeing \"uncamelcased\" somehow. gist.githubusercontent.com/fabianmoronzirfas/…\n- The only difference I could notice was the `'` before and after the query between the failing query and successful query from gist.githubusercontent.com/fabianmoronzirfas/…. Also, probably `$` is missing from `2` in working query? `WHERE \"bathingspot\".\"userId\" = 2 AND \"bathingspot\".\"id\" = $1` from gist.github.com/fabianmoronzirfas/…\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:44.713Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":124,"estimatedTokens":949}}389{"id":"stack-68983394","source":"stackoverflow","questionId":68983394,"title":"In TypeOrm, what are the default fetch types for OneToMany and ManyToOne?","tags":["typeorm"],"text":"Title: In TypeOrm, what are the default fetch types for OneToMany and ManyToOne?\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nTypeorm's official document states that if you use Lazy, you must use promise. If not promise, will default fetch type be eager loading? However, I checked and it seems to be loading Lazy, not Eager.\nThe default pitch type of JPA is as follows:\n\n```\nOneToMany: LAZY\nManyToOne: EAGER\nManyToMany: LAZY\nOneToOne: EAGER\n```\n\nIs TypeOrm's default fetch type the same?\n\n========================================\n\nCode:\n```text\nOneToMany: LAZY\nManyToOne: EAGER\nManyToMany: LAZY\nOneToOne: EAGER\n```\n\n```js\nexport interface RelationOptions {\n ...\n\n /**\n * Set this relation to be lazy. Note: lazy relations are promises. When you call them they return promise\n * which resolve relation result then. If your property's type is Promise then this relation is set to lazy automatically.\n */\n lazy?: boolean;\n /**\n * Set this relation to be eager.\n * Eager relations are always loaded automatically when relation's owner entity is loaded using find* methods.\n * Only using QueryBuilder prevents loading eager relations.\n * Eager flag cannot be set from both sides of relation - you can eager load only one side of the relationship.\n */\n eager?: boolean;\n\n ...\n}\n```\n\n```js\nconst user = userRepository.find({\n where: {\n name: \"John\",\n },\n relations: [\"project\"],\n});\n\n// Think user has a one-to-many relationship with projects, then:\n// const projects = user.projects;\n```\n\n```js\nconst user = userRepository.find({\n where: {\n name: \"John\",\n }\n});\n\n// Need await for `lazy`:\n// const projects = await user.projects;\n```\n\n```js\nconst user = userRepository.find({\n where: {\n name: \"John\",\n }\n});\n\n// No await for `eager`:\n// const projects = user.projects;\n```\n\n```text\nlazy\n```\n\n```text\neager\n```\n\n```text\nlazy\n```\n\n```text\neager\n```\n\n```text\nlazy\n```\n\n```text\neager\n```\n\n```text\nfind\n```\n\n```text\nQueryBuilder\n```\n\n```text\nfind\n```\n\n```text\nlazy\n```\n\n```text\neager\n```\n\n```text\nfind\n```\n\n```text\nQueryBuilder\n```\n\n```text\nlazy\n```\n\n```text\neager\n```\n\n========================================\n\nComments:\n- Thank you so much Heshan. I spent the day because of this problem. very very Thank you :)","metadata":{"transformedAt":"2026-08-18T18:33:44.713Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":146,"estimatedTokens":575}}390{"id":"stack-73581933","source":"stackoverflow","questionId":73581933,"title":"TypeORM \"OR\" \"AND \"operator combination","tags":["typescript","graphql","nestjs","typeorm"],"text":"Title: TypeORM \"OR\" \"AND \"operator combination\nTags: typescript, graphql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm not sure how to use the OR condition in typeOrm where clause, could not find solution so far.\n\nI have a db call as follows\n\n\r\n\r\n\n```\ndb.getRepository(MyModel).find({\nwhere:{\n type : \"new\",\n status: \"A\"\n region: \"central\"\n zip_code: \"4831\"\n }\n })\n```\n\n\r\n\r\n\r\n\nI need to modify the above call same as to below SQL query\n\n```\nselect * from model where type=\"new\" and status=\"A\" and (region=\"central\" or zip_code=\"4831\");\n```\n\n========================================\n\nTop Answer:\nYou can use the createQueryBuilder of typeorm. You can check the use of bracket here. You can use orWhere wherever you need to use the OR condition. By your query, you can use the below code:\n\n```\ncreateQueryBuilder(\"MyModel\")\n .where(\"MyModel.type = :type\", { type: \"new\" })\n .andWhere(\"MyModel.status = :status\", { status: \"A\" })\n .andWhere(\n new Brackets((qb) => {\n qb.where(\"MyModel.region = :region\", {\n region: \"central\",\n }).orWhere(\"MyModel.zip_code = :zip\", { zip: \"4831\" });\n })\n );\n```\n\nThis will result in the SQL query:\n\n```\nselect * from model where type=\"new\" and status=\"A\" and (region=\"central\" or zip_code=\"4831\");\n```\n\n========================================\n\nCode:\n```html\ndb.getRepository(MyModel).find({\nwhere:{\n type : \"new\",\n status: \"A\"\n region: \"central\"\n zip_code: \"4831\"\n }\n })\n```\n\n```text\nselect * from model where type=\"new\" and status=\"A\" and (region=\"central\" or zip_code=\"4831\");\n```\n\n```js\ndb.getRepository(MyModel).find({\n where: [\n {\n type : \"new\",\n status: \"A\",\n region: \"central\"\n },\n {\n type : \"new\",\n status: \"A\",\n zip_code: \"4831\"\n },\n ]\n})\n```\n\n```sql\nselect * from model \n where \n (type=\"new\" and status=\"A\" and region=\"central\")\n OR \n (type=\"new\" and status=\"A\" and zip_code=\"4831\")\n```\n\n```text\nwhere\n```\n\n```text\nOR\n```\n\n```text\ncreateQueryBuilder(\"MyModel\")\n .where(\"MyModel.type = :type\", { type: \"new\" })\n .andWhere(\"MyModel.status = :status\", { status: \"A\" })\n .andWhere(\n new Brackets((qb) => {\n qb.where(\"MyModel.region = :region\", {\n region: \"central\",\n }).orWhere(\"MyModel.zip_code = :zip\", { zip: \"4831\" });\n })\n );\n```\n\n```text\nselect * from model where type=\"new\" and status=\"A\" and (region=\"central\" or zip_code=\"4831\");\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.713Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":8,"totalLines":124,"estimatedTokens":594}}391{"id":"stack-64337152","source":"stackoverflow","questionId":64337152,"title":"TypeORM make COUNT query on table which maps two tables together","tags":["mysql","database","nestjs","typeorm"],"text":"Title: TypeORM make COUNT query on table which maps two tables together\nTags: mysql, database, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have two entities `Model` and `Video` where `Video` basically store information about videos and `Model` store information about model. Because each video can have multiple models and each model can have multiple video entities looks like this:\n\n### How my entites and tables looks like:\n\n```\n// Video Entity\n@Entity()\nexport class Video {\n @PrimaryGeneratedColumn()\n id?: number; \n\n @Column({ charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })\n name: string;\n\n @Column({ type: 'text', charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })\n description: string;\n\n @ManyToMany((type) => Model)\n @JoinTable()\n models: Model[];\n}\n\n// Model Entity\n@Entity()\nexport class Model {\n\n @PrimaryGeneratedColumn()\n id?: number; \n\n @Column()\n name: string;\n\n @Column()\n code: string;\n}\n```\n\nBecause there is relation `@ManyToMany` between model and video TypeORM also created one extra table for connecting this two. Table name is `video_models_model` and it looks like this:\n\n```\n+-----------+---------+\n| videoId | modelId |\n+===========+=========+\n| 1 | 107 |\n+-----------+---------+\n| 2 | 142 |\n+-----------+---------+\n| 3 | 91 |\n+-----------+---------+\n```\n\n### What I need:\n\nBased on modelId I need to find out `COUNT()` of videos.\nIn regular query language it would be something like:\n\n```\nSELECT model.*, COUNT(model_videos.videoId) as totalVideos FROM model as model\nLEFT JOIN `video_models_model` `model_videos` ON `model_videos`.`modelId`=`model`.`id` \nWHERE model.id = 1;\n```\n\n### What I tried:\n\nThis is how regular query would looks like:\n\n```\nthis.modelRepository\n .createQueryBuilder('model') \n .where('model.id = :id', { id: id }) \n .getOne();\n```\n\nso what I did was added to `Model` entity\n\n```\n@ManyToMany(type => Video)\n @JoinTable()\n videos: Video[];\n```\n\nand after that I tried\n\n```\nthis.modelRepository\n .createQueryBuilder('model')\n .leftJoin('model.videos', 'videos')\n .select('COUNT(videos)', 'totalVideos') \n .where('model.id = :id', { id: id }) \n .getOne();\n```\n\nBut it didn't work for me at all pluis it created one additional table named `model_videos_video` with `modelId` and `videoId` columns. So basically duplicate `video_models_model` table.\n\nIs there any way how to make that easy query with TypeORM?\n\n========================================\n\nCode:\n```text\n// Video Entity\n@Entity()\nexport class Video {\n @PrimaryGeneratedColumn()\n id?: number; \n\n @Column({ charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })\n name: string;\n\n @Column({ type: 'text', charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })\n description: string;\n\n @ManyToMany((type) => Model)\n @JoinTable()\n models: Model[];\n}\n\n\n// Model Entity\n@Entity()\nexport class Model {\n\n @PrimaryGeneratedColumn()\n id?: number; \n\n @Column()\n name: string;\n\n @Column()\n code: string;\n}\n```\n\n```text\n+-----------+---------+\n| videoId | modelId |\n+===========+=========+\n| 1 | 107 |\n+-----------+---------+\n| 2 | 142 |\n+-----------+---------+\n| 3 | 91 |\n+-----------+---------+\n```\n\n```text\nSELECT model.*, COUNT(model_videos.videoId) as totalVideos FROM model as model\nLEFT JOIN `video_models_model` `model_videos` ON `model_videos`.`modelId`=`model`.`id` \nWHERE model.id = 1;\n```\n\n```text\nthis.modelRepository\n .createQueryBuilder('model') \n .where('model.id = :id', { id: id }) \n .getOne();\n```\n\n```text\n@ManyToMany(type => Video)\n @JoinTable()\n videos: Video[];\n```\n\n```text\nthis.modelRepository\n .createQueryBuilder('model')\n .leftJoin('model.videos', 'videos')\n .select('COUNT(videos)', 'totalVideos') \n .where('model.id = :id', { id: id }) \n .getOne();\n```\n\n```text\nModel\n```\n\n```text\nVideo\n```\n\n```text\nVideo\n```\n\n```text\nModel\n```\n\n```text\n@ManyToMany\n```\n\n```text\nvideo_models_model\n```\n\n```text\nCOUNT()\n```\n\n```text\nModel\n```\n\n```text\nmodel_videos_video\n```\n\n```text\nmodelId\n```\n\n```text\nvideoId\n```\n\n```text\nvideo_models_model\n```\n\n```text\n@Entity()\nexport class Video {\n @PrimaryGeneratedColumn()\n id?: number; \n\n @Column({ charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })\n name: string;\n\n @Column({ type: 'text', charset: 'utf8mb4', collation: 'utf8mb4_unicode_ci' })\n description: string;\n\n @ManyToMany(type => Model, model => model.videos)\n @JoinTable()\n models: Model[];\n}\n```\n\n```text\n@Entity()\nexport class Model {\n\n @PrimaryGeneratedColumn()\n id?: number; \n\n @Column()\n name: string;\n\n @Column()\n code: string;\n\n @ManyToMany(type => Video, video => video.models)\n videos: Video[];\n}\n```\n\n```text\nthis.modelRepository\n .createQueryBuilder('model')\n .loadRelationCountAndMap('model.videoCount', 'model.videos')\n .where('model.id = :id', { id: id }) \n .getOne();\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.713Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":21,"totalLines":269,"estimatedTokens":1208}}392{"id":"stack-60768582","source":"stackoverflow","questionId":60768582,"title":"Nest js POST Request Not Recognizing DTO method","tags":["javascript","typescript","http","nest","typeorm"],"text":"Title: Nest js POST Request Not Recognizing DTO method\nTags: javascript, typescript, http, nest, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm having some trouble hitting a POST endpoint that triggers a typeorm repository.save() method to my postgres DB. \n\nHere's my DTO object:\n\n```\nimport { ApiProperty } from '@nestjs/swagger/';\nimport { IsString, IsUUID} from 'class-validator';\n\nimport { Client } from '../../../models';\nimport { User } from '../../../user.decorator';\n\nexport class ClientDTO implements Readonly {\n @ApiProperty({ required: true })\n @IsUUID()\n id: string;\n\n @ApiProperty({ required: true })\n @IsString()\n name: string;\n\n public static from(dto: Partial) {\n const cl = new ClientDTO();\n cl.id = dto.id;\n cl.name = dto.name;\n return cl;\n }\n\n public static fromEntity(entity: Client) {\n return this.from({\n id: entity.id,\n name: entity.name,\n });\n }\n\n public toEntity = (user: User | null) => {\n const cl = new Client();\n cl.id = this.id;\n cl.name = this.name;\n cl.createDateTime = new Date();\n cl.createdBy = user ? user.id : null;\n cl.lastChangedBy = user ? user.id : null;\n return cl;\n }\n }\n```\n\nMy controller at POST - `/client`:\n\n```\nimport { \n Body,\n Controller, \n Get, Post \n} from '@nestjs/common';\n\nimport { ClientDTO } from './dto/client.dto';\nimport { ClientService } from './client.service';\nimport { User } from 'src/user.decorator';\n\n@Controller('client')\nexport class ClientController {\n constructor(\n private clientService: ClientService\n ) { }\n\n @Get()\n public async getAllClients(): Promise {\n return this.clientService.getAllClients();\n }\n\n @Post()\n public async createClient(@User() user: User, @Body() dto: ClientDTO): Promise {\n return this.clientService.createClient(dto, user);\n }\n}\n```\n\nAnd my service:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\nimport { Client } from '../../models';\nimport { ClientDTO } from './dto/client.dto';\nimport { User } from '../../user.decorator';\n\n@Injectable()\nexport class ClientService {\n constructor(\n @InjectRepository(Client) private readonly clientRepository: Repository\n ) {}\n\n public async getAllClients(): Promise {\n return await this.clientRepository.find()\n .then(clients => clients.map(e => ClientDTO.fromEntity(e)));\n }\n\n public async createClient(dto: ClientDTO, user: User): Promise {\n return this.clientRepository.save(dto.toEntity(user))\n .then(e => ClientDTO.fromEntity(e));\n }\n}\n```\n\nI get a 500 internal server error with log message stating that my ClientDTO.toEntity is not a function.\n\n```\nTypeError: dto.toEntity is not a function\n at ClientService.createClient (C:\\...\\nest-backend\\dist\\features\\client\\client.service.js:29:47)\n at ClientController.createClient (C:\\...\\nest-backend\\dist\\features\\client\\client.controller.js:27:35)\n at C:\\...\\nest-backend\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:37:29\n at process._tickCallback (internal/process/next_tick.js:68:7)\n```\n\nI'm confused because this only happens via http request. I have a script that seed my dev database after I launch it fresh in a docker container called seed.ts:\n\n```\nimport * as _ from 'lodash';\n\nimport { Client } from '../models';\nimport { ClientDTO } from '../features/client/dto/client.dto';\nimport { ClientService } from '../features/client/client.service';\nimport { configService } from '../config/config.service';\nimport { createConnection, ConnectionOptions } from 'typeorm';\nimport { User } from '../user.decorator';\n\nasync function run() {\n\n const seedUser: User = { id: 'seed-user' };\n\n const seedId = Date.now()\n .toString()\n .split('')\n .reverse()\n .reduce((s, it, x) => (x > 3 ? s : (s += it)), '');\n\n const opt = {\n ...configService.getTypeOrmConfig(),\n debug: true\n };\n\n const connection = await createConnection(opt as ConnectionOptions);\n const clientService = new ClientService(connection.getRepository(Client));\n\n const work = _.range(1, 10).map(n => ClientDTO.from({\n name: `seed${seedId}-${n}`,\n }))\n######################## my service calls ClientDTO.toEntity() without issue ###########################\n .map(dto => clientService.createClient(dto, seedUser) \n .then(r => (console.log('done ->', r.name), r)))\n\n return await Promise.all(work);\n}\n\nrun()\n .then(_ => console.log('...wait for script to exit'))\n .catch(error => console.error('seed error', error));\n```\n\nIt makes me think I am missing something simple/obvious. \n\nThanks!\n\n========================================\n\nTop Answer:\nLooks like you are using ValidationPipe. The solution is mentioned here\nhttps://github.com/nestjs/nest/issues/552\n\nwhen setting your validation pipe you need to tell it to transform for example\n\n```\napp.useGlobalPipes(new ValidationPipe({\n transform: true\n}));\n```\n\n========================================\n\nCode:\n```text\nimport { ApiProperty } from '@nestjs/swagger/';\nimport { IsString, IsUUID} from 'class-validator';\n\nimport { Client } from '../../../models';\nimport { User } from '../../../user.decorator';\n\n\nexport class ClientDTO implements Readonly<ClientDTO> {\n @ApiProperty({ required: true })\n @IsUUID()\n id: string;\n\n\n @ApiProperty({ required: true })\n @IsString()\n name: string;\n\n public static from(dto: Partial<ClientDTO>) {\n const cl = new ClientDTO();\n cl.id = dto.id;\n cl.name = dto.name;\n return cl;\n }\n\n public static fromEntity(entity: Client) {\n return this.from({\n id: entity.id,\n name: entity.name,\n });\n }\n\n public toEntity = (user: User | null) => {\n const cl = new Client();\n cl.id = this.id;\n cl.name = this.name;\n cl.createDateTime = new Date();\n cl.createdBy = user ? user.id : null;\n cl.lastChangedBy = user ? user.id : null;\n return cl;\n }\n }\n```\n\n```text\nimport { \n Body,\n Controller, \n Get, Post \n} from '@nestjs/common';\n\nimport { ClientDTO } from './dto/client.dto';\nimport { ClientService } from './client.service';\nimport { User } from 'src/user.decorator';\n\n@Controller('client')\nexport class ClientController {\n constructor(\n private clientService: ClientService\n ) { }\n\n @Get()\n public async getAllClients(): Promise<ClientDTO[]> {\n return this.clientService.getAllClients();\n }\n\n @Post()\n public async createClient(@User() user: User, @Body() dto: ClientDTO): Promise<ClientDTO> {\n return this.clientService.createClient(dto, user);\n }\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\n\nimport { Client } from '../../models';\nimport { ClientDTO } from './dto/client.dto';\nimport { User } from '../../user.decorator';\n\n\n@Injectable()\nexport class ClientService {\n constructor(\n @InjectRepository(Client) private readonly clientRepository: Repository<Client>\n ) {}\n\n public async getAllClients(): Promise<ClientDTO[]> {\n return await this.clientRepository.find()\n .then(clients => clients.map(e => ClientDTO.fromEntity(e)));\n }\n\n public async createClient(dto: ClientDTO, user: User): Promise<ClientDTO> {\n return this.clientRepository.save(dto.toEntity(user))\n .then(e => ClientDTO.fromEntity(e));\n }\n}\n```\n\n```text\nTypeError: dto.toEntity is not a function\n at ClientService.createClient (C:\\...\\nest-backend\\dist\\features\\client\\client.service.js:29:47)\n at ClientController.createClient (C:\\...\\nest-backend\\dist\\features\\client\\client.controller.js:27:35)\n at C:\\...\\nest-backend\\node_modules\\@nestjs\\core\\router\\router-execution-context.js:37:29\n at process._tickCallback (internal/process/next_tick.js:68:7)\n```\n\n```text\nimport * as _ from 'lodash';\n\nimport { Client } from '../models';\nimport { ClientDTO } from '../features/client/dto/client.dto';\nimport { ClientService } from '../features/client/client.service';\nimport { configService } from '../config/config.service';\nimport { createConnection, ConnectionOptions } from 'typeorm';\nimport { User } from '../user.decorator';\n\nasync function run() {\n\n const seedUser: User = { id: 'seed-user' };\n\n const seedId = Date.now()\n .toString()\n .split('')\n .reverse()\n .reduce((s, it, x) => (x > 3 ? s : (s += it)), '');\n\n const opt = {\n ...configService.getTypeOrmConfig(),\n debug: true\n };\n\n const connection = await createConnection(opt as ConnectionOptions);\n const clientService = new ClientService(connection.getRepository(Client));\n\n const work = _.range(1, 10).map(n => ClientDTO.from({\n name: `seed${seedId}-${n}`,\n }))\n######################## my service calls ClientDTO.toEntity() without issue ###########################\n .map(dto => clientService.createClient(dto, seedUser) \n .then(r => (console.log('done ->', r.name), r)))\n\n return await Promise.all(work);\n}\n\nrun()\n .then(_ => console.log('...wait for script to exit'))\n .catch(error => console.error('seed error', error));\n```\n\n```text\n/client\n```\n\n```text\n@Post()\npublic async createClient(@User() user: User, @Body() dto: ClientDTO): Promise<ClientDTO> {\n const client = ClientDTO.from(dto);\n return this.clientService.createClient(client, user);\n}\n```\n\n```text\ndto\n```\n\n```text\ndto: ClientDTO\n```\n\n```text\nClientDTO.from\n```\n\n```text\ndto\n```\n\n```text\nconstructor\n```\n\n```text\napp.useGlobalPipes(new ValidationPipe({\n transform: true\n}));\n```\n\n========================================\n\nComments:\n- your solution will not work because the object coming in to the route from the post is still just a generic object. In order for the \"from\" method to work, a new object has to be created from the class. Then the \"from\" method as it exists can work as long as it takes the plain object as a param.\n- this is just JavaScript behind, no types involved, you could write `constructor(obj?: any) { Object.assign(this, obj); }` in the DTO class, and then `const client = new ClientDTO(dto);`\n- The Ops post is based on a tutorial in Medium. This answer fixes it. Just add the above code to main.ts, and \"npm install class-transformer\" and you are good to go (at least on this issue)","metadata":{"transformedAt":"2026-08-18T18:33:44.714Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":13,"totalLines":383,"estimatedTokens":2533}}393{"id":"stack-73905987","source":"stackoverflow","questionId":73905987,"title":"TypeORM No metadata for \\\"MyEntity\\\" was found","tags":["postgresql","nestjs","datasource","typeorm"],"text":"Title: TypeORM No metadata for \\\"MyEntity\\\" was found\nTags: postgresql, nestjs, datasource, typeorm\nSource: Stack Overflow\n\nQuestion:\nI 1. have the following datasource on \"app-data-source.ts\"\n\n```\nimport { DataSource } from \"typeorm\";\nimport { App } from \"./entities/app\";\n\nexport const appDataSource = new DataSource({\n type: 'postgres',\n host: process.env.CONFIG_DB_HOST,\n port: 5432,\n username: process.env.CONFIG_DB_USER,\n password: process.env.CONFIG_DB_PASSWORD,\n database: process.env.CONFIG_DB_DATABASE,\n entities: [App],\n synchronize: false,\n});\n```\n\n- Which uses the entity App on \"entities/app.ts\"\n\n```\nimport { Column, Entity, PrimaryColumn } from \"typeorm\";\n\n@Entity('apps')\nexport class App {\n @PrimaryColumn()\n tenant_id: number;\n \n @Column()\n client_id: string;\n \n @Column()\n legacy_client_id: string;\n\n @Column()\n user_pool: string;\n}\n```\n\n- And the following module that queries the Entity **App**(Shown above on number 2).\n\n```\nimport { App } from './entities/app';\nimport { appDataSource } from './app-data-source';\n\nexport class AuthService {\n async getApp() {\n let tenant= await appDataSource.getRepository(App).findOneBy({\n client_id: clientId\n });\n }\n}\n```\n\nHowever I get the following Error.\n\n```\n{\n \"errorMessage\": \"No metadata for \\\"App\\\" was found.\",\n \"errorType\": \"EntityMetadataNotFoundError\",\n \"stackTrace\": [\n \"EntityMetadataNotFoundError: No metadata for \\\"App\\\" was found.\",\n \" at DataSource.getMetadata (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:181364:19)\",\n \" at get metadata [as metadata] (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:185119:40)\",\n \" at Repository.findOneBy (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:185312:44)\",\n \" at AuthService.getAccessToken (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:57451:89)\",\n \" at handler (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:32:27)\"\n ]\n}\n```\n\n========================================\n\nCode:\n```js\nimport { DataSource } from \"typeorm\";\nimport { App } from \"./entities/app\";\n\nexport const appDataSource = new DataSource({\n type: 'postgres',\n host: process.env.CONFIG_DB_HOST,\n port: 5432,\n username: process.env.CONFIG_DB_USER,\n password: process.env.CONFIG_DB_PASSWORD,\n database: process.env.CONFIG_DB_DATABASE,\n entities: [App],\n synchronize: false,\n});\n```\n\n```js\nimport { Column, Entity, PrimaryColumn } from \"typeorm\";\n\n@Entity('apps')\nexport class App {\n @PrimaryColumn()\n tenant_id: number;\n \n @Column()\n client_id: string;\n \n @Column()\n legacy_client_id: string;\n\n @Column()\n user_pool: string;\n}\n```\n\n```js\nimport { App } from './entities/app';\nimport { appDataSource } from './app-data-source';\n\nexport class AuthService {\n async getApp() {\n let tenant= await appDataSource.getRepository(App).findOneBy({\n client_id: clientId\n });\n }\n}\n```\n\n```json\n{\n \"errorMessage\": \"No metadata for \\\"App\\\" was found.\",\n \"errorType\": \"EntityMetadataNotFoundError\",\n \"stackTrace\": [\n \"EntityMetadataNotFoundError: No metadata for \\\"App\\\" was found.\",\n \" at DataSource.getMetadata (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:181364:19)\",\n \" at get metadata [as metadata] (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:185119:40)\",\n \" at Repository.findOneBy (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:185312:44)\",\n \" at AuthService.getAccessToken (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:57451:89)\",\n \" at handler (D:\\\\lami-accounts\\\\dist\\\\apps\\\\auth\\\\main.js:32:27)\"\n ]\n}\n```\n\n```js\n// initialize\nawait appDataSource.initialize();\nlet tenant= await appDataSource.getRepository(App).findOneBy({\n client_id: clientId\n}); \n\n// destroy the connection\nawait appDataSource.destroy()\n```\n\n```text\nappDataSource.initialize();\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.714Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":156,"estimatedTokens":948}}394{"id":"stack-67290780","source":"stackoverflow","questionId":67290780,"title":"Column X of relation Y contains null values","tags":["node.js","typescript","postgresql","nestjs","typeorm"],"text":"Title: Column X of relation Y contains null values\nTags: node.js, typescript, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nWhen inserting first admin into my database I get this error message and don't know how to solve it:\n\n```\n[Nest] 13803 - 04/27/2021, 23:03:02 [TypeOrmModule] Unable to connect to the database. Retrying (6)... +3176ms\nQueryFailedError: column \"name\" of relation \"admin\" contains null values\n```\n\nOther tables work just fine so far and without errors.\n\nColumn `name` in `admin` table is not null it contains value:\nhttps://i.sstatic.net/5RNII.png\n\nRegister service:\n\n```\nasync register(registerInput: RegisterInput): Promise {\n const { key, name, password, email } = registerInput;\n\n const hashedKey = createHash('sha256')\n .update(key)\n .digest('hex');\n\n const invite = await this.invitesRepository.findOne({ key: hashedKey });\n\n if (!invite) {\n throw new UnauthorizedException();\n }\n\n const newAdmin = await this.adminsRepository.create({\n name,\n password,\n email,\n });\n await this.adminsRepository.save(newAdmin);\n\n await this.invitesRepository.delete({ id: invite.id });\n }\n```\n\n========================================\n\nCode:\n```text\n[Nest] 13803 - 04/27/2021, 23:03:02 [TypeOrmModule] Unable to connect to the database. Retrying (6)... +3176ms\nQueryFailedError: column \"name\" of relation \"admin\" contains null values\n```\n\n```text\nasync register(registerInput: RegisterInput): Promise<void> {\n const { key, name, password, email } = registerInput;\n\n const hashedKey = createHash('sha256')\n .update(key)\n .digest('hex');\n\n const invite = await this.invitesRepository.findOne({ key: hashedKey });\n\n if (!invite) {\n throw new UnauthorizedException();\n }\n\n const newAdmin = await this.adminsRepository.create({\n name,\n password,\n email,\n });\n await this.adminsRepository.save(newAdmin);\n\n await this.invitesRepository.delete({ id: invite.id });\n }\n```\n\n```text\nname\n```\n\n```text\nadmin\n```\n\n```text\ndist\n```\n\n========================================\n\nComments:\n- what is the value of the prop `name` in `registerInput`?\n- I entered \"John Doe\" as displayed in table, but whatever value I input and however many admins I add the error doesn't go away.\n- Can you update the question with the related entity classes and the connection options you pass to connect to the database?\n- Also, try to delete your `dist` directory, rebuild the code and try again\n- This still works in 2022. I don't know why it's necessary, though. Added `rm -rf dist` in the `package.json` script for convenience.","metadata":{"transformedAt":"2026-08-18T18:33:44.714Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":97,"estimatedTokens":647}}395{"id":"stack-61755680","source":"stackoverflow","questionId":61755680,"title":"TypeORM doesn't return entire entity after calling .save() method","tags":["postgresql","typeorm"],"text":"Title: TypeORM doesn't return entire entity after calling .save() method\nTags: postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a simple entity:\n\n```\nimport { BaseEntity, Entity, Column, PrimaryGeneratedColumn, Timestamp } from 'typeorm';\n\n@Entity('organizations')\nexport class OrganizationEntity extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column('varchar', { length: 10 })\n uid: string;\n\n @Column('varchar', { length: 100 })\n name: string;\n\n @Column('varchar', { length: 100 })\n status: string;\n\n @Column('timestamp')\n createdAt: Timestamp;\n\n @Column('timestamp')\n updatedAt: Timestamp;\n\n @Column('timestamp')\n deletedAt: Timestamp;\n}\n```\n\nCreating a new entity:\n\n```\nconst organization = new OrganizationEntity();\norganization.name = 'someName';\norganization.status = 'someStatus';\nawait organization.save();\n```\n\nIn Postgres SQL looks like this:\n\n```\nINSERT INTO \"organizations\"(\"uid\", \"name\", \"status\", \"createdAt\", \"updatedAt\", \"deletedAt\") VALUES (DEFAULT, $1, $2, DEFAULT, DEFAULT, DEFAULT) RETURNING \"id\", \"status\"\n```\n\nAs can be seen it returns only filled fields in `RETURNING` statement.\nI know there are some workarounds by using query builder but I am concern is there any semantical way how I can return an entire entity after calling method `save` so there will be `RETURNING *`\nThanks in advance.\n\n========================================\n\nTop Answer:\nYou can use something like this until TypeORM fixes it:\n\n```\nconst user = await this.userRepository.findOne(id);\n// handle user not found\nconst updatedUser = await this.userRepository.save({ id, ...updateDto });\nreturn Object.assign(user, updatedUser);\n```\n\n========================================\n\nCode:\n```text\nimport { BaseEntity, Entity, Column, PrimaryGeneratedColumn, Timestamp } from 'typeorm';\n\n@Entity('organizations')\nexport class OrganizationEntity extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column('varchar', { length: 10 })\n uid: string;\n\n @Column('varchar', { length: 100 })\n name: string;\n\n @Column('varchar', { length: 100 })\n status: string;\n\n @Column('timestamp')\n createdAt: Timestamp;\n\n @Column('timestamp')\n updatedAt: Timestamp;\n\n @Column('timestamp')\n deletedAt: Timestamp;\n}\n```\n\n```text\nconst organization = new OrganizationEntity();\norganization.name = 'someName';\norganization.status = 'someStatus';\nawait organization.save();\n```\n\n```text\nINSERT INTO \"organizations\"(\"uid\", \"name\", \"status\", \"createdAt\", \"updatedAt\", \"deletedAt\") VALUES (DEFAULT, $1, $2, DEFAULT, DEFAULT, DEFAULT) RETURNING \"id\", \"status\"\n```\n\n```text\nRETURNING\n```\n\n```text\nsave\n```\n\n```text\nRETURNING *\n```\n\n```text\nconst user = await this.userRepository.findOne(id);\n// handle user not found\nconst updatedUser = await this.userRepository.save({ id, ...updateDto });\nreturn Object.assign(user, updatedUser);\n```\n\n========================================\n\nComments:\n- github.com/typeorm/typeorm/issues/3490\n- its the same case with me, i fetching the user using findOne and updating the property and calling .save() but the changes wont reflect in database i dont know why , i\"m using base entity and not repository","metadata":{"transformedAt":"2026-08-18T18:33:44.714Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":132,"estimatedTokens":795}}396{"id":"stack-69853812","source":"stackoverflow","questionId":69853812,"title":"Typeorm/Nestjs Raw query usage forcing lowercase to column name","tags":["sql","typescript","postgresql","nestjs","typeorm"],"text":"Title: Typeorm/Nestjs Raw query usage forcing lowercase to column name\nTags: sql, typescript, postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI need a help on executing a query using nest/typeorm;\n\nIm using Typeorm \"InjectConnection\" to build a raw query into my Postgres Database, the field giving me the error is the column user_roles_role.userId (note that I from userId is uppercase)\n\nHeres the code:\n\n```\nconst queryText = `SELECT * FROM user_roles_role WHERE user_roles_role.userId = ${id}`\n\ntry {\n const rawData = await this.connection.query(queryText);\n return rawData;\n} catch (err) {\n console.log(err);\n return err;\n}\n```\n\nI get an error while doing this query, because somehow Typeorm is forcing lowercase on the column name, as seen below on typeorm error (from catch(Err))\n\nquery: 'SELECT * FROM user_roles_role WHERE user_roles_role.userId =\n1', parameters: undefined, driverError: error: column\nuser_roles_role.userid does not exist\n\nI've tried:\n\nUsing single quotes and double quotes (didn't work)\n\nFull Error:\n\n\"query\": \"SELECT * FROM user_roles_role WHERE user_roles_role.userId = 1\",\n\"driverError\": {\n\"length\": 189,\n\"name\": \"error\",\n\"severity\": \"ERROR\",\n\"code\": \"42703\",\n\"hint\": \"Perhaps you meant to reference the column >\"user_roles_role.userId\".\",\n\"position\": \"37\",\n\"file\": \"parse_relation.c\",\n\"line\": \"3599\",\n\"routine\": \"errorMissingColumn\"\n}\n\n========================================\n\nCode:\n```text\nconst queryText = `SELECT * FROM user_roles_role WHERE user_roles_role.userId = ${id}`\n\ntry {\n const rawData = await this.connection.query(queryText);\n return rawData;\n} catch (err) {\n console.log(err);\n return err;\n}\n```\n\n```text\n`SELECT * FROM user_roles_role WHERE user_roles_role.\"userId\" = ${id}`\n```\n\n========================================\n\nComments:\n- Does not work, when I do this I get the following error: query: 'SELECT * FROM user_roles_role WHERE \"user_roles_role.userId\" = 1', parameters: undefined, driverError: error: column \"user_roles_role.userId\" does not exist, looks like Its a typeorm issue\n- SELECT * FROM user_roles_role where user_roles_role.\"userId\" = 1 worked, Ill accept the answer cuz it led me to this solution, thank you\n- yes you are right we should to the quotes only for the column, I'll update my answer for the others who need the solution, you're welcome","metadata":{"transformedAt":"2026-08-18T18:33:44.714Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":2,"totalLines":73,"estimatedTokens":584}}397{"id":"stack-73937450","source":"stackoverflow","questionId":73937450,"title":"TypeORM: column must appear in the GROUP BY clause or be used in an aggregate function","tags":["sql","node.js","postgresql","typeorm"],"text":"Title: TypeORM: column must appear in the GROUP BY clause or be used in an aggregate function\nTags: sql, node.js, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to work out why the following raw SQL works perfectly with PostGres, whereas the SQL generated via TypeORM does not.\n\nRunning this works:\n\n```\nSELECT symbol, MAX(created_at) AS created_at\nFROM update_history\nWHERE exchange = 'NYSE'\nAND data_type = 'companyRecord'\nGROUP BY symbol\nORDER BY created_at ASC\n```\n\nExample: https://dbfiddle.uk/yocl-rBq\n\nWhereas, the TypeORM sql generated by the following:\n\n```\nconst result = this.repository\n .createQueryBuilder('h1')\n .select(['MAX(h1.createdAt) AS created_at', 'h1.symbol'])\n .where('h1.exchange = :exchange', { exchange })\n .andWhere('h1.dataType = :dataType', { dataType })\n .groupBy('h1.symbol')\n .orderBy({ created_at: 'ASC' })\n .take(limit)\n .getMany();\n\n/* Produces this:\n\nSELECT \"h1\".\"symbol\" AS \"h1_symbol\", \n MAX(\"h1\".\"created_at\") AS created_at \nFROM \"update_history\" \"h1\" \nWHERE \"h1\".\"exchange\" = 'NYSE'\nAND \"h1\".\"data_type\" = 'companyRecord' \nGROUP BY \"h1\".\"symbol\" \nORDER BY created_at ASC LIMIT 5000\n*/\n```\n\nExample (second select box): https://dbfiddle.uk/yocl-rBq\n\nReturns the following error:\n\nQueryFailedError: column \"h1.id\" must appear in the GROUP BY clause or be used in an aggregate function\n\nIf I add `h1.id` to the `GROUP BY` clause, the query no longer returns the correct result set, as it is effectively different.\n\nAs you can see from the DBFiddle links, both generated SQL queries work outside of TypeORM.\n\nWhat am I missing here?\n\n========================================\n\nCode:\n```sql\nSELECT symbol, MAX(created_at) AS created_at\nFROM update_history\nWHERE exchange = 'NYSE'\nAND data_type = 'companyRecord'\nGROUP BY symbol\nORDER BY created_at ASC\n```\n\n```js\nconst result = this.repository\n .createQueryBuilder('h1')\n .select(['MAX(h1.createdAt) AS created_at', 'h1.symbol'])\n .where('h1.exchange = :exchange', { exchange })\n .andWhere('h1.dataType = :dataType', { dataType })\n .groupBy('h1.symbol')\n .orderBy({ created_at: 'ASC' })\n .take(limit)\n .getMany();\n\n/* Produces this:\n\nSELECT \"h1\".\"symbol\" AS \"h1_symbol\", \n MAX(\"h1\".\"created_at\") AS created_at \nFROM \"update_history\" \"h1\" \nWHERE \"h1\".\"exchange\" = 'NYSE'\nAND \"h1\".\"data_type\" = 'companyRecord' \nGROUP BY \"h1\".\"symbol\" \nORDER BY created_at ASC LIMIT 5000\n*/\n```\n\n```text\nh1.id\n```\n\n```text\nGROUP BY\n```\n\n```text\ngetMany()\n```\n\n```text\nid\n```\n\n```text\nselect\n```\n\n```text\ngetMany()\n```\n\n```text\nlogging: true\n```\n\n```text\normconfig.js\n```\n\n```text\ngetRawMany()\n```\n\n========================================\n\nComments:\n- What is h1.id ? I could not find it inside of your query select part.\n- It's an alias generated by TypeORM, it's specified here, createQueryBuilder('h1')\n- Ahh got it, ok many thanks. I'm trying to avoid getRawMany() as that means I'll have to map the result to an entity myself. Is there anything I can change to make getMany() work?\n- No. `getMany` always adds primary key to your query. The query that you’re doing is not even mapping to your entity at least logically. Why do you want to map this to your entity class? Let’s say, even if you do it manually, you might mistake `MAX(created_at)` with `created_at` some point later in your code.\n- OK got it, thanks! The reason being, my entities are using camelCase, whereas the table fields use snake_case. I'll just manually map the casing myself.\n- Sweet. You save my day","metadata":{"transformedAt":"2026-08-18T18:33:44.714Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":137,"estimatedTokens":868}}398{"id":"stack-64763402","source":"stackoverflow","questionId":64763402,"title":"typeorm add index on jsonb column property","tags":["typescript","postgresql","typeorm"],"text":"Title: typeorm add index on jsonb column property\nTags: typescript, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a table which has a `jsonb` column named `asset`. The record in this column has a field called `value`. I am looking for an option to create index of `asset.value` but unable to find it. Can someone help me out here? I am using `typeorm`.\n\nThanks\n\n========================================\n\nCode:\n```text\njsonb\n```\n\n```text\nasset\n```\n\n```text\nvalue\n```\n\n```text\nasset.value\n```\n\n```text\ntypeorm\n```\n\n```text\nCREATE TABLE test(id int, data JSONB, PRIMARY KEY (id));\n```\n\n```text\nCREATE INDEX datagin ON books USING gin (data);\n```\n\n```text\nselect * from books where data @> '{\"braille\":true}'::jsonb;\n```\n\n```text\nconst rawData = await manager.query(`select * from books where data @> '{\"braille\":true}'::jsonb`);\n```\n\n```text\nCREATE INDEX\n```\n\n```text\nDROP INDEX\n```\n\n```text\nup()\n```\n\n```text\ndown()\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.714Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":63,"estimatedTokens":233}}399{"id":"stack-57412880","source":"stackoverflow","questionId":57412880,"title":"How to remove dashes (-) in autogenerated UUID - typeorm","tags":["typeorm"],"text":"Title: How to remove dashes (-) in autogenerated UUID - typeorm\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI am using UUID as primary key for my entity and it works just fine. But I wish to remove those dashes.\n\nNow ids are saved as `8e5365f4-3d42-4274-bafc-93b97bd6e3f2` **36 characters**\n\nAnd what I want is `8e5365f43d424274bafc93b97bd6e3f2` **32 characters**\n\nI dont see any option of using transformer in `@PrimaryGeneratedColumn('uuid')` is there a simple way to archive this?\n\n========================================\n\nTop Answer:\nInstead of using `@PrimaryGeneratedColumn`, you could use `@PrimaryColumn` with `generated: \"uuid\"` and specify a transformer:\n\n```\nconst removeDashes: ValueTransformer = {\n from: (str: string | null | undefined) => str != null ? str.replace(/-/g, \"\") : str,\n to: (str: string | null | undefined) => str != null ? str.replace(/-/g, \"\") : str,\n};\n\n@Entity()\nexport class SomeEntity {\n @PrimaryColumn({ type: \"uuid\", generated: \"uuid\", transformer: removeDashes })\n id: string;\n}\n```\n\nTheoretically that should work with databases other than postgres (perhaps with some minor adjustments).\n\nBut if you *are* using postgres, and your column is the built-in `uuid` type, the dashes that you see in the UUID are not actually stored in the database. Instead, they're stored as a 128-bit integer, and postgres converts it to a human-readable format (with dashes) for display when needed. Postgres accepts UUID input in a variety of formats, both with and without dashes. (See https://www.postgresql.org/docs/11/datatype-uuid.html)\n\nSince postgres is so flexible with input, you don't need to strip the dashes when sending a UUID to postgres if you're using the `uuid` type:\n\n```\nconst removeDashesPostgres: ValueTransformer = {\n from: (str: string | null | undefined) => str != null ? str.replace(/-/g, \"\") : str,\n to: (str: string | null | undefined) => str,\n};\n```\n\nWhen typeorm transforms query results into the entity, the transformer will strip the dashes from the string representation of your UUID, so you always \"see\" the dash-less UUIDs in your objects. When typeorm transforms an entity into a query to save/update/etc., it passes through the string representation of the UUID to the database as-is, and postgres converts it to its own `uuid` thanks to its extreme input tolerance.\n\nFor completeness, the `id` column in the table in these postgres examples is defined as:\n\n```\nid uuid NOT NULL PRIMARY KEY DEFAULT uuid_generate_v4()\n```\n\n========================================\n\nCode:\n```text\n8e5365f4-3d42-4274-bafc-93b97bd6e3f2\n```\n\n```text\n8e5365f43d424274bafc93b97bd6e3f2\n```\n\n```text\n@PrimaryGeneratedColumn('uuid')\n```\n\n```text\nelse if (column.isGenerated && column.generationStrategy === \"uuid\" && !this.connection.driver.isUUIDGenerationSupported() && value === undefined) {\n\n const paramName = \"uuid_\" + column.databaseName + valueSetIndex;\n value = RandomGenerator.uuid4();\n this.expressionMap.nativeParameters[paramName] = value;\n expression += this.connection.driver.createParameter(paramName, parametersCount);\n parametersCount++;\n\n // if value for this column was not provided then insert default value\n }\n```\n\n```text\nimport { BeforeInsert, Entity, PrimaryColumn } from 'typeorm';\nimport { v4 as uuid4 } from 'uuid';\n\n@Entity({})\nexport class User {\n @PrimaryColumn()\n uuid: string;\n\n @BeforeInsert()\n generateUuid() {\n this.uuid = uuid4().replace(/-/g, '');\n }\n}\n```\n\n```js\nconst removeDashes: ValueTransformer = {\n from: (str: string | null | undefined) => str != null ? str.replace(/-/g, \"\") : str,\n to: (str: string | null | undefined) => str != null ? str.replace(/-/g, \"\") : str,\n};\n\n@Entity()\nexport class SomeEntity {\n @PrimaryColumn({ type: \"uuid\", generated: \"uuid\", transformer: removeDashes })\n id: string;\n}\n```\n\n```js\nconst removeDashesPostgres: ValueTransformer = {\n from: (str: string | null | undefined) => str != null ? str.replace(/-/g, \"\") : str,\n to: (str: string | null | undefined) => str,\n};\n```\n\n```sql\nid uuid NOT NULL PRIMARY KEY DEFAULT uuid_generate_v4()\n```\n\n```text\n@PrimaryGeneratedColumn\n```\n\n```text\n@PrimaryColumn\n```\n\n```text\ngenerated: \"uuid\"\n```\n\n```text\nuuid\n```\n\n```text\nuuid\n```\n\n```text\nuuid\n```\n\n```text\nid\n```\n\n========================================\n\nComments:\n- REPLACE(UUID(),'-','') or uuid().replace(/-/g, '')\n- @Treewallie how to use that in typeorm entity?","metadata":{"transformedAt":"2026-08-18T18:33:44.714Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":153,"estimatedTokens":1138}}400{"id":"stack-60753807","source":"stackoverflow","questionId":60753807,"title":"NestJS custom decorator returns undefined","tags":["typescript","nestjs","typeorm"],"text":"Title: NestJS custom decorator returns undefined\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nGood morning,\n\nI'm trying to create a custom decorator:\n`user.decorator.ts`\n\n```\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const User = createParamDecorator(\n (data: string, ctx: ExecutionContext) => {\n const request = ctx.switchToHttp().getRequest();\n const user = request.user;\n\n return data ? user && user[data] : user;\n },\n);\n```\n\n`user.entity.ts`\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column, BeforeInsert } from \"typeorm\";\nimport * as bcrypt from 'bcryptjs';\nimport * as jwt from 'jsonwebtoken';\nimport { UserRO } from \"./user.dto\";\n\n@Entity(\"user\")\nexport class UserEntity {\n\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column({\n type: 'varchar',\n length: 50,\n unique: true,\n })\n username: string;\n\n @Column('text')\n password: string;\n\n @Column('text')\n role: string;\n\n (...)\n}\n```\n\nAnd finally, `user.controller.ts` (only the useful part):\n\n```\n(...)\n @Post('login')\n @UsePipes(new ValidationPipe())\n login(@Body() data: UserDTO, @User('role') role: string) {\n console.log(`hello ${role}`);\n return this.userService.login(data);\n(...)\n }\n```\n\nMy problem: console.log(...) returns me `hello undefined`, when the expected response should be `hello admin` (as admin is the role of the user in the database)\n\nEDIT: I also tried to `console.log(user)` in my decorator and it is undefined too.\n\nEDIT2: My HttpErrorFilter also says: `Cannot read property 'role' of undefined`\n\nI followed closely the documentation and I can't figure out where the problem is (https://docs.nestjs.com/custom-decorators).\n\nThank you for your time.\n\n========================================\n\nTop Answer:\nI found a solution.\n\nIn `user.decorator.ts`:\n\nChange `const user = request.user;` with `const user = request.body;`\n\nAccording to nestjs's doc, it should be `.user` but when I looked deeper into the request, I noticed there were no 'user' but a 'body' with all in the informations. (https://docs.nestjs.com/custom-decorators)\n\nCan't tell if I messed up earlier or if the doc is just outdated.\n\nProblem solved whatsoever !\n\nEDIT: 2nd solution:\n\nI forgot to use `@UseGuards(new AuthGuard())` on top, and the `request.user` is created with the AuthGuard..\n\n========================================\n\nCode:\n```text\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const User = createParamDecorator(\n (data: string, ctx: ExecutionContext) => {\n const request = ctx.switchToHttp().getRequest();\n const user = request.user;\n\n return data ? user && user[data] : user;\n },\n);\n```\n\n```text\nimport { Entity, PrimaryGeneratedColumn, Column, BeforeInsert } from \"typeorm\";\nimport * as bcrypt from 'bcryptjs';\nimport * as jwt from 'jsonwebtoken';\nimport { UserRO } from \"./user.dto\";\n\n@Entity(\"user\")\nexport class UserEntity {\n\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @Column({\n type: 'varchar',\n length: 50,\n unique: true,\n })\n username: string;\n\n @Column('text')\n password: string;\n\n @Column('text')\n role: string;\n\n (...)\n}\n```\n\n```text\n(...)\n @Post('login')\n @UsePipes(new ValidationPipe())\n login(@Body() data: UserDTO, @User('role') role: string) {\n console.log(`hello ${role}`);\n return this.userService.login(data);\n(...)\n }\n```\n\n```text\nuser.decorator.ts\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nuser.controller.ts\n```\n\n```text\nhello undefined\n```\n\n```text\nhello admin\n```\n\n```text\nconsole.log(user)\n```\n\n```text\nCannot read property 'role' of undefined\n```\n\n```typescript\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const CurrentUser = createParamDecorator(\n (data: unknown, ctx: ExecutionContext) => {\n return ctx.getArgByIndex(2).req.user;\n }\n);\n```\n\n```text\nconst request = ctx.switchToHttp().getRequest();\n```\n\n```text\ngetRequest()\n```\n\n```text\ngetArgByIndex()\n```\n\n```text\nuser.decorator.ts\n```\n\n```text\nconst user = request.user;\n```\n\n```text\nconst user = request.body;\n```\n\n```text\n.user\n```\n\n```text\n@UseGuards(new AuthGuard())\n```\n\n```text\nrequest.user\n```\n\n```text\nexport const CurrentUser = createParamDecorator(\n (data: unknown, context: ExecutionContext) => {\n const ctx = GqlExecutionContext.create(context);\n return ctx.getContext().req.user;\n },\n);\n```\n\n```text\nif (ctx.getType() == 'http') {\n return ctx.switchToHttp().getRequest().user;\n} else {\n const gqlContext = GqlExecutionContext.create(ctx);\n return gqlContext.getContext().user;\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.714Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":22,"totalLines":243,"estimatedTokens":1151}}401{"id":"stack-72721207","source":"stackoverflow","questionId":72721207,"title":"Running migrations with `useFactory`","tags":["typeorm","nest"],"text":"Title: Running migrations with `useFactory`\nTags: typeorm, nest\nSource: Stack Overflow\n\nQuestion:\nI have the app in `nestjs` with the `app.module.ts` containing the following configuration:\n\n```\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport {\n TypeOrmModuleAsyncOptions,\n TypeOrmModuleOptions,\n} from '@nestjs/typeorm';\nimport { DataSource } from 'typeorm'; \n\nexport const typeOrmAsyncConfig: TypeOrmModuleAsyncOptions = {\n imports: [ConfigModule],\n inject: [ConfigService],\n name: 'nameA',\n useFactory: (configService: ConfigService) => ({\n type: 'postgres',\n host: configService.get('DB_HOST'),\n port: parseInt(configService.get('DB_PORT') || '5432'),\n username: configService.get('DB_USER'),\n password: configService.get('DB_PASSWORD'),\n database: configService.get('DB_NAME'),\n entities: [__dirname + './../**/*.entity{.ts,.js}'],\n migrations: [__dirname + '/../database/migrations/*{.ts,.js}'],\n synchronize: false,\n cli: {\n entitiesDir: __dirname + './../**/*.entity{.ts,.js}',\n },\n ssl: configService.get('DB_SSL') === 'true',\n }),\n};\n\n@Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n TypeOrmModule.forRootAsync(typeOrmAsyncConfig),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\nI have `typeorm` installed globally and have migration files generated in the specified paths above, but, I get a `dataSource` not found error.\n\n`typeorm migration:run` output:\n\n```\nRuns all pending migrations.\n\nOptions:\n -h, --help Show help [boolean]\n -d, --dataSource Path to the file where your DataSource instance is defined.\n [required]\n -t, --transaction Indicates if transaction should be used or not for\n migration run. Enabled by default. [default: \"default\"]\n -v, --version Show version number [boolean]\n\nMissing required argument: dataSource\n```\n\nHow do I export a datasource when I'm using the `useFactory` inside of the `app.module.ts` and solve this issue?\n\n========================================\n\nTop Answer:\nFor migration up there seems to be a convenient way, but, since the answer is partial, I'm not marking it done:\n\n```\n{\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: (configService: ConfigService) => ({\n type: 'postgres',\n host: configService.get('DB_HOST'),\n port: parseInt(configService.get('DB_PORT') || '4432'),\n username: configService.get('DB_USER'),\n password: configService.get('DB_PASSWORD'),\n database: configService.get('DB_NAME'),\n entities: [MyEntity],\n migrations: ['./**/*.migration.js'],\n synchronize: false,\n ssl: configService.get('DB_SSL') === 'true',\n }),\n dataSourceFactory: async (options: DataSourceOptions) => {\n const dataSource = await new DataSource(options).initialize();\n await dataSource.runMigrations();\n \n return dataSource;\n },\n }\n```\n\nIf new migrations are added, they should be applied since the server is restarted.\n\n========================================\n\nCode:\n```js\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport {\n TypeOrmModuleAsyncOptions,\n TypeOrmModuleOptions,\n} from '@nestjs/typeorm';\nimport { DataSource } from 'typeorm'; \n\nexport const typeOrmAsyncConfig: TypeOrmModuleAsyncOptions = {\n imports: [ConfigModule],\n inject: [ConfigService],\n name: 'nameA',\n useFactory: (configService: ConfigService) => ({\n type: 'postgres',\n host: configService.get('DB_HOST'),\n port: parseInt(configService.get('DB_PORT') || '5432'),\n username: configService.get('DB_USER'),\n password: configService.get('DB_PASSWORD'),\n database: configService.get('DB_NAME'),\n entities: [__dirname + './../**/*.entity{.ts,.js}'],\n migrations: [__dirname + '/../database/migrations/*{.ts,.js}'],\n synchronize: false,\n cli: {\n entitiesDir: __dirname + './../**/*.entity{.ts,.js}',\n },\n ssl: configService.get('DB_SSL') === 'true',\n }),\n};\n\n@Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n TypeOrmModule.forRootAsync(typeOrmAsyncConfig),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nRuns all pending migrations.\n\nOptions:\n -h, --help Show help [boolean]\n -d, --dataSource Path to the file where your DataSource instance is defined.\n [required]\n -t, --transaction Indicates if transaction should be used or not for\n migration run. Enabled by default. [default: \"default\"]\n -v, --version Show version number [boolean]\n\nMissing required argument: dataSource\n```\n\n```text\nnestjs\n```\n\n```text\napp.module.ts\n```\n\n```text\ntypeorm\n```\n\n```text\ndataSource\n```\n\n```text\ntypeorm migration:run\n```\n\n```text\nuseFactory\n```\n\n```text\napp.module.ts\n```\n\n```js\nimport 'dotenv/config';\n import { DataSourceOptions } from 'typeorm';\n \n const databaseConfig: DataSourceOptions = {\n name: 'default',\n type: 'better-sqlite3',\n database: process.env.DB_NAME,\n entities: [__dirname + '/../entities/*.entity.ts'],\n migrations: [__dirname + '/../migrations/*{.ts,.js}'],\n synchronize: false,\n logging: true,\n migrationsRun: true\n };\n \n export default databaseConfig;\n```\n\n```js\nimport { DataSource } from 'typeorm';\n import databaseConfig from './database-config';\n \n export const AppDataSource = new DataSource(databaseConfig);\n```\n\n```js\nimport { ConfigModule, ConfigService } from '@nestjs/config';\n import {\n TypeOrmModuleAsyncOptions,\n TypeOrmModuleOptions,\n } from '@nestjs/typeorm';\n import databaseConfig from './database-config';\n \n export const typeOrmConfig: TypeOrmModuleOptions = databaseConfig;\n \n export const typeOrmAsyncConfig: TypeOrmModuleAsyncOptions = {\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: async (): Promise<TypeOrmModuleOptions> => {\n return databaseConfig;\n },\n };\n```\n\n```json\n{\n \"typeorm:cli\": \"ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli -d src/config/data-source.ts\",\n \"migration:generate\": \"yarn run typeorm:cli migration:generate\",\n \"migration:create\": \"yarn run typeorm:cli migration:create\",\n \"migration:run\": \"yarn run typeorm:cli migration:run\",\n \"migration:revert\": \"yarn run typeorm:cli migration:revert\"\n }\n```\n\n```text\nyarn run migration:generate src/migrations/newMigrationName\n```\n\n```text\nsrc/config/database-config.ts\n```\n\n```text\nsrc/config/data-source.ts\n```\n\n```text\nsrc/config/typeorm-config.ts\n```\n\n```text\nlike so: TypeOrmModule.forRootAsync(typeOrmAsyncConfig)\n```\n\n```js\n{\n imports: [ConfigModule],\n inject: [ConfigService],\n useFactory: (configService: ConfigService) => ({\n type: 'postgres',\n host: configService.get('DB_HOST'),\n port: parseInt(configService.get('DB_PORT') || '4432'),\n username: configService.get('DB_USER'),\n password: configService.get('DB_PASSWORD'),\n database: configService.get('DB_NAME'),\n entities: [MyEntity],\n migrations: ['./**/*.migration.js'],\n synchronize: false,\n ssl: configService.get('DB_SSL') === 'true',\n }),\n dataSourceFactory: async (options: DataSourceOptions) => {\n const dataSource = await new DataSource(options).initialize();\n await dataSource.runMigrations();\n \n return dataSource;\n },\n }\n```\n\n========================================\n\nComments:\n- my question is why are we using ts-node to run the migrations ? Usually ts-node is a dev-dependency\n- typeorm-cli itself has 3 binaries as typeorm, typeorm-ts-node-commonjs, typeorm-ts-node-esm. For some reason it is the only way I managed to make it work. I would be happy to learn alternative too.\n- I actually had tried creating the datasource as above, but then it errored saying that it was not initialized\n- @juztcode you mean cli right? I have just confirmed this way works. make sure datasource export same way and same name. export const AppDataSource = new DataSource(databaseConfig);\n- hm... it seems to work after I added the glob pattern: `migrations: ['./**/*.migration.js']`\n- I've mentioned an approach for up migrations , yet a suitable place to manually trigger down is somewhat tricky\n- @juztcode both glob pattern or importing Entity Classes work fine. but they will disable the glob pattern in the next version.\n- not to bother you, but, I wonder if you know something about this as well: stackoverflow.com/questions/72778191/…\n- hello, question does anyone of you having issue when trying to access env variables? I'm getting undefined even those I import `dotenv/config` just like on the answer.\n- @aRtoo check your env file. Dotenv looks for \".env\" file in the root directory. If you want to put it in another place, for example: import * as dotenv from 'dotenv'; dotenv.config({ path: __dirname + '/../../myenv.env' });\n- @linusw that's what I thought. I changed my env file name from \".development.env\" to \".env\" and it worked and downloaded the dotenv package. but I'm confused because nest already using dotenv. I don't want to download or duplicate it.\n- @aRtoo yes nestjs depends on dotenv so you don't need to redownload. If you use npm or yarn, dotenv is already available to import. pnpm needs \"pnpm add dotenv\" command but doesn't download just creates link to the previous download.\n- this is the equivalent of migrationsRun: true, I had deleted it temporarily in my config. Edited now. Good catch. Although some could prefer \"synchronize:true\" while developing too. and my code works without defining dataSourceFactory property or initializing manually.\n- hm... this is but different than `synchronize:true` though as it should probably run only when you'd merge in the migrations file into the deployed branch\n- yes, I am not saying it is a drop in alternative. I assume developer would know what to modify my code to their needs. My solution is just intended as to make the new cli work in the absence of global ormconfig\n- @linusw , do you know if we can use the entity itself for migration?\n- I don't know what exactly you mean by \"entity itself\" only way I know is you can pass entity class to queryRunner.manager in migration files.\n- @linusw , do you happen to have a link or sth to an example that does that?\n- medium.com/@emfelipe/… it is outdated but queryrunner api still works like in this link. I use this method to seed database. Basically create another migrations folder as \"seeds\". put it in a datasource configuration as migrations. You should check queryRunner.manager (EntityManager) api documentation too. typeorm.io/entity-manager-api\n- I did try out the EntityManager api , with something like this: `queryRunner.manager.create()` yet it throws error saying no metadata, it doesn't seem like we can create the whole table in postgres with just the entity defined in nest\n- apparently you haven't read the whole queryrunner documentation. creating and altering tables done through either generated migrations or functions like queryRunner.createTable, queryRunner.addColumn. queryRunner.manager shines best at inserting or bulk inserting. typeorm.io/migrations#using-migration-api-to-write-migration‌​s I don't know what editor you use but I suggest something you can use LSP server-typescript addon. VS Code or Sublime Text. Typeorm already have documentation in the source code you can read by just hovering on code this way.\n- by the way metadata error can be result of wrong entities configuration in the datasource. You can try importing Entity Classes and put in the array if you haven't done already.","metadata":{"transformedAt":"2026-08-18T18:33:44.714Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":19,"totalLines":308,"estimatedTokens":2924}}402{"id":"stack-73019162","source":"stackoverflow","questionId":73019162,"title":"NestJS TypeORM mock a datasource of a repository","tags":["typescript","jestjs","nestjs","typeorm"],"text":"Title: NestJS TypeORM mock a datasource of a repository\nTags: typescript, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to mock out a repository. I don't want to do actual database calls. I (think I) am following the documentation on NestJS, and certain stackoverflow items.\n\nHowever, when I run the test I get the following error:\n\n```\nJwtStrategy › validate › throws an unauthorized exception as user cannot be found\nNest can't resolve dependencies of the UserEntityRepository (?). Please make sure that the argument DataSource at index [0] is available in the TypeOrmModule context.\n\nPotential solutions:\n- If DataSource is a provider, is it part of the current TypeOrmModule?\n- If DataSource is exported from a separate @Module, is that module imported within TypeOrmModule?\n @Module({\n imports: [ /* the Module containing DataSource */ ]\n })\n```\n\nNow as I understand, it seems that the UserEntityRepository is not properly mocked. As it is the first (index [0]) dependency in the user service class:\n\n**./user.service.ts**\n\n```\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(UserEntity)\n private userRepository: Repository\n ) {}\n\n async findOneBy({ username }): Promise {\n return await this.userRepository.findOneBy({ username })\n }\n}\n```\n\n**./jwt.strategy.ts**\n\n```\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(\n private userService: UserService,\n ) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: process.env.JWT_SECRET || config.get('jwt.secret'),\n })\n }\n\n async validate(payload: JwtPayload) {\n const { username } = payload;\n const user = await this.userService.findOneBy({username});\n\n if (!user) {\n throw new UnauthorizedException();\n }\n\n return user;\n }\n}\n```\n\n**./jwt.strategy.spect.ts**\n\n```\nconst mockUserRepositoryFactory = jest.fn(() => ({\n findOneBy: jest.fn(entity => entity),\n}));\n\ndescribe('JwtStrategy', () => {\n let jwtStrategy: JwtStrategy;\n let userService;\n\n beforeEach(async () => {\n const module = await Test.createTestingModule({\n imports: [UserModule],\n providers: [\n JwtStrategy,\n UserService,\n // shouldn't this correctly provide the datasource?\n {\n provide: getRepositoryToken(UserEntity),\n useFactory: mockUserRepositoryFactory,\n },\n\n ]\n }).compile();\n\n jwtStrategy = await module.get(JwtStrategy);\n userService = await module.get(UserService);\n });\n\n describe('validate', () => {\n it('validates and returns user based on JWT payload', async () => {\n const user = new UserEntity();\n user.username = 'TestUser';\n\n userService.findOneBy.mockResolvedValue(user);\n const result = await jwtStrategy.validate({ username: 'TestUser' });\n expect(userService.findOneBy).toHaveBeenCalledWith({ username: 'TestUser' });\n expect(result).toEqual(user);\n });\n\n it('throws an unauthorized exception as user cannot be found', async () => {\n userService.findOneBy.mockResolvedValue(null);\n expect(jwtStrategy.validate({ username: 'TestUser' })).rejects.toThrow(UnauthorizedException);\n });\n });\n});\n```\n\n**===== Update**\n\nCreated a minimal setup in a Codesandbox.\n\nhttps://codesandbox.io/s/xenodochial-benz-kve4eq?file=/test/jwt.test.js\n\nBut somehow the test tab isn't showing in the sandbox.\n\n========================================\n\nTop Answer:\nI have noticed that you are calling `findOneBy` in your service but mocked the `findOne` repository method.\n\nEither you have to mock the `findOne` method of your service or `findOneBy` of your repository. In the current approach, you mock the repository. The solution for this use case would look like this:\n\n```\nconst mockUserRepositoryFactory = jest.fn(() => ({\n // Change here from findOne to findOneBy\n findOneBy: jest.fn(entity => entity),\n}));\n\ndescribe('JwtStrategy', () => {\n let jwtStrategy: JwtStrategy;\n let userService;\n\n beforeEach(async () => {\n const module = await Test.createTestingModule({\n imports: [UserModule],\n providers: [\n JwtStrategy,\n UserService, {\n provide: getRepositoryToken(UserEntity),\n useFactory: mockUserRepositoryFactory,\n },\n\n ]\n }).compile();\n\n jwtStrategy = await module.get(JwtStrategy);\n userService = await module.get(UserService);\n });\n\n describe('validate', () => {\n it('validates and returns user based on JWT payload', async () => {\n const user = new UserEntity();\n user.username = 'TestUser';\n\n // change findOne to findOneBy here as well\n userService.findOneBy.mockResolvedValue(user);\n const result = await jwtStrategy.validate({ username: 'TestUser' });\n expect(userService.findOneBy).toHaveBeenCalledWith({ username: 'TestUser' });\n expect(result).toEqual(user);\n });\n\n it('throws an unauthorized exception as user cannot be found', async () => {\n userService.findOneBy.mockResolvedValue(null);\n expect(jwtStrategy.validate({ username: 'TestUser' })).rejects.toThrow(UnauthorizedException);\n });\n });\n});\n```\n\n========================================\n\nCode:\n```text\nJwtStrategy › validate › throws an unauthorized exception as user cannot be found\nNest can't resolve dependencies of the UserEntityRepository (?). Please make sure that the argument DataSource at index [0] is available in the TypeOrmModule context.\n\nPotential solutions:\n- If DataSource is a provider, is it part of the current TypeOrmModule?\n- If DataSource is exported from a separate @Module, is that module imported within TypeOrmModule?\n @Module({\n imports: [ /* the Module containing DataSource */ ]\n })\n```\n\n```js\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(UserEntity)\n private userRepository: Repository<UserEntity>\n ) {}\n\n async findOneBy({ username }): Promise<UserEntity> {\n return await this.userRepository.findOneBy({ username })\n }\n}\n```\n\n```js\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(\n private userService: UserService,\n ) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: process.env.JWT_SECRET || config.get('jwt.secret'),\n })\n }\n\n async validate(payload: JwtPayload) {\n const { username } = payload;\n const user = await this.userService.findOneBy({username});\n\n if (!user) {\n throw new UnauthorizedException();\n }\n\n return user;\n }\n}\n```\n\n```js\nconst mockUserRepositoryFactory = jest.fn(() => ({\n findOneBy: jest.fn(entity => entity),\n}));\n\ndescribe('JwtStrategy', () => {\n let jwtStrategy: JwtStrategy;\n let userService;\n\n beforeEach(async () => {\n const module = await Test.createTestingModule({\n imports: [UserModule],\n providers: [\n JwtStrategy,\n UserService,\n // shouldn't this correctly provide the datasource?\n {\n provide: getRepositoryToken(UserEntity),\n useFactory: mockUserRepositoryFactory,\n },\n\n ]\n }).compile();\n\n jwtStrategy = await module.get<JwtStrategy>(JwtStrategy);\n userService = await module.get<UserService>(UserService);\n });\n\n describe('validate', () => {\n it('validates and returns user based on JWT payload', async () => {\n const user = new UserEntity();\n user.username = 'TestUser';\n\n userService.findOneBy.mockResolvedValue(user);\n const result = await jwtStrategy.validate({ username: 'TestUser' });\n expect(userService.findOneBy).toHaveBeenCalledWith({ username: 'TestUser' });\n expect(result).toEqual(user);\n });\n\n it('throws an unauthorized exception as user cannot be found', async () => {\n userService.findOneBy.mockResolvedValue(null);\n expect(jwtStrategy.validate({ username: 'TestUser' })).rejects.toThrow(UnauthorizedException);\n });\n });\n});\n```\n\n```text\nimport { DataSource } from \"typeorm\";\n\n// @ts-ignore\nexport const dataSourceMockFactory: () => MockType<DataSource> = jest.fn(() => ({\n <mock_function>: jest.fn(),\n}));\n\nexport type MockType<T> = {\n [P in keyof T]?: jest.Mock<{}>;\n};\n```\n\n```text\ndescribe('---MSG---', () => {\n...\n let dataSourceMock: MockType<DataSource>\n...\n beforeAll(async () => {\n const module = await Test.createTestingModule({\n imports: [],\n controllers: [<CONTROLLERS>],\n providers: [ <PROVIDERS>\n { provide: DataSource, useFactory: dataSourceMockFactory }],\n }).compile()\n...\n dataSourceMock = module.get(DataSource);\n...\n })\n\n describe('---MSG---', () => {\n it('---MSG---', async () => {\n await <Call mock function>\n expect(dataSourceMock.<DataSource mocked function>).toBeCalled();\n });\n })\n```\n\n```text\nconst mockUserRepositoryFactory = jest.fn(() => ({\n // Change here from findOne to findOneBy\n findOneBy: jest.fn(entity => entity),\n}));\n\ndescribe('JwtStrategy', () => {\n let jwtStrategy: JwtStrategy;\n let userService;\n\n beforeEach(async () => {\n const module = await Test.createTestingModule({\n imports: [UserModule],\n providers: [\n JwtStrategy,\n UserService, {\n provide: getRepositoryToken(UserEntity),\n useFactory: mockUserRepositoryFactory,\n },\n\n ]\n }).compile();\n\n jwtStrategy = await module.get<JwtStrategy>(JwtStrategy);\n userService = await module.get<UserService>(UserService);\n });\n\n describe('validate', () => {\n it('validates and returns user based on JWT payload', async () => {\n const user = new UserEntity();\n user.username = 'TestUser';\n\n // change findOne to findOneBy here as well\n userService.findOneBy.mockResolvedValue(user);\n const result = await jwtStrategy.validate({ username: 'TestUser' });\n expect(userService.findOneBy).toHaveBeenCalledWith({ username: 'TestUser' });\n expect(result).toEqual(user);\n });\n\n it('throws an unauthorized exception as user cannot be found', async () => {\n userService.findOneBy.mockResolvedValue(null);\n expect(jwtStrategy.validate({ username: 'TestUser' })).rejects.toThrow(UnauthorizedException);\n });\n });\n});\n```\n\n```text\nfindOneBy\n```\n\n```text\nfindOne\n```\n\n```text\nfindOne\n```\n\n```text\nfindOneBy\n```\n\n========================================\n\nComments:\n- Good one. I've updated my answer to match. But it also does not solve the problem sadly.\n- : jest.fn() getting error for this. Tried let mock_function = any it didn't work.\n- need to be call await here - test file","metadata":{"transformedAt":"2026-08-18T18:33:44.714Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":11,"totalLines":385,"estimatedTokens":2568}}403{"id":"stack-68584092","source":"stackoverflow","questionId":68584092,"title":"using between for query Dates on api Repository Typeorm","tags":["postgresql","nestjs","typeorm"],"text":"Title: using between for query Dates on api Repository Typeorm\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am doing an endpoint that will receive an **array of strings** , **from date** and **to date**\n\nlike this:\n\n```\n{\n \"cage\": [\n \"100000\",\n \"100100\",\n \"130109\",\n \"130106\"\n ],\n \"from\": \"2020-05-01T00:00:00Z\",\n \"to\": \"2021-12-29T23:32:33.464Z\"\n}\n```\n\nThis is my query:\n\n```\nreturn await this.returnRepository.findAndCount({\n where: {\n cod_locality: In(cage),\n status_id: 1,\n shipment_id: IsNull(),\n asn_date: Between(from, to)\n //asn_date: Raw(asnDate => `${asnDate} => :from AND ${asnDate} **Question**\n\nIs a good idea to filter the dates using Between? Dates always are hard for me so its a little confusing.\n\nI was thinking that the Between will be comparing 2 strings but not Date Object so I dont know if this would work fine\n\nThe other option I seek was the comment one but I'm not sure how to use it properly.\n\nWhat do you guy think? Between will work or I need to change it for another one?\n\nps. I just remember the thing about the timezone of the database -.-\n\nthank you very much\n\n========================================\n\nCode:\n```text\n{\n \"cage\": [\n \"100000\",\n \"100100\",\n \"130109\",\n \"130106\"\n ],\n \"from\": \"2020-05-01T00:00:00Z\",\n \"to\": \"2021-12-29T23:32:33.464Z\"\n}\n```\n\n```text\nreturn await this.returnRepository.findAndCount({\n where: {\n cod_locality: In(cage),\n status_id: 1,\n shipment_id: IsNull(),\n asn_date: Between(from, to)\n //asn_date: Raw(asnDate => `${asnDate} => :from AND ${asnDate} <= :to`, { from, to }),\n }\n })\n```\n\n```js\nimport { Between } from 'typeorm';\nimport { format } from 'date-fns';\n\n// TypeORM Query Operators\nexport const BetweenDates = (from: Date | string, to: Date | string) =>\n Between(\n format(typeof from === 'string' ? new Date(from) : from, 'YYYY-MM-DD HH:MM:SS'),\n format(typeof to === 'string' ? new Date(to) : to, 'YYYY-MM-DD HH:MM:SS'),\n );\n\n// Query\nreturn await this.returnRepository\n .findAndCount({\n where: {\n cod_locality: In(cage),\n status_id: 1,\n shipment_id: IsNull(),\n asn_date: BetweenDates(from, to),\n }\n });\n```\n\n```text\nBetween\n```\n\n========================================\n\nComments:\n- Typeerror when the date field is of type date","metadata":{"transformedAt":"2026-08-18T18:33:44.714Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":104,"estimatedTokens":635}}404{"id":"stack-62771335","source":"stackoverflow","questionId":62771335,"title":"TypeORM find where clause, how to add where in multiple parameter","tags":["mysql","node.js","typeorm"],"text":"Title: TypeORM find where clause, how to add where in multiple parameter\nTags: mysql, node.js, typeorm\nSource: Stack Overflow\n\nQuestion:\n```\nthis.sampleRepo.find (\n {\n where: {\n id: In [\"1\",\"7\",\"13\"]\n\n }\n order: {\n id: \"DESC\"\n },\n select: ['id','group']\n \n \n }\n\n );\n```\n\nhow to add where clause here so that i can find records only where user id is one or 7 or 13.\n\n========================================\n\nCode:\n```text\nthis.sampleRepo.find (\n {\n where: {\n id: In [\"1\",\"7\",\"13\"]\n\n }\n order: {\n id: \"DESC\"\n },\n select: ['id','group']\n \n \n }\n\n );\n```\n\n```js\nimport { In } from 'typeorm';\n\n...\n...\n...\n\nthis.sampleRepo.find({\n where: {\n id: In(['1', '7', '13'])\n },\n order: {\n id: 'DESC'\n },\n select: ['id', 'group']\n});\n```\n\n```text\nIn\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.714Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":67,"estimatedTokens":234}}405{"id":"stack-56769663","source":"stackoverflow","questionId":56769663,"title":"TypeORM + Webpack causes SyntaxError: Unexpected token for entity file","tags":["node.js","typescript","webpack","typeorm"],"text":"Title: TypeORM + Webpack causes SyntaxError: Unexpected token for entity file\nTags: node.js, typescript, webpack, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have set up a pretty plain project with express, node.js and webpack. After installing TypeORM when configuring webpack.config.js it triggers unexpected token error for User.ts in entity folder. \n\nThe problem seems to be related to the fact that ormconfig.json is referring to .ts entity files. \n\nSolution in similar threads seems to be using ts-node with some extra parameters, but I am using webpack in this project and executing the bundle file.\n\nindex.ts\n\n```\nimport 'reflect-metadata';\nimport { createConnection } from 'typeorm';\nimport { User } from './entity/User';\ncreateConnection()\n .then(async connection => {\n console.log('Inserting a new user into the database...');\n const user = new User();\n user.firstName = 'Timber';\n user.lastName = 'Saw';\n user.age = 25;\n await connection.manager.save(user);\n console.log('Saved a new user with id: ' + user.id);\n\n console.log('Loading users from the database...');\n const users = await connection.manager.find(User);\n console.log('Loaded users: ', users);\n\n console.log(\n 'Here you can setup and run express/koa/any other framework.'\n );\n })\n .catch(error => console.log(error));\n```\n\normconfig.json\n\n```\n{\n \"type\": \"mssql\",\n \"host\": \"*\",\n \"port\": 27017,\n \"username\": \"*\",\n \"password\": \"*\",\n \"database\": \"*\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\"src/entity/**/*.ts\"],\n \"migrations\": [\"src/migration/**/*.ts\"],\n \"subscribers\": [\"src/subscriber/**/*.ts\"],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\nwebpack.config.js\n\n```\nmodule.exports = {\n mode: 'development',\n entry: path.resolve(path.join(__dirname, './src/index.ts')),\n externals: [nodeExternals()],\n name: 'API',\n context: __dirname,\n target: 'node',\n output: {\n path: __dirname + '/dist',\n filename: '[name].bundle.js',\n publicPath: '/',\n libraryTarget: 'commonjs2',\n },\n resolve: {\n extensions: ['.ts', '.tsx', '.js', '.json'],\n modules: [path.resolve(__dirname, 'node_modules')],\n },\n module: {\n rules: [\n {\n test: /\\.tsx?$/,\n loader: 'awesome-typescript-loader',\n exclude: [/node_modules/, /dist/],\n },\n {\n test: /\\.js$/,\n loader: 'babel-loader',\n exclude: [/node_modules/, /dist/],\n options: {\n babelrc: true,\n },\n },\n ],\n },\n plugins: [new CleanWebpackPlugin()],\n};\n```\n\nError messages are as following (the code reference is the default user entity file that comes with TypeORM\n\n```\napi/src/entity/User.ts:1\n(function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';\n ^\n\nSyntaxError: Unexpected token {\n at new Script (vm.js:80:7)\n at createScript (vm.js:274:10)\n at Object.runInThisContext (vm.js:326:10)\n at Module._compile (internal/modules/cjs/loader.js:664:28)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)\n at Module.load (internal/modules/cjs/loader.js:600:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:539:12)\n at Function.Module._load (internal/modules/cjs/loader.js:531:3)\n at Module.require (internal/modules/cjs/loader.js:637:17)\n at require (internal/modules/cjs/helpers.js:22:18)\n```\n\n========================================\n\nTop Answer:\nThis is because you are calling the global version of typeorm which expects javascript you need to be calling typeorm through ts-node like:\n\n./node_modules/.bin/ts-node ./node_modules/.bin/typeorm\n\nI set up an alias in my .bashrc:\n\nalias tstypeorm='./node_modules/.bin/ts-node ./node_modules/.bin/typeorm'\n\nThis solution works well for me (running on OsX)\n\n(You could also change the directories in your ormconfig.json to point to the generated javascript files)\n\n========================================\n\nCode:\n```js\nimport 'reflect-metadata';\nimport { createConnection } from 'typeorm';\nimport { User } from './entity/User';\ncreateConnection()\n .then(async connection => {\n console.log('Inserting a new user into the database...');\n const user = new User();\n user.firstName = 'Timber';\n user.lastName = 'Saw';\n user.age = 25;\n await connection.manager.save(user);\n console.log('Saved a new user with id: ' + user.id);\n\n console.log('Loading users from the database...');\n const users = await connection.manager.find(User);\n console.log('Loaded users: ', users);\n\n console.log(\n 'Here you can setup and run express/koa/any other framework.'\n );\n })\n .catch(error => console.log(error));\n```\n\n```text\n{\n \"type\": \"mssql\",\n \"host\": \"*\",\n \"port\": 27017,\n \"username\": \"*\",\n \"password\": \"*\",\n \"database\": \"*\",\n \"synchronize\": true,\n \"logging\": false,\n \"entities\": [\"src/entity/**/*.ts\"],\n \"migrations\": [\"src/migration/**/*.ts\"],\n \"subscribers\": [\"src/subscriber/**/*.ts\"],\n \"cli\": {\n \"entitiesDir\": \"src/entity\",\n \"migrationsDir\": \"src/migration\",\n \"subscribersDir\": \"src/subscriber\"\n }\n}\n```\n\n```text\nmodule.exports = {\n mode: 'development',\n entry: path.resolve(path.join(__dirname, './src/index.ts')),\n externals: [nodeExternals()],\n name: 'API',\n context: __dirname,\n target: 'node',\n output: {\n path: __dirname + '/dist',\n filename: '[name].bundle.js',\n publicPath: '/',\n libraryTarget: 'commonjs2',\n },\n resolve: {\n extensions: ['.ts', '.tsx', '.js', '.json'],\n modules: [path.resolve(__dirname, 'node_modules')],\n },\n module: {\n rules: [\n {\n test: /\\.tsx?$/,\n loader: 'awesome-typescript-loader',\n exclude: [/node_modules/, /dist/],\n },\n {\n test: /\\.js$/,\n loader: 'babel-loader',\n exclude: [/node_modules/, /dist/],\n options: {\n babelrc: true,\n },\n },\n ],\n },\n plugins: [new CleanWebpackPlugin()],\n};\n```\n\n```text\napi/src/entity/User.ts:1\n(function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';\n ^\n\nSyntaxError: Unexpected token {\n at new Script (vm.js:80:7)\n at createScript (vm.js:274:10)\n at Object.runInThisContext (vm.js:326:10)\n at Module._compile (internal/modules/cjs/loader.js:664:28)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)\n at Module.load (internal/modules/cjs/loader.js:600:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:539:12)\n at Function.Module._load (internal/modules/cjs/loader.js:531:3)\n at Module.require (internal/modules/cjs/loader.js:637:17)\n at require (internal/modules/cjs/helpers.js:22:18)\n```\n\n```text\nimport { User } from './entity'\n// import every other entity you have\n// .......\n\nawait createConnection({\n type: 'sqlite',\n database: 'database.sqlite',\n synchronize: true,\n logging: true,\n entities: [\n User // pass your entities in here\n ]\n })\n```\n\n========================================\n\nComments:\n- This ignores the existence of typeorm cli","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":263,"estimatedTokens":1830}}406{"id":"stack-65870541","source":"stackoverflow","questionId":65870541,"title":"TypeOrm - NestJS using queryBuilder","tags":["mysql","node.js","nestjs","query-builder","typeorm"],"text":"Title: TypeOrm - NestJS using queryBuilder\nTags: mysql, node.js, nestjs, query-builder, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have this db schema in mysql:\n\n```\nusers_tbl\n --------------------------------------------\n id | first_name | last_name\n --------------------------------------------\n 1 | Jon | Doe\n 2 | Mark | Smith\n\n address_tbl\n ------------------------------------------------------------\n id | address | city | user_id\n ------------------------------------------------------------\n 1 | some address | some city | 1\n```\n\nThen, I wanted to use TypeOrm's queryBuilder inorder to get the address of Jon Doe.\n\nMy raw sql query:\n`SELECT users.first_name, users.last_name, address.address, address.city FROM users INNER JOIN address ON address.user_id=users.id`\n\nMy TypeOrm queryBuilder:\n\n```\nconst users = await this.userRepo\n .createQueryBuilder('users')\n .select('users.first_name', 'fName')\n .addSelect('users.last_name', 'lName')\n .addSelect('adr.address', 'address')\n .addSelect('adr.city', 'city')\n .innerJoin('address', 'adr', 'adr.user_id=users.id')\n .getMany();\nreturn users;\n```\n\nThere doesn't seem to have any error as I am able to run a `GET` request. However, it returns an empty object. In my console, NestJS (or TypeORM) logs the generated mysql query. Here it is:\n\n`SELECT adr.city AS city, adr.country AS country, adr.id AS adr_id, users.first_name AS fName, users.last_name AS lName FROM users users INNER JOIN address adr ON adr.user_id = users.id`\n\nI copied and pasted it to perform a manual query in phpmyadmin. And the query seems to work, and gives me the expected output. Am I missing something in my code, or is this some TypeORM limitation?\n\n========================================\n\nCode:\n```text\nusers_tbl\n --------------------------------------------\n id | first_name | last_name\n --------------------------------------------\n 1 | Jon | Doe\n 2 | Mark | Smith\n\n\n address_tbl\n ------------------------------------------------------------\n id | address | city | user_id\n ------------------------------------------------------------\n 1 | some address | some city | 1\n```\n\n```text\nconst users = await this.userRepo\n .createQueryBuilder('users')\n .select('users.first_name', 'fName')\n .addSelect('users.last_name', 'lName')\n .addSelect('adr.address', 'address')\n .addSelect('adr.city', 'city')\n .innerJoin('address', 'adr', 'adr.user_id=users.id')\n .getMany();\nreturn users;\n```\n\n```text\nSELECT users.first_name, users.last_name, address.address, address.city FROM users INNER JOIN address ON address.user_id=users.id\n```\n\n```text\nGET\n```\n\n```text\nSELECT adr.city AS city, adr.country AS country, adr.id AS adr_id, users.first_name AS fName, users.last_name AS lName FROM users users INNER JOIN address adr ON adr.user_id = users.id\n```\n\n```text\nreturn await this.userRepo\n .createQueryBuilder('users')\n .select('users.first_name', 'fName')\n .addSelect('users.last_name', 'lName')\n .addSelect('adr.address', 'address')\n .addSelect('adr.city', 'city')\n .innerJoin('address', 'adr', 'adr.user_id=users.id')\n .printSql() \n .getRawMany();\n```\n\n```text\ngetRawMany\n```\n\n```text\ngetMany\n```\n\n========================================\n\nComments:\n- Can you you controller method?","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":114,"estimatedTokens":859}}407{"id":"stack-58273342","source":"stackoverflow","questionId":58273342,"title":"How to get a date from Postgres in my timezone","tags":["postgresql","nestjs","typeorm"],"text":"Title: How to get a date from Postgres in my timezone\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI try to deploy a JS application using TypeORM and Postgres on a host. Locally I had a Postgress DB so running in my own TZ. The remote host happens to have its system time set to UTC:\n\n```\n$ date\nMon Oct 7 15:45:00 UTC 2019\n\n$ psql\n> select localtimestamp;\n2019-10-07 15:45:00.123456\n```\n\nI have a table with an automatically updated date in it (meaning it updates when record is updated).\n\n```\n// my.entity.ts\n@UpdateDateColumn({type: 'timestamp', name: 'lastUpdate', default: () => 'LOCALTIMESTAMP' })\nlastUpdate: Date;\n```\n\nA row is inserted at 12:00 CEST:\n\n```\n> select \"lastUpdate\" from myTable;\n2019-10-07 10:00:00.000000+00\n```\n\nI would like to get the date out in my timezone (CEST) regardless of the server time, so it should return me 2019-10-07 12:00. I prefer to not hardcode any tricks because it should also work on my CEST machine.\n\nPostgress has all the info:\n\n```\n> show timezone;\nUCT\n```\n\n- it knows it runs on UTC time\n\n- I can tell it in which timezone I want the date\n\nSo I would expect it to be easy to convert this to my requested format. However, the following examples I found don't seem to work:\n\n```\n> select (\"lastUpdate\" at time zone 'CEST') from myTable;\n2019-10-07 08:00:00.000000+00\n\n> select timezone('CEST', \"lastUpdate\") from myTable;\n2019-10-07 08:00:00.000000+00\n```\n\nThere is one way I can get it right, and thats by specifying the current timezone:\n\n```\n> select (\"lastUpdate\" at time zone 'UTC' at time zone 'CEST') from myTable;\n2019-10-07 12:00:00.000000\n```\n\nHowever, like I said I don't want to hardcode this (as other DB's run at other TZs) and Postgres knows it's own timezone.\n\nIs there another syntax to do this correctly?\n\n========================================\n\nTop Answer:\nselect created_at at time zone 'utc' at time zone 'america/los_angeles'\nfrom users;\n\n========================================\n\nCode:\n```text\n$ date\nMon Oct 7 15:45:00 UTC 2019\n\n$ psql\n> select localtimestamp;\n2019-10-07 15:45:00.123456\n```\n\n```text\n// my.entity.ts\n@UpdateDateColumn({type: 'timestamp', name: 'lastUpdate', default: () => 'LOCALTIMESTAMP' })\nlastUpdate: Date;\n```\n\n```text\n> select \"lastUpdate\" from myTable;\n2019-10-07 10:00:00.000000+00\n```\n\n```text\n> show timezone;\nUCT\n```\n\n```text\n> select (\"lastUpdate\" at time zone 'CEST') from myTable;\n2019-10-07 08:00:00.000000+00\n\n> select timezone('CEST', \"lastUpdate\") from myTable;\n2019-10-07 08:00:00.000000+00\n```\n\n```text\n> select (\"lastUpdate\" at time zone 'UTC' at time zone 'CEST') from myTable;\n2019-10-07 12:00:00.000000\n```\n\n```text\n=> create table demo ( time timestamp, timetz timestamptz );\nCREATE TABLE\n\n=> insert into demo values ('2019-10-07 10:00', '2019-10-07 12:00 +0200');\nINSERT 0 1\n\n=> select * from demo;\n time | timetz \n---------------------+------------------------\n 2019-10-07 10:00:00 | 2019-10-07 10:00:00+00\n```\n\n```text\n=> set time zone 'Antarctica/Troll';\n\n=> select * from demo;\n time | timetz \n---------------------+------------------------\n 2019-10-07 10:00:00 | 2019-10-07 12:00:00+02\n```\n\n```text\n=> select timetz at time zone 'CEST' from demo;\n timezone \n---------------------\n 2019-10-07 12:00:00\n```\n\n```text\ntimestamp\n```\n\n```text\ntimestamptz\n```\n\n```text\ntimestamp\n```\n\n```text\ntimestamptz\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeorm\n```\n\n========================================\n\nComments:\n- Perhaps you should try to work only with type `timestamptz` and not sometimes with type `timestamp`. Try to set the default to `now()`. Of what type is your column?\n- Anyways, `select '2019-10-07 10:00:00.000000+00' at time zone 'CEST';` works fine for me.. (Output: `2019-10-07 12:00:00`)\n- If you are confused about types and the `AT TIME ZONE` operator perhaps the docs might help: postgresql.org/docs/current/…\n- Since `\"lastUpdate\"` and `(\"lastUpdate\" at time zone 'CEST')` both have a time zone in your given example, I guess there is something wrong with it.\n- Thanks, using timestamptz is indeed the simple solution!\n- select created_at at time zone 'utc' at time zone 'pst' from users;\n- select * from pg_timezone_names;","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":175,"estimatedTokens":1063}}408{"id":"stack-73368503","source":"stackoverflow","questionId":73368503,"title":"does set search_path of postgres affect connection or the database","tags":["postgresql","typeorm"],"text":"Title: does set search_path of postgres affect connection or the database\nTags: postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nTypeorm's migration is quite unexpected, even though I specify the schema, migrations run though the `queryRunner`, don't respect the `schema` specified in the connection:\n\n```\nconst dbconfig: DataSourceOptions = {\n ...baseConnection,\n schema: my_schema,\n migrations: ['./**/*.migration.js'],\n };\n\nlet data = new DataSource(dbconfig);\ndata = await data.initialize();\ndata.runMigrations()\n```\n\nit only seems to work if you've used something like a repository, orm specific.\n\nOne way I got around this is by using a static variable that persists throughout the migration process the name of the schema, and sets search_path of the database before each query, like this:\n\n```\nset search_path to ${static_variable.my_schema};\n run_query_1;\n\n set search_path to ${static_variable.my_schema};\n run_query_2;\n ...\n\n set search_path to ${static_variable.my_schema};\n run_query_n;\n```\n\nConsider this case,(1) an admin starts a migration, the schema is set to 'X', the database search_path is set to 'X', in the midst of this process, if a request comes in from tenant 'Y', then would he be writing to the tenant 'X' or 'Y'\n\n(2) If the app is horizontally scaled, then if two admins are performing migrations for two tenants, (there are two different static vars now), how would this affect the authenticity and integrity of the data.\n\nIf the `set search_path` is connection specifically maintained, then I suppose it could matter less , but if the database globally manages it, this could be an issue.\n\nAre these concurrent operations going to be a problem? Should I opt to modify the search_path at all?\n\nEDIT: What about for the case like this:\n\n```\nSTART TRANSACTION;\n set search_path to ${static_variable.my_schema};\n run_query_1;\n\n set search_path to ${static_variable.my_schema};\n run_query_2;\n ...\n\n set search_path to ${static_variable.my_schema};\n run_query_n;\nCOMMIT;\n```\n\n========================================\n\nCode:\n```text\nconst dbconfig: DataSourceOptions = {\n ...baseConnection,\n schema: my_schema,\n migrations: ['./**/*.migration.js'],\n };\n\nlet data = new DataSource(dbconfig);\ndata = await data.initialize();\ndata.runMigrations()\n```\n\n```text\nset search_path to ${static_variable.my_schema};\n run_query_1;\n\n set search_path to ${static_variable.my_schema};\n run_query_2;\n ...\n\n set search_path to ${static_variable.my_schema};\n run_query_n;\n```\n\n```text\nSTART TRANSACTION;\n set search_path to ${static_variable.my_schema};\n run_query_1;\n\n set search_path to ${static_variable.my_schema};\n run_query_2;\n ...\n\n set search_path to ${static_variable.my_schema};\n run_query_n;\nCOMMIT;\n```\n\n```text\nqueryRunner\n```\n\n```text\nschema\n```\n\n```text\nset search_path\n```\n\n```text\nSET\n```\n\n```text\nlocal\n```\n\n```text\nset search_patt to ...\n```\n\n```text\nalter database set search_path ...\n```\n\n```text\nalter user set search_path ...\n```\n\n========================================\n\nComments:\n- is there a command to terminate the session from postgres after the end of the transaction? I'm wondering if the sessions are pooled or not for the connection to be reused?\n- also the doc says: `SET LOCAL last only till the end of the current transaction` , can the same session be used for multiple transactions concurrently? Or a new transaction will have to use a new or unused session?\n- what about for the case if wrapped by an outer transaction, as I have updated in the question above.","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":138,"estimatedTokens":893}}409{"id":"stack-53117834","source":"stackoverflow","questionId":53117834,"title":"How to implement a node query resolver with apollo / graphql","tags":["postgresql","graphql","apollo","apollo-server","typeorm"],"text":"Title: How to implement a node query resolver with apollo / graphql\nTags: postgresql, graphql, apollo, apollo-server, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am working on implementing a node interface for graphql -- a pretty standard design pattern.\n\nLooking for guidance on the best way to implement a node query resolver for graphql\n\n`node(id ID!): Node`\n\nThe main thing that I am struggling with is how to encode/decode the ID the typename so that we can find the right table/collection to query from.\n\nCurrently I am using postgreSQL uuid strategy with pgcrytpo to generate ids.\n\nWhere is the right seam in the application to do this?:\n\n- could be done in the primary key generation at the database\n\n- could be done at the graphql seam (using a visitor pattern maybe)\n\nAnd once the best seam is picked:\n\n- how/where do you encode/decode?\n\nNote my stack is:\n\n- ApolloClient/Server (from graphql-yoga)\n\n- node\n\n- TypeORM\n\n- PostgreSQL\n\n========================================\n\nTop Answer:\n@Jonathan I can an implementation that I have and you see what you think. This is using `graphql-js`, `MongoDB` and `relay` on the client.\n\n```\n/**\n * Given a function to map from an ID to an underlying object, and a function\n * to map from an underlying object to the concrete GraphQLObjectType it\n * corresponds to, constructs a `Node` interface that objects can implement,\n * and a field config for a `node` root field.\n *\n * If the typeResolver is omitted, object resolution on the interface will be\n * handled with the `isTypeOf` method on object types, as with any GraphQL\n * interface without a provided `resolveType` method.\n */\nexport function nodeDefinitions(\n idFetcher: (id: string, context: TContext, info: GraphQLResolveInfo) => any,\n typeResolver?: ?GraphQLTypeResolver,\n): GraphQLNodeDefinitions {\n const nodeInterface = new GraphQLInterfaceType({\n name: 'Node',\n description: 'An object with an ID',\n fields: () => ({\n id: {\n type: new GraphQLNonNull(GraphQLID),\n description: 'The id of the object.',\n },\n }),\n resolveType: typeResolver,\n });\n\n const nodeField = {\n name: 'node',\n description: 'Fetches an object given its ID',\n type: nodeInterface,\n args: {\n id: {\n type: GraphQLID,\n description: 'The ID of an object',\n },\n },\n resolve: (obj, { id }, context, info) => (id ? idFetcher(id, context, info) : null),\n };\n\n const nodesField = {\n name: 'nodes',\n description: 'Fetches objects given their IDs',\n type: new GraphQLNonNull(new GraphQLList(nodeInterface)),\n args: {\n ids: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLID))),\n description: 'The IDs of objects',\n },\n },\n resolve: (obj, { ids }, context, info) => Promise.all(ids.map(id => Promise.resolve(idFetcher(id, context, info)))),\n };\n\n return { nodeInterface, nodeField, nodesField };\n}\n```\n\nThen:\n\n```\nimport { nodeDefinitions } from './node';\n\nconst { nodeField, nodesField, nodeInterface } = nodeDefinitions(\n // A method that maps from a global id to an object\n async (globalId, context) => {\n const { id, type } = fromGlobalId(globalId);\n\n if (type === 'User') {\n return UserLoader.load(context, id);\n }\n\n ....\n ...\n ...\n // it should not get here\n return null;\n },\n // A method that maps from an object to a type\n obj => {\n\n if (obj instanceof User) {\n return UserType;\n }\n\n ....\n ....\n\n // it should not get here\n return null;\n },\n);\n```\n\nThe `load` method resolves the actual object. This part you would have work more specifically with your DB and etc...\nIf it's not clear, you can ask! Hope it helps :)\n\n========================================\n\nCode:\n```text\nnode(id ID!): Node\n```\n\n```text\nimport Foo from '../../models/Foo'\n\nfunction encode (id, __typename) {\n return Buffer.from(`${id}:${__typename}`, 'utf8').toString('base64');\n}\n\nfunction decode (objectId) {\n const decoded = Buffer.from(objectId, 'base64').toString('utf8')\n const parts = decoded.split(':')\n return {\n id: parts[0],\n __typename: parts[1],\n }\n}\n\nconst typeDefs = `\n type Query {\n node(id: ID!): Node\n }\n type Foo implements Node {\n id: ID!\n foo: String\n }\n interface Node {\n id: ID!\n }\n`;\n\n// Just in case model name and typename do not always match\nconst modelsByTypename = {\n Foo,\n}\n\nconst resolvers = {\n Query: {\n node: async (root, args, context) => {\n const { __typename, id } = decode(args.id)\n const Model = modelsByTypename[__typename]\n const node = await Model.getById(id)\n return {\n ...node,\n __typename,\n };\n },\n },\n Foo: {\n id: (obj) => encode(obj.id, 'Foo')\n }\n};\n```\n\n```text\nfunction addIDResolvers (resolvers, types) {\n for (const type of types) {\n if (!resolvers[type]) {\n resolvers[type] = {}\n }\n resolvers[type].id = (obj) => encode(obj.id, type)\n }\n}\n\naddIDResolvers(resolvers, ['Foo', 'Bar', 'Qux'])\n```\n\n```text\nid\n```\n\n```text\n__typename\n```\n\n```text\nresolveType\n```\n\n```text\n__resolveType\n```\n\n```text\nid\n```\n\n```text\n/**\n * Given a function to map from an ID to an underlying object, and a function\n * to map from an underlying object to the concrete GraphQLObjectType it\n * corresponds to, constructs a `Node` interface that objects can implement,\n * and a field config for a `node` root field.\n *\n * If the typeResolver is omitted, object resolution on the interface will be\n * handled with the `isTypeOf` method on object types, as with any GraphQL\n * interface without a provided `resolveType` method.\n */\nexport function nodeDefinitions<TContext>(\n idFetcher: (id: string, context: TContext, info: GraphQLResolveInfo) => any,\n typeResolver?: ?GraphQLTypeResolver<*, TContext>,\n): GraphQLNodeDefinitions<TContext> {\n const nodeInterface = new GraphQLInterfaceType({\n name: 'Node',\n description: 'An object with an ID',\n fields: () => ({\n id: {\n type: new GraphQLNonNull(GraphQLID),\n description: 'The id of the object.',\n },\n }),\n resolveType: typeResolver,\n });\n\n const nodeField = {\n name: 'node',\n description: 'Fetches an object given its ID',\n type: nodeInterface,\n args: {\n id: {\n type: GraphQLID,\n description: 'The ID of an object',\n },\n },\n resolve: (obj, { id }, context, info) => (id ? idFetcher(id, context, info) : null),\n };\n\n const nodesField = {\n name: 'nodes',\n description: 'Fetches objects given their IDs',\n type: new GraphQLNonNull(new GraphQLList(nodeInterface)),\n args: {\n ids: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLID))),\n description: 'The IDs of objects',\n },\n },\n resolve: (obj, { ids }, context, info) => Promise.all(ids.map(id => Promise.resolve(idFetcher(id, context, info)))),\n };\n\n return { nodeInterface, nodeField, nodesField };\n}\n```\n\n```text\nimport { nodeDefinitions } from './node';\n\nconst { nodeField, nodesField, nodeInterface } = nodeDefinitions(\n // A method that maps from a global id to an object\n async (globalId, context) => {\n const { id, type } = fromGlobalId(globalId);\n\n if (type === 'User') {\n return UserLoader.load(context, id);\n }\n\n ....\n ...\n ...\n // it should not get here\n return null;\n },\n // A method that maps from an object to a type\n obj => {\n\n if (obj instanceof User) {\n return UserType;\n }\n\n ....\n ....\n\n // it should not get here\n return null;\n },\n);\n```\n\n```text\ngraphql-js\n```\n\n```text\nMongoDB\n```\n\n```text\nrelay\n```\n\n```text\nload\n```\n\n========================================\n\nComments:\n- Awesome -- this looks great. Couple of questions: (1) the `interface Node {id: String}` -- should it be: `Node {id: ID!}`? and (2): with `id: (obj) => encode(obj.id, 'Foo')` is there a good place to put this to handle it generically across all objects?\n- Yeah, `id` should be non-nullable... that's why I said it's a rough example :P AFAIK, you can't add a resolver for interface fields... you have to add a resolver for each type that extends `Node`. See my edit for an example of a function to DRY things up a bit.","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":340,"estimatedTokens":2003}}410{"id":"stack-73626614","source":"stackoverflow","questionId":73626614,"title":"Typeorm - multiple where statements","tags":["javascript","typeorm"],"text":"Title: Typeorm - multiple where statements\nTags: javascript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'd like to achieve something like this:\n\n```\nWHERE ( statement1 OR statement2 ) AND statement3\n```\n\nHow can I achieve this with query builder?\n\nI have tried this before:\n\n```\nEntity.createQueryBuilder()\n .where(statement1)\n .orWhere(statement2)\n .andWhere(statement3);\n```\n\nBut it produces following query:\n\n```\nWHERE statement1 OR statement2 AND statement3\n```\n\n========================================\n\nTop Answer:\nI believe that if @sp Kruten answer doesn't suit you, you'll find something here.\n\n========================================\n\nCode:\n```sql\nWHERE ( statement1 OR statement2 ) AND statement3\n```\n\n```js\nEntity.createQueryBuilder()\n .where(statement1)\n .orWhere(statement2)\n .andWhere(statement3);\n```\n\n```sql\nWHERE statement1 OR statement2 AND statement3\n```\n\n```js\nEntity.createQueryBuilder()\n .where(\n new Brackets((qb1) => {\n qb1.where(statement1).orWhere(statement2);\n })\n )\n .andWhere(statement3);\n```\n\n```text\nBrackets\n```\n\n========================================\n\nComments:\n- Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":69,"estimatedTokens":349}}411{"id":"stack-57881960","source":"stackoverflow","questionId":57881960,"title":"TypeORM: How to run SELECT... FOR UPDATE inside queryRunner?","tags":["typeorm"],"text":"Title: TypeORM: How to run SELECT... FOR UPDATE inside queryRunner?\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nHow can I run `SELECT... FOR UPDATE` inside `queryRunner` ?\nI see the TypeORM doc that queryRunner can only access `manager`, how I can access `Repository` to lock record. For example `queryRunner.getRepository(User).setLock(\"pessimistic_write\").....`\n\n```\nconsole.log(\"----------------- START TRANSACTION -----------------\");\n\n const queryRunner = connection.createQueryRunner();\n // establish real database connection using our new query runner\n await queryRunner.connect();\n\n await queryRunner.startTransaction();\n\n try {\n // `SELECT....FOR UPDATE`\n // Want to .setLock(\"pessimistic_write\")\n\n // commit transaction now:\n await queryRunner.commitTransaction();\n } catch (err) {\n // since we have errors lets rollback changes we made\n await queryRunner.rollbackTransaction();\n } finally {\n // you need to release query runner which is manually created:\n await queryRunner.release();\n }\n\n console.log(\"----------------- FINISH TRANSACTION -----------------\");\n```\n\nAny advice is welcome!\n\n========================================\n\nCode:\n```text\nconsole.log(\"----------------- START TRANSACTION -----------------\");\n\n const queryRunner = connection.createQueryRunner();\n // establish real database connection using our new query runner\n await queryRunner.connect();\n\n await queryRunner.startTransaction();\n\n try {\n // `SELECT....FOR UPDATE`\n // Want to .setLock(\"pessimistic_write\")\n\n\n // commit transaction now:\n await queryRunner.commitTransaction();\n } catch (err) {\n // since we have errors lets rollback changes we made\n await queryRunner.rollbackTransaction();\n } finally {\n // you need to release query runner which is manually created:\n await queryRunner.release();\n }\n\n console.log(\"----------------- FINISH TRANSACTION -----------------\");\n```\n\n```text\nSELECT... FOR UPDATE\n```\n\n```text\nqueryRunner\n```\n\n```text\nmanager\n```\n\n```text\nRepository\n```\n\n```text\nqueryRunner.getRepository(User).setLock(\"pessimistic_write\").....\n```\n\n```js\nusers = await queryRunner.manager\n .getRepository(User)\n .createQueryBuilder(\"user\")\n .useTransaction(true)\n .setLock(\"pessimistic_write\")\n .where(\"user.status = :status\", { status: status })\n .getMany();\n```\n\n```text\nRepository\n```\n\n```text\nmanager\n```\n\n========================================\n\nComments:\n- I start a transaction with a query runner. Would this code wrap the query into another transaction or the one I already have?\n- you can create wrapper function and execute your code const connection = getConnection(); const queryRunner = connection.createQueryRunner(); await queryRunner.connect(); await queryRunner.startTransaction(); try{ ur code here .... } catch (error) { await queryRunner.rollbackTransaction(); console.error('Transaction failed:', error); } finally { await queryRunner.release(); }","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":109,"estimatedTokens":758}}412{"id":"stack-64071522","source":"stackoverflow","questionId":64071522,"title":"How to create generic function in TS and TypeORM?","tags":["javascript","typescript","typeorm"],"text":"Title: How to create generic function in TS and TypeORM?\nTags: javascript, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nHow to create generic function in TS and TypeORM?\n\nI have a multiple functions like this:\n\n```\nasync getOrderName(id: number): Promise {\n const order = await this.conn.getRepository(Order).findOne(id);\n return `${order.name}`;\n }\n```\n\n```\nasync getServiceName(id: number): Promise {\n const service = await this.conn.getRepository(Service).findOne(id);\n return `${service.name}`;\n }\n```\n\nand another ... another... another...\n\nso, i need to create one generic function to use with the many entities\n\ncan somebody tell me how to create that function?\n\n========================================\n\nTop Answer:\nI highly recommend checking out https://www.typescriptlang.org/docs/handbook/generics.html\n\nYou can pass in type T (and return type T) if you'd like.\n\n```\nasync getServiceName(id: T): Promise {\n const service = await this.conn.getRepository(Service).findOne(id);\n return `${service.name}`;\n }\n```\n\nObviously you would have to overload findOne function to take any number of type T's. Or you could be super lazy and use any keyword in the lowest level.\n\n========================================\n\nCode:\n```text\nasync getOrderName(id: number): Promise<string> {\n const order = await this.conn.getRepository(Order).findOne(id);\n return `${order.name}`;\n }\n```\n\n```text\nasync getServiceName(id: number): Promise<string> {\n const service = await this.conn.getRepository(Service).findOne(id);\n return `${service.name}`;\n }\n```\n\n```js\ninterface NamedThing {\n name: string\n}\nasync getName<Entity extends NamedThing>(id: number, target: EntityTarget<Entity>): Promise<string> {\n const named = await this.conn.getRepository<Entity>(target).findOne(id);\n return `${named && named.name}`;\n}\n\n// equivalent calls are now `getName(id, Order)`, `getName(id, Service)`, etc.\n```\n\n```text\nEntityTarget\n```\n\n```text\nasync getServiceName<T>(id: T): Promise<string> {\n const service = await this.conn.getRepository(Service).findOne(id);\n return `${service.name}`;\n }\n```\n\n```text\nconst a = MyRepositoryName\n```\n\n```text\na\n```\n\n========================================\n\nComments:\n- thanks, but from where i can get `EntityTarget`? This class is in typeORM?\n- instead of `EntityTarget` I use `ObjectType` and works perfectly, thanks a lot :)\n- The OP doesn't want to generalize over the ID types, but rather over the repositories that they fetch from. This unconstrained `id` also doesn't work, because the types of IDs to `findOne` are `string|number|Date|ObjectID`.\n- That's why I would overload it. Depending on the type would go to the correct method.","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":100,"estimatedTokens":685}}413{"id":"stack-68867857","source":"stackoverflow","questionId":68867857,"title":"How to convert query ' WHERE IN' of strings with TypeORM Query Builder?","tags":["sql-server","typeorm","node.js-typeorm"],"text":"Title: How to convert query ' WHERE IN' of strings with TypeORM Query Builder?\nTags: sql-server, typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nGetting errors in following TypeORM query:\n\n```\nasync exportUsers(stateId: string, zipcodes: string) \n{\n //zipcodes = '60563', '54656', '94087';//\n const query = await this.userRepository\n .createQueryBuilder('user')\n .select('user.email', 'email')\n .where('left(user.Zip,5) in :zip', { zip: zipcodes }); \n}\n```\n\nHow to pass string containing 'array of strings' to TypeORM query using IN.\n\n========================================\n\nTop Answer:\nReplace your where clause with this code:\n\n```\n.where(\"left(user.Zip,5) IN (:zip )\", { zip : zipcodes })\n```\n\n**Note: your zipcode variable should be in array format; in means:**\n\n```\nzipcodes = ['94085','54656','94087']\n```\n\n========================================\n\nCode:\n```text\nasync exportUsers(stateId: string, zipcodes: string) \n{\n //zipcodes = '60563', '54656', '94087';//\n const query = await this.userRepository\n .createQueryBuilder('user')\n .select('user.email', 'email')\n .where('left(user.Zip,5) in :zip', { zip: zipcodes }); \n}\n```\n\n```text\nzipcodes = '60563', '54656', '94087';\nconst ziplist: string[] = zipcodes.replace(\"'\", \"\").split(\",\");\n```\n\n```text\n.where('left(s.ShipToZip,5) in (:...zip)', { zip: ziplist });\n```\n\n```text\n.where(\"left(user.Zip,5) IN (:zip )\", { zip : zipcodes })\n```\n\n```text\nzipcodes = ['94085','54656','94087']\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":65,"estimatedTokens":366}}414{"id":"stack-55564528","source":"stackoverflow","questionId":55564528,"title":"Is it possible to set field values from object using TypeOrm?","tags":["typescript","orm","typeorm"],"text":"Title: Is it possible to set field values from object using TypeOrm?\nTags: typescript, orm, typeorm\nSource: Stack Overflow\n\nQuestion:\nIs it possible to set field values from object using TypeOrm preserving type safity?\n\nAll examples I found in the documentation suggest you to set properties one-by-one\n\n```\nconst newUser = new User();\nnewUser.firstName = 'John'\nnewUser.lastName = 'Doe'\nnewUser.role = 'manager'\nnewUser.phone = '1234567890'\nnewUser.login = 'john.doe'\nnewUser.password = '12345'\nnewUser.save();\n```\n\nIt would be much nicer if I could set fields this way:\n\n```\nconst newUser = new User();\nnewUser.setFields({\n firstName: 'John',\n lastName: 'Doe',\n role: 'manager',\n phone: '1234567890',\n login: 'john.doe',\n password: '12345'\n }\n);\nnewUser.save();\n```\n\nIt would allow to use shortcuts\n\n```\nconst newUser = new User();\nnewUser.setFields({\n firstName,\n lastName,\n role,\n phone,\n login: 'john.doe',\n password: '12345'\n }\n);\nnewUser.save();\n```\n\nAnd use composition\n\n```\nconst newUser = new User();\nnewUser.setFields({\n firstName,\n lastName,\n role,\n phone,\n ...credentials\n }\n);\nnewUser.save();\n```\n\nthough I could not find any way to do so.\n\nI understand that by you need to have a type describing shape of your object in order to achieve it but I was hoping TS/TsOrm can derive it somehow from models I define.\n\n========================================\n\nCode:\n```text\nconst newUser = new User();\nnewUser.firstName = 'John'\nnewUser.lastName = 'Doe'\nnewUser.role = 'manager'\nnewUser.phone = '1234567890'\nnewUser.login = 'john.doe'\nnewUser.password = '12345'\nnewUser.save();\n```\n\n```text\nconst newUser = new User();\nnewUser.setFields({\n firstName: 'John',\n lastName: 'Doe',\n role: 'manager',\n phone: '1234567890',\n login: 'john.doe',\n password: '12345'\n }\n);\nnewUser.save();\n```\n\n```text\nconst newUser = new User();\nnewUser.setFields({\n firstName,\n lastName,\n role,\n phone,\n login: 'john.doe',\n password: '12345'\n }\n);\nnewUser.save();\n```\n\n```text\nconst newUser = new User();\nnewUser.setFields({\n firstName,\n lastName,\n role,\n phone,\n ...credentials\n }\n);\nnewUser.save();\n```\n\n```text\nconst userEntity = UserEntity.create({ firstName, lastName, ...someOtherStuff });\nconst mergedEntity = UserEntity.merge(mergedEntity, { lastName: \"new last name\" });\n```\n\n```text\nconst user = repository.create(); // same as const user = new User();\nconst user = repository.create({\n id: 1,\n firstName: \"Timber\",\n lastName: \"Saw\"\n}); // same as const user = new User(); user.firstName = \"Timber\"; user.lastName = \"Saw\";\n\nconst user = new User();\nrepository.merge(user, { firstName: \"Timber\" }, { lastName: \"Saw\" });\n// same as user.firstName = \"Timber\"; user.lastName = \"Saw\";\n```\n\n```text\ncreate\n```\n\n```text\nmerge\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":151,"estimatedTokens":713}}415{"id":"stack-58995838","source":"stackoverflow","questionId":58995838,"title":"NestJS y TypeORM: InjectRepository undefined","tags":["repository","inject","typeorm"],"text":"Title: NestJS y TypeORM: InjectRepository undefined\nTags: repository, inject, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a problem in a service that I am developing with nestjs and TypeORM\n\nThe system runs with a docker, everything works fine on my pc, but when I run it on any other side it stops working.\n\nThe error says:\n\n```\nTypeError: Cannot read property 'findOne' of undefined\n```\n\nBasicRepository:\n\n```\nexport abstract class BasicRepository {\n\n constructor(protected readonly repository: Repository,\nprotected readonly request: Request) {\n console.log(\"basicRepo\", this.repository.metadata.givenTableName) \n }\n}\n```\n\nUserRepository:\n\n```\nimport { Inject, Injectable, Scope } from '@nestjs/common';\nimport { Repository } from 'typeorm';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { BasicRepository } from './basic.repository';\nimport { UserEntity } from '../../shared/entities/user.entity';\nimport { REQUEST } from '@nestjs/core';\nimport { Request } from 'express';\n\n@Injectable({ scope: Scope.REQUEST })\nexport class UserRepository extends BasicRepository {\n\n constructor(\n @InjectRepository(UserEntity) public readonly repository: Repository,\n @Inject(REQUEST) public readonly request: Request,\n ) {\n super(repository, request);\n }\n}\n```\n\nTapRepository:\n\n```\nimport { Inject, Injectable, Scope } from '@nestjs/common';\nimport { Repository, FindManyOptions, getConnection, getManager } from 'typeorm';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { BasicRepository } from './basic.repository';\nimport { TapEntity} from '../../shared/entities/tap.entity';\nimport { REQUEST } from '@nestjs/core';\nimport { Request } from 'express';\n\n@Injectable({ scope: Scope.REQUEST })\nexport class TapRepository extends BasicRepository {\n\n constructor(\n @InjectRepository(TapEntity) public readonly repository: Repository,\n @Inject(REQUEST) public readonly request: Request,\n ) {\n super(repository, request);\n }\n}\n```\n\nThe strange thing is that in this case UserRepository does not give me an error, but the others.\n\nThe system only works on my pc, I usually run the system using kubernetes, it fails when I want to run it on GKE (google) or EKS (amazon).\n\nAnother thing that happens is that the 'basicRepo' message that prints the name of the repository table is only printed with the UserRepository class.\n\n========================================\n\nCode:\n```text\nTypeError: Cannot read property 'findOne' of undefined\n```\n\n```text\nexport abstract class BasicRepository<Entity> {\n\n constructor(protected readonly repository: Repository<Entity>,\nprotected readonly request: Request) {\n console.log(\"basicRepo\", this.repository.metadata.givenTableName) \n }\n}\n```\n\n```text\nimport { Inject, Injectable, Scope } from '@nestjs/common';\nimport { Repository } from 'typeorm';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { BasicRepository } from './basic.repository';\nimport { UserEntity } from '../../shared/entities/user.entity';\nimport { REQUEST } from '@nestjs/core';\nimport { Request } from 'express';\n\n@Injectable({ scope: Scope.REQUEST })\nexport class UserRepository extends BasicRepository<UserEntity> {\n\n constructor(\n @InjectRepository(UserEntity) public readonly repository: Repository<UserEntity>,\n @Inject(REQUEST) public readonly request: Request,\n ) {\n super(repository, request);\n }\n}\n```\n\n```text\nimport { Inject, Injectable, Scope } from '@nestjs/common';\nimport { Repository, FindManyOptions, getConnection, getManager } from 'typeorm';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { BasicRepository } from './basic.repository';\nimport { TapEntity} from '../../shared/entities/tap.entity';\nimport { REQUEST } from '@nestjs/core';\nimport { Request } from 'express';\n\n@Injectable({ scope: Scope.REQUEST })\nexport class TapRepository extends BasicRepository<TapEntity> {\n\n constructor(\n @InjectRepository(TapEntity) public readonly repository: Repository<TapEntity>,\n @Inject(REQUEST) public readonly request: Request,\n ) {\n super(repository, request);\n }\n}\n```\n\n```text\nexport class UserService {\n private userRepository: UserRepository;\n private authRepository: AuthRepository;\n constructor(\n private readonly connection: Connection\n ) {\n this.userRepository = this.connection.getCustomRepository(UserRepository);\n this.authRepository = this.connection.getCustomRepository(AuthRepository);\n }\n}\n```\n\n```text\n@InjectRepository()\n```\n\n```text\nConnection\n```\n\n```text\ntypeorm\n```\n\n========================================\n\nComments:\n- had a similar problem when ormconfig.json pointed to 'src/entity/**/*.{ts,js}' but the build version did not have the 'src' folder.","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":167,"estimatedTokens":1174}}416{"id":"stack-63584034","source":"stackoverflow","questionId":63584034,"title":"NestJS, PortsgreSQL and TypeORM - Migrations not running properly","tags":["postgresql","nestjs","typeorm"],"text":"Title: NestJS, PortsgreSQL and TypeORM - Migrations not running properly\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nWhen trying to run the TypeORM Migrations, either automatically in the application startup or manually via the TypeORM CLI, only the migrations table gets created (and it stays empty). The migration files themselves are not being executed.\n\nHere is my tsconfig.json\n\n```\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true\n }\n}\n```\n\nHere is my package.json\n\n```\n...\n\"typeorm\": \"node --require ts-node/register ./node_modules/typeorm/cli.js\",\n...\n```\n\nHere is my ormconfig.json\n\n```\n...\n\"entities\": [\"dist/**/*.entity{.ts,.js}\"],\n\"synchronize\": true,\n\"migrationsRun\": true,\n\"migrations \": [\"dist/migrations/*{.ts,.js}\"],\n\"cli\": {\n \"migrationsDir\": \"src/migrations\"\n }\n...\n```\n\nThe migration files are being created through the TypeORM CLI and they are to populate some tables (insert statements). They are not related to changes in the database schema.\n\nPlease, can anyone help me make it work?\n\n========================================\n\nTop Answer:\nyou should have synchronized to false `synchronize:false`\n\nAnd from the terminal run\n\n`npx typeorm migration:generate -n AnyNameYouWant`\n\nAfter that, you can run\n\n`npx typeorm migration:run`\n\nYou may also have to run `nest build` before running these commands.\n\n========================================\n\nCode:\n```text\n{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"declaration\": true,\n \"removeComments\": true,\n \"emitDecoratorMetadata\": true,\n \"experimentalDecorators\": true,\n \"allowSyntheticDefaultImports\": true,\n \"target\": \"es2017\",\n \"sourceMap\": true,\n \"outDir\": \"./dist\",\n \"baseUrl\": \"./\",\n \"incremental\": true\n }\n}\n```\n\n```text\n...\n\"typeorm\": \"node --require ts-node/register ./node_modules/typeorm/cli.js\",\n...\n```\n\n```text\n...\n\"entities\": [\"dist/**/*.entity{.ts,.js}\"],\n\"synchronize\": true,\n\"migrationsRun\": true,\n\"migrations \": [\"dist/migrations/*{.ts,.js}\"],\n\"cli\": {\n \"migrationsDir\": \"src/migrations\"\n }\n...\n```\n\n```text\normconfig.json\n```\n\n```text\n\"migrations \":\n```\n\n```text\nsynchronize:false\n```\n\n```text\nnpx typeorm migration:generate -n AnyNameYouWant\n```\n\n```text\nnpx typeorm migration:run\n```\n\n```text\nnest build\n```\n\n========================================\n\nComments:\n- run this command `npx typeorm migration:run`\n- I tried it but the only thing that happens is that the migrations table gets created (if it's not yet created). It's as if the migration files I created with the insert statements are not being found. I checked `\"migrations\": [\"dist/migrations/*{.ts,.js}\"]`and the files (.ts and .js) are all there.\n- I forgot to mention that the migration files I created are to populate some tables (insert statements). They are not related to changes in the database schema... I will edit the question with this info. I tried with `synchronize:false` but the result was the same.","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":137,"estimatedTokens":798}}417{"id":"stack-48427686","source":"stackoverflow","questionId":48427686,"title":"socketPath equivalent for mySQL connection in TypeORM","tags":["mysql","firebase","google-cloud-platform","typeorm"],"text":"Title: socketPath equivalent for mySQL connection in TypeORM\nTags: mysql, firebase, google-cloud-platform, typeorm\nSource: Stack Overflow\n\nQuestion:\nI created a mySQL database in the google cloud and I'm trying to connect to the mySQL instance from firebase according to this question on stackoverflow we need to set the socketPath property of mySql connection but TypeORM hasn't the same property wondering is there any other alternative?\n\n========================================\n\nCode:\n```text\n{\n\"type\": \"mysql\",\n\"extra\": {\n \"socketPath\": \"/cloudsql/<project>:<region>:<database>\"\n },\n\"port\": 3306,\n\"username\": \"myuser\",\n\"password\": \"secret\",\n\"database\": \"mydb\"\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":22,"estimatedTokens":169}}418{"id":"stack-60673361","source":"stackoverflow","questionId":60673361,"title":"TypeORM get one side of a many to many relationship","tags":["node.js","typescript","typeorm"],"text":"Title: TypeORM get one side of a many to many relationship\nTags: node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have got two entities: `User` and `Organisation`. These entities have a Many-to-Many relationship with each other. (A user can belong to multiple organisations and an organisation has multiple users.)\n\nI have an endpoint `/organisation/:id/members` this endpoint should return only the users belonging to the organisation of `:id`.\n\nI have created a query as follows:\n\n```\nconst members = await getConnection()\n .createQueryBuilder(Organisation, 'org')\n .where('org.id = :orgId', { orgId })\n .innerJoinAndSelect('org.members', 'member')\n .select('member')\n .getMany();\n```\n\nThis returns an empty array, except when `getRawMany` is used. Then it returns the following:\n\n```\n[\n {\n \"member_id\": 1,\n \"member_email\": \"example@example.com\",\n \"member_firstName\": \"John\",\n \"member_middleName\": \"\",\n \"member_lastName\": \"Doe\"\n }\n]\n```\n\nI would like to know how I get `getMany()` to return `User` entities.\n\n**Update:**\nI have the following example which does work. However, it requires the user to give the joinTable a name.\n\n```\nawait getConnection()\n .createQueryBuilder(User, 'user')\n .innerJoinAndSelect(\n 'organisation_members',\n 'member',\n 'member.userId = user.id',\n )\n .where('member.organisationId = :orgId', { orgId })\n .getMany();\n```\n\n========================================\n\nCode:\n```text\nconst members = await getConnection()\n .createQueryBuilder(Organisation, 'org')\n .where('org.id = :orgId', { orgId })\n .innerJoinAndSelect('org.members', 'member')\n .select('member')\n .getMany();\n```\n\n```text\n[\n {\n \"member_id\": 1,\n \"member_email\": \"example@example.com\",\n \"member_firstName\": \"John\",\n \"member_middleName\": \"\",\n \"member_lastName\": \"Doe\"\n }\n]\n```\n\n```text\nawait getConnection()\n .createQueryBuilder(User, 'user')\n .innerJoinAndSelect(\n 'organisation_members',\n 'member',\n 'member.userId = user.id',\n )\n .where('member.organisationId = :orgId', { orgId })\n .getMany();\n```\n\n```text\nUser\n```\n\n```text\nOrganisation\n```\n\n```text\n/organisation/:id/members\n```\n\n```text\n:id\n```\n\n```text\ngetRawMany\n```\n\n```text\ngetMany()\n```\n\n```text\nUser\n```\n\n```text\n@ManyToMany(type => User)\nmembers: User[];\n```\n\n```text\n@ManyToMany(\n type => User,\n user => user.organisations,\n)\n members: User[];\n```\n\n```text\n@ManyToMany(\n type => Organisation,\n org => org.members,\n)\norganisations: Organisation[];\n```\n\n```text\nreturn getConnection()\n .createQueryBuilder()\n .relation(Organisation, 'members')\n .of(orgId)\n .loadMany();\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":143,"estimatedTokens":664}}419{"id":"stack-65459698","source":"stackoverflow","questionId":65459698,"title":"Does typeorm raw sql query support IN clause","tags":["postgresql","typeorm"],"text":"Title: Does typeorm raw sql query support IN clause\nTags: postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI know we can use IN clause through querybuilder as:\n\n```\nawait manager.getRepository(ReportEntity).createQueryBuilder()\n .select('id')\n .where('job_id IN (:...ids)',{ids:query_data[i].array_agg})\n .getRawAndEntities()\n```\n\nIs it possible to do the same in a raw sql query? If yes, how do I pass parameters to IN clause\nin a raw query?\n\nIf I want to do it like this:\n\n```\nawait manager.query(\"select id from report where job_id IN (:...ids)\",[{ids:['d8add1db-41fe-4e2d-b287-037fc22f1d29','a07497b7-1a94-482a-988c-1e2dcf6059c6']}])\n```\n\n========================================\n\nCode:\n```text\nawait manager.getRepository(ReportEntity).createQueryBuilder()\n .select('id')\n .where('job_id IN (:...ids)',{ids:query_data[i].array_agg})\n .getRawAndEntities()\n```\n\n```text\nawait manager.query(\"select id from report where job_id IN (:...ids)\",[{ids:['d8add1db-41fe-4e2d-b287-037fc22f1d29','a07497b7-1a94-482a-988c-1e2dcf6059c6']}])\n```\n\n```text\nawait manager.query(\n 'SELECT id from report where job_id = ANY($1)',\n [['d8add1db-41fe-4e2d-b287-037fc22f1d29', 'a07497b7-1a94-482a-988c-1e2dcf6059c6']]\n)\n```\n\n========================================\n\nComments:\n- Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.\n- @MarkRotteveel that's true\n- sqlite doesn't support \"any\", is there any way to make \"in\" work?","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":50,"estimatedTokens":423}}420{"id":"stack-74143751","source":"stackoverflow","questionId":74143751,"title":"How to ignore DUPLICATE ENTRY error when updating multiple records at once using TypeORM","tags":["sql","node.js","nestjs","typeorm"],"text":"Title: How to ignore DUPLICATE ENTRY error when updating multiple records at once using TypeORM\nTags: sql, node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to update hundreds of database records using the TypeORM library. Problem is that sometimes DUPLICATE ERR is returned from SQL when the bulk upload is performed and stops the whole operation. Is possible to set up TypeORM in a way so duplicate entries are ignored and the insert is performed?\nThe table is using two primary keys:\nhttps://i.sstatic.net/uSZ0f.png\n\nThis is my insert command (TypeORM + Nestjs):\n\n```\npublic async saveBulk(historicalPrices: IHistoricalPrice[]) {\n if (!historicalPrices.length) {\n return;\n }\n const repoPrices = historicalPrices.map((p) => this.historicalPricesRepository.create(p));\n await this.historicalPricesRepository.save(repoPrices, { chunk: 200 });\n }\n```\n\nThanks in advance\n\n========================================\n\nCode:\n```js\npublic async saveBulk(historicalPrices: IHistoricalPrice[]) {\n if (!historicalPrices.length) {\n return;\n }\n const repoPrices = historicalPrices.map((p) => this.historicalPricesRepository.create(p));\n await this.historicalPricesRepository.save(repoPrices, { chunk: 200 });\n }\n```\n\n```text\nfor (let i = 0; i < historicalPrices.length; i += 200) {\n const chunk = historicalPrices.slice(i, i + 200);\n const targetEntity = this.historicalPricesRepository.target;\n await this.historicalPricesRepository\n .createQueryBuilder()\n .insert()\n .into(targetEntity)\n .values(chunk)\n .orIgnore()\n .execute();\n}\n```\n\n```text\nInsertQueryBuilder\n```\n\n```text\nrepository.save\n```\n\n```text\nInsertQueryBuilder\n```\n\n```text\norIgnore()\n```\n\n```text\nIGNORE\n```\n\n```text\nINSERT\n```\n\n```text\nInsertQueryBuilder\n```\n\n========================================\n\nComments:\n- I've never worked with `typeorm`, but it looks like they've had support for `onIgnore` since Q4 2018, at least based on this pull request. That will treat duplicate inserts as warnings instead of causing error.\n- Thanks for your commentary. It points to correct solution\n- Thank you for the explanation and solution. Chunking to code on my own is completely fine as it removes unnecessary layer of abstraction","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":84,"estimatedTokens":560}}421{"id":"stack-69813303","source":"stackoverflow","questionId":69813303,"title":"TypeORM - appending new items to array-type column (Postgres)","tags":["javascript","postgresql","typeorm"],"text":"Title: TypeORM - appending new items to array-type column (Postgres)\nTags: javascript, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nPostgres supports array type columns, and exposes methods for working with those arrays (like `array_append`). I'm wondering if TypeORM allows using those methods somehow.\n\nIn case it's not supported, what do you think the best way to append items to PG array? Doing something like get-and-set? (a transaction of getting the value, creating the new new array with js, and updating the value in the DB)\n\n========================================\n\nCode:\n```text\narray_append\n```\n\n```js\nawait dataSource.createQueryBuilder()\n .update(User)\n .set({\n yourArrayColumn: () => `array_append(\"yourArrayColumn\", 1)`\n })\n .where(\"id = :id\", { id: 1 })\n .execute();\n```\n\n```text\narray_append\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":29,"estimatedTokens":208}}422{"id":"stack-71736795","source":"stackoverflow","questionId":71736795,"title":"Cannot use TypeOrm in nx-nestjs project: ERR_REQUIRE_ESM","tags":["webpack","nestjs","typeorm","monorepo","nrwl-nx"],"text":"Title: Cannot use TypeOrm in nx-nestjs project: ERR_REQUIRE_ESM\nTags: webpack, nestjs, typeorm, monorepo, nrwl-nx\nSource: Stack Overflow\n\nQuestion:\nI am migrating my NestJS-TypeOrm app to a monorepo (NX workspace).\n\nWhenever I try to run the app, I get this error:\n\n```\nC:\\myproject\\node_modules\\@nrwl\\node\\src\\executors\\node\\node-with-require-overrides.js:16\nreturn originalLoader.apply(this, arguments);\n^\nError [ERR_REQUIRE_ESM]: require() of ES Module C:\\myproject\\node_modules\\@angular\\core\\fesm2015\\core.mjs not supported.\nInstead change the require of C:\\myproject\\node_modules\\@angular\\core\\fesm2015\\core.mjs to a dynamic import() which is available in all CommonJS modules.\nat Function.Module._load (C:\\myproject\\node_modules\\@nrwl\\node\\src\\executors\\node\\node-with-require-overrides.js:16:31)\nat ...\n```\n\nI debugged for hours and tracked the problem down to the \"import\" of my entities to TypeOrm, in AppModule:\n\n```\nimport {Foo} from './foo.entity.ts';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({...myConfig, entities: [Foo]}),\n /*...*/\n})\nexport class AppModule {/*...*/}\n```\n\nBut also using `forFeature()` causes the same error:\n\n```\nimport {Foo} from './foo.entity.ts';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Foo])],\n /*...*/\n})\nexport class MyFeatureModule {/*...*/}\n```\n\nIt seems like the problem might be caused by nx/webpack creating a single main.js file with all the code, whereas before the dist folder contained all the code files seperately.\n\nPeople suggested using `\"module\": \"commonjs\"` in my tsconfig, or `\"type\": \"module\"` in package.json, but this doesn't do anything :(\n\nAny solution ideas highly appreciated 🙏\n\n========================================\n\nCode:\n```js\nC:\\myproject\\node_modules\\@nrwl\\node\\src\\executors\\node\\node-with-require-overrides.js:16\nreturn originalLoader.apply(this, arguments);\n^\nError [ERR_REQUIRE_ESM]: require() of ES Module C:\\myproject\\node_modules\\@angular\\core\\fesm2015\\core.mjs not supported.\nInstead change the require of C:\\myproject\\node_modules\\@angular\\core\\fesm2015\\core.mjs to a dynamic import() which is available in all CommonJS modules.\nat Function.Module._load (C:\\myproject\\node_modules\\@nrwl\\node\\src\\executors\\node\\node-with-require-overrides.js:16:31)\nat ...\n```\n\n```js\nimport {Foo} from './foo.entity.ts';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({...myConfig, entities: [Foo]}),\n /*...*/\n})\nexport class AppModule {/*...*/}\n```\n\n```js\nimport {Foo} from './foo.entity.ts';\n\n@Module({\n imports: [TypeOrmModule.forFeature([Foo])],\n /*...*/\n})\nexport class MyFeatureModule {/*...*/}\n```\n\n```text\nforFeature()\n```\n\n```text\n\"module\": \"commonjs\"\n```\n\n```text\n\"type\": \"module\"\n```\n\n```text\nrequire()\n```\n\n========================================\n\nComments:\n- Similar issue, that would've probably taken me hours to notice. My problem was that I was importing the `Injectable` decorator from `@angular/core` instead of `@nestjs/common`.\n- my mono repo did not have any project or libs tagged which resulted int the same mistake. one of the libs had a dependency that pointed into an angular service. morale of the story, use the the tag system that Nx provides.","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":105,"estimatedTokens":792}}423{"id":"stack-51800851","source":"stackoverflow","questionId":51800851,"title":"TypeORM - findAll method to find all articles of an user","tags":["typescript","typeorm"],"text":"Title: TypeORM - findAll method to find all articles of an user\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want find all articles of one user from **TypeORM** package.\n\nOn **Sequelize**, I have this:\n\n```\nasync findAllByUser(userUuid: string, findOptions: object): Promise {\n return await Article.findAll({\n include: [{\n model: User,\n where: {\n uuid: userUuid\n }\n }]\n });\n}\n```\n\nI'd like an alternative for **TypeORM**.\n\n========================================\n\nCode:\n```text\nasync findAllByUser(userUuid: string, findOptions: object): Promise<Article[]> {\n return await Article.findAll<Article>({\n include: [{\n model: User,\n where: {\n uuid: userUuid\n }\n }]\n });\n}\n```\n\n```js\nexport class Article {\n /// ... other columns\n\n @ManyToOne(type => Author, author => author.articles)\n author: Author;\n}\n```\n\n```js\n// find*\n\ncreateConnection(/*...*/).then(async connection => {\n\n /*...*/\n let articleRepository = connection.getRepository(Article);\n let articles = await articleRepository.find({ relations: [\"author\"] });\n\n}).catch(error => console.log(error));\n```\n\n```js\n// Query Builder\nconst articles = await connection\n .getRepository(Article)\n .createQueryBuilder(\"article\") \n .leftJoinAndSelect(\"article.author\", \"user\")\n .getMany();\n```\n\n```text\nfind*\n```\n\n```text\nQueryBuilder\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":77,"estimatedTokens":350}}424{"id":"stack-59957394","source":"stackoverflow","questionId":59957394,"title":"TypeORM uploading and serve (downloading) files","tags":["node.js","file","express","download","typeorm"],"text":"Title: TypeORM uploading and serve (downloading) files\nTags: node.js, file, express, download, typeorm\nSource: Stack Overflow\n\nQuestion:\n### Introduction\n\nIn my Project, I try to store files in MySQL. An user can upload a file (html WEB-APP). Later the user has a list of uploaded files (html WEB-APP), and the user can download the file via Link. In the backend, I use a node.js (TypeORM) Project: \n\n- **\"typescript\": \"3.3.3333\"**\n\n- \"body-parser\": \"^1.19.0\",\n\n- \"debug\": \"^4.1.1\",\n\n- \"express\": \"^4.17.1\",\n\n- \"express-fileupload\": \"^1.1.6\",\n\n- \"mysql\": \"^2.14.1\",\n\n- \"reflect-metadata\": \"^0.1.10\",\n\n- **\"typeorm\": \"0.2.22\"**\n\n### Problem\n\n- ✅ In my Code, I can upload a file successfully.\n\n- ❌ If I try downloading the file, I got a file, that can not read, or is damaged.\n\n**What is wrong in my code, by downloading a file?**\n\nhttps://i.sstatic.net/629NG.png\n\n### My Code\n\n### Entity Class\n\nfile.ts \n\n```\nimport {Entity, Column, PrimaryGeneratedColumn} from \"typeorm\"\n\n@Entity()\nexport class MYFile{\n\n @PrimaryGeneratedColumn()\n id: number \n\n @Column()\n name: string\n\n @Column({\n type: \"longblob\"\n })\n data: string\n\n @Column()\n mimeType:string\n}\n```\n\n### App script\n\nindex.ts \n\n```\nimport \"reflect-metadata\";\nimport {createConnection, getRepository, getConnection} from \"typeorm\";\nimport * as express from 'express';\nimport * as bodyParser from \"body-parser\";\nimport http = require(\"http\");\nvar debug = require('debug')('rkdemo:server');\nimport * as fileUpload from \"express-fileupload\";\nconst fs = require('fs');\nimport {User} from \"./entity/User\";\nimport {MYFile} from \"./entity/file\"\n\nconst app = express();\nvar port = normalizePort(process.env.PORT || '3000');\nvar server = http.createServer(app);\napp.set('port', port);\napp.use(bodyParser.json({limit: '50mb'}));\napp.use(bodyParser.urlencoded({limit: '50mb', extended: false }));\napp.use(fileUpload({\n limits: { fileSize: 50 * 1024 * 1024 },\n}));\n\ncreateConnection().then(async connection => {\n\n app.get('/', (req, res) => {\n res.send('Hello world!');\n });\n\n app.get(\"/upload\", (req, res)=>{\n res.send(`\n Wählen Sie die hochzuladenden Dateien von Ihrem Rechner aus:\n \n \n hochladen\n `)\n })\n\n app.post(\"/upload\", async (req, res)=>{\n let fileData = req.files.datein\n\n console.log(fileData);\n\n if (Array.isArray(fileData)){\n console.log(\"TODO: Array\")\n }else{\n\n var newFile = new MYFile()\n newFile.name = fileData.name\n newFile.data = fileData.data.toString('base64')\n newFile.mimeType = fileData.mimetype\n\n try {\n const repo = getConnection().getRepository(MYFile)\n const result_File = await repo.save(newFile)\n res.send(\"Upload complete\")\n } catch (error) {\n console.log(error)\n res.send(\"ERROR\")\n }\n }\n })\n\n app.get(\"/file/:id\", async (req, res)=>{\n try {\n const repo = getConnection().getRepository(MYFile)\n const result_find = await repo.findOne(req.params.id)\n console.log(result_find);\n var fileData = Buffer.from(result_find.data, 'base64');\n res.writeHead(200, {\n 'Content-Type': result_find.mimeType,\n 'Content-Disposition': 'attachment; filename=' + result_find.name,\n 'Content-Length': fileData.length\n });\n res.write(fileData);\n res.end();\n } catch (error) {\n console.log(error)\n res.send(\"ERROR\")\n }\n })\n}).catch(error => console.log(error));\n\nserver.listen(port, function () {\n console.log('Example app listening on port: ' + port);\n });\nserver.on('error', onError);\nserver.on('listening', onListening);\n\nfunction normalizePort(val) {\n var port = parseInt(val, 10);\n if (isNaN(port)) {\n return val;\n }\n if (port >= 0) {\n return port;\n }\n return false;\n }\n\nfunction onError(error) {\n if (error.syscall !== 'listen') {\n throw error;\n }\n\n var bind = typeof port === 'string'\n ? 'Pipe ' + port\n : 'Port ' + port;\n\n switch (error.code) {\n case 'EACCES':\n console.error(bind + ' requires elevated privileges');\n process.exit(1);\n break;\n case 'EADDRINUSE':\n console.error(bind + ' is already in use');\n process.exit(1);\n break;\n default:\n throw error;\n }\n }\n\n function onListening() {\n var addr = server.address();\n var bind = typeof addr === 'string'\n ? 'pipe ' + addr\n : 'port ' + addr.port;\n debug('Listening on ' + bind);\n }\n```\n\n========================================\n\nCode:\n```text\nimport {Entity, Column, PrimaryGeneratedColumn} from \"typeorm\"\n\n@Entity()\nexport class MYFile{\n\n @PrimaryGeneratedColumn()\n id: number \n\n\n @Column()\n name: string\n\n @Column({\n type: \"longblob\"\n })\n data: string\n\n @Column()\n mimeType:string\n}\n```\n\n```text\nimport \"reflect-metadata\";\nimport {createConnection, getRepository, getConnection} from \"typeorm\";\nimport * as express from 'express';\nimport * as bodyParser from \"body-parser\";\nimport http = require(\"http\");\nvar debug = require('debug')('rkdemo:server');\nimport * as fileUpload from \"express-fileupload\";\nconst fs = require('fs');\nimport {User} from \"./entity/User\";\nimport {MYFile} from \"./entity/file\"\n\nconst app = express();\nvar port = normalizePort(process.env.PORT || '3000');\nvar server = http.createServer(app);\napp.set('port', port);\napp.use(bodyParser.json({limit: '50mb'}));\napp.use(bodyParser.urlencoded({limit: '50mb', extended: false }));\napp.use(fileUpload({\n limits: { fileSize: 50 * 1024 * 1024 },\n}));\n\n\n\ncreateConnection().then(async connection => {\n\n\n\n app.get('/', (req, res) => {\n res.send('Hello world!');\n });\n\n\n\n app.get(\"/upload\", (req, res)=>{\n res.send(`<form action=\"http://localhost:3000/upload\" method=\"post\" enctype=\"multipart/form-data\">\n <label>Wählen Sie die hochzuladenden Dateien von Ihrem Rechner aus:\n <input name=\"datein\" type=\"file\" multiple> \n </label> \n <button>hochladen</button>\n </form>`)\n })\n\n\n\n app.post(\"/upload\", async (req, res)=>{\n let fileData = req.files.datein\n\n console.log(fileData);\n\n\n if (Array.isArray(fileData)){\n console.log(\"TODO: Array\")\n }else{\n\n var newFile = new MYFile()\n newFile.name = fileData.name\n newFile.data = fileData.data.toString('base64')\n newFile.mimeType = fileData.mimetype\n\n try {\n const repo = getConnection().getRepository(MYFile)\n const result_File = await repo.save(newFile)\n res.send(\"Upload complete\")\n } catch (error) {\n console.log(error)\n res.send(\"ERROR\")\n }\n }\n })\n\n\n\n app.get(\"/file/:id\", async (req, res)=>{\n try {\n const repo = getConnection().getRepository(MYFile)\n const result_find = await repo.findOne(req.params.id)\n console.log(result_find);\n var fileData = Buffer.from(result_find.data, 'base64');\n res.writeHead(200, {\n 'Content-Type': result_find.mimeType,\n 'Content-Disposition': 'attachment; filename=' + result_find.name,\n 'Content-Length': fileData.length\n });\n res.write(fileData);\n res.end();\n } catch (error) {\n console.log(error)\n res.send(\"ERROR\")\n }\n })\n}).catch(error => console.log(error));\n\n\n\nserver.listen(port, function () {\n console.log('Example app listening on port: ' + port);\n });\nserver.on('error', onError);\nserver.on('listening', onListening);\n\n\nfunction normalizePort(val) {\n var port = parseInt(val, 10);\n if (isNaN(port)) {\n return val;\n }\n if (port >= 0) {\n return port;\n }\n return false;\n }\n\n\n\nfunction onError(error) {\n if (error.syscall !== 'listen') {\n throw error;\n }\n\n var bind = typeof port === 'string'\n ? 'Pipe ' + port\n : 'Port ' + port;\n\n switch (error.code) {\n case 'EACCES':\n console.error(bind + ' requires elevated privileges');\n process.exit(1);\n break;\n case 'EADDRINUSE':\n console.error(bind + ' is already in use');\n process.exit(1);\n break;\n default:\n throw error;\n }\n }\n\n\n function onListening() {\n var addr = server.address();\n var bind = typeof addr === 'string'\n ? 'pipe ' + addr\n : 'port ' + addr.port;\n debug('Listening on ' + bind);\n }\n```\n\n```text\napp.post(\"/upload\", async (req, res) => {\n ...\n newFile.data = fileData.data\n ...\n})\n\n... \n\napp.get(\"/file/:id\", async (req, res) => {\n ...\n let fileData = result_find.data\n ... \n})\n```\n\n```text\ndata: string\n```\n\n```text\ndata: Buffer\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.715Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":395,"estimatedTokens":2099}}425{"id":"stack-67521900","source":"stackoverflow","questionId":67521900,"title":"Connection \"default\" was not found with NestJS Unit Testing of Service","tags":["typescript","unit-testing","mocking","nestjs","typeorm"],"text":"Title: Connection \"default\" was not found with NestJS Unit Testing of Service\nTags: typescript, unit-testing, mocking, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am currently unit testing my NestJS service. My entity is called 'User' and I established a basic Service that allows me to interact with a MS SQL server, with GET and POST endpoints established in my Controller.\n\nWhile I was able to mock the `Repository` that is used in the Service, I was unable to establish a mock `getConnection` in a method that had to call `getConection()`.\n\nWhen I tried unit testing with `npm run test:watch`, I get the error that `ConnectionNotFoundError: Connection \"default\" was not found.` I have looked into (and in fact, taken much from) How to stub EntityManager and Connection in TypeORM with Jest, but this post does not seem to elaborate on a connection that was not established, which is my problem.\n\nIn any case, here's my service with the relevant parts:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { getConnection, Repository } from \"typeorm\";\nimport {User} from '../entities/user.entity';\n\n@Injectable()\nexport class ServiceName {\n constructor(@InjectRepository(User) private usersRepository: Repository) {}\n\n // Creating and inserting a new user into the database table using Repository\n // unit testing for this one works fine\n async createUserRepository(user: User): Promise {\n const newUser = this.usersRepository.create(user); \n return await this.usersRepository.save(newUser);\n }\n\n // Creating and inserting a new user into the database table using QueryBuilder and getConnection\n // unit testing for this one does not work so well \n async createUserQueryBuilder(user: User): Promise {\n await getConnection()\n .createQueryBuilder()\n .insert()\n .into(User)\n .values([\n user, \n ])\n .execute();\n return user; \n }\n```\n\nAnd here's my spec.ts file for unit testing:\n\n```\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { ServiceName } from './app_codes_rms_area.service';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport { User } from '../entities/user.entity';\nimport { Connection, Repository } from 'typeorm';\n\ndescribe('service tests', () => {\n\n const repositoryMockFactory: () => MockType> = jest.fn(() => ({ \n create: jest.fn(),\n save: jest.fn(),\n // other functions\n }));\n\n const mockConnectionFactory = jest.fn(() => ({\n getConnection: jest.fn().mockReturnValue({\n createQueryBuilder: jest.fn().mockReturnThis(),\n getMany: jest.fn().mockReturnValue(allUsers),\n insert: jest.fn().mockReturnThis(),\n into: jest.fn().mockReturnThis(),\n values: jest.fn().mockReturnThis(),\n execute: jest.fn().mockReturnValue(user),\n })\n }));\n \n let service: ServiceName;\n let mockRepository: MockType>;\n let mockConnection: Connection;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n ServiceName,\n {\n provide: getRepositoryToken(User), // a User Repository is injected to the service \n useFactory: repositoryMockFactory, // using factory ensures that a new mock is used for every test\n },\n {\n provide: Connection,\n useFactory: mockConnectionFactory,\n }\n ],\n }).compile();\n\n service = module.get(ServiceName);\n mockRepository = module.get(getRepositoryToken(User));\n mockConnection = module.get(Connection);\n });\n it('should create a new user and return it using Repository', async () => {\n // some test that passes using mockRepository\n });\n\n it('should create a new user and return it using QueryBuilder (with mocked Connection)', async () => {\n expect(await service.createUserQueryBuilder(user)).toEqual(user);\n expect(mockConnection.createQueryBuilder).toBeCalled();\n expect(mockConnection.createQueryBuilder()['insert']).toBeCalled();\n expect(mockConnection.createQueryBuilder()['into']).toBeCalled();\n expect(mockConnection.createQueryBuilder()['values']).toBeCalled();\n expect(mockConnection.createQueryBuilder()['execute']).toBeCalled();\n })\n```\n\nIt is the second test, `it('should create a new user and return it using QueryBuilder (with mocked Connection)'`, that triggers the following error:\n\n```\n● service tests › Service Functions › should create a new user and return it using QueryBuilder (with mocked Connection)\n\n ConnectionNotFoundError: Connection \"default\" was not found.\n\n at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)\n at ConnectionManager.Object..ConnectionManager.get (connection/ConnectionManager.ts:40:19)\n at Object.getConnection (index.ts:252:35)\n at ServiceName.createUserQueryBuilder (somefile:19:11)\n at Object.it (somefile:134:34)\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { getConnection, Repository } from \"typeorm\";\nimport {User} from '../entities/user.entity';\n\n\n@Injectable()\nexport class ServiceName {\n constructor(@InjectRepository(User) private usersRepository: Repository<User>) {}\n\n // Creating and inserting a new user into the database table using Repository\n // unit testing for this one works fine\n async createUserRepository(user: User): Promise<User> {\n const newUser = this.usersRepository.create(user); \n return await this.usersRepository.save(newUser);\n }\n\n // Creating and inserting a new user into the database table using QueryBuilder and getConnection\n // unit testing for this one does not work so well \n async createUserQueryBuilder(user: User): Promise<User> {\n await getConnection()\n .createQueryBuilder()\n .insert()\n .into(User)\n .values([\n user, \n ])\n .execute();\n return user; \n }\n```\n\n```text\nimport { Test, TestingModule } from '@nestjs/testing';\nimport { ServiceName } from './app_codes_rms_area.service';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport { User } from '../entities/user.entity';\nimport { Connection, Repository } from 'typeorm';\n\ndescribe('service tests', () => {\n\n const repositoryMockFactory: () => MockType<Repository<any>> = jest.fn(() => ({ \n create: jest.fn(),\n save: jest.fn(),\n // other functions\n }));\n\n const mockConnectionFactory = jest.fn(() => ({\n getConnection: jest.fn().mockReturnValue({\n createQueryBuilder: jest.fn().mockReturnThis(),\n getMany: jest.fn().mockReturnValue(allUsers),\n insert: jest.fn().mockReturnThis(),\n into: jest.fn().mockReturnThis(),\n values: jest.fn().mockReturnThis(),\n execute: jest.fn().mockReturnValue(user),\n })\n }));\n \n let service: ServiceName;\n let mockRepository: MockType<Repository<User>>;\n let mockConnection: Connection;\n\n beforeEach(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [\n ServiceName,\n {\n provide: getRepositoryToken(User), // a User Repository is injected to the service \n useFactory: repositoryMockFactory, // using factory ensures that a new mock is used for every test\n },\n {\n provide: Connection,\n useFactory: mockConnectionFactory,\n }\n ],\n }).compile();\n\n service = module.get<ServiceName>(ServiceName);\n mockRepository = module.get(getRepositoryToken(User));\n mockConnection = module.get<Connection>(Connection);\n });\n it('should create a new user and return it using Repository', async () => {\n // some test that passes using mockRepository\n });\n\n it('should create a new user and return it using QueryBuilder (with mocked Connection)', async () => {\n expect(await service.createUserQueryBuilder(user)).toEqual(user);\n expect(mockConnection.createQueryBuilder).toBeCalled();\n expect(mockConnection.createQueryBuilder()['insert']).toBeCalled();\n expect(mockConnection.createQueryBuilder()['into']).toBeCalled();\n expect(mockConnection.createQueryBuilder()['values']).toBeCalled();\n expect(mockConnection.createQueryBuilder()['execute']).toBeCalled();\n })\n```\n\n```text\n● service tests › Service Functions › should create a new user and return it using QueryBuilder (with mocked Connection)\n\n ConnectionNotFoundError: Connection \"default\" was not found.\n\n at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)\n at ConnectionManager.Object.<anonymous>.ConnectionManager.get (connection/ConnectionManager.ts:40:19)\n at Object.getConnection (index.ts:252:35)\n at ServiceName.createUserQueryBuilder (somefile:19:11)\n at Object.it (somefile:134:34)\n```\n\n```text\nRepository\n```\n\n```text\ngetConnection\n```\n\n```text\ngetConection()\n```\n\n```text\nnpm run test:watch\n```\n\n```text\nConnectionNotFoundError: Connection \"default\" was not found.\n```\n\n```text\nit('should create a new user and return it using QueryBuilder (with mocked Connection)'\n```\n\n```js\nasync createUserQueryBuilder(user: User): Promise<User> {\n await this.usersRepository\n .createQueryBuilder()\n .insert()\n .into(User)\n .values([\n user, \n ])\n .execute();\n return user; \n}\n```\n\n```js\nconst repositoryMockFactory: () => MockType<Repository<any>> = jest.fn(() => ({ \n create: jest.fn(),\n save: jest.fn(),\n createQueryBuilder: jest.fn().mockReturnThis(),\n getMany: jest.fn().mockReturnValue(allUsers),\n insert: jest.fn().mockReturnThis(),\n into: jest.fn().mockReturnThis(),\n values: jest.fn().mockReturnThis(),\n execute: jest.fn().mockReturnValue(user),\n}));\n```\n\n```js\nimport * as typeorm from 'typeorm';\n\nconst getConnectionSpy = jest.spyOn(typeorm, 'getConnection');\ngetConnectionSpy.mockImplementation(() => ({\n createQueryBuilder: jest.fn().mockReturnThis(),\n getMany: jest.fn().mockReturnValue(allUsers),\n insert: jest.fn().mockReturnThis(),\n into: jest.fn().mockReturnThis(),\n values: jest.fn().mockReturnThis(),\n execute: jest.fn().mockReturnValue(user),\n}));\n```\n\n```text\ncreateUserQueryBuilder\n```\n\n```text\nrepositoryMockFactory\n```\n\n```text\nspec.ts\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeorm.Connection\n```\n\n========================================\n\nComments:\n- Thank you for your answer! Indeed, this seems to work; but I would really like to stick to using `getConnection()`. (Really, it is for practice; my new role involves NestJS). Do you have any suggestions for mocking getConnection? I've found a way where I use `@InjectConnection() private connection: Connection` in my service and combine it with `{provide: Connection, useFactory: mockConnectionFactory, }` in my spec.ts file (and it works), but here I'm mocking an injected connection, NOT the getConnection that is imported. It'd be really nice if I could mock the imported getConnection.\n- I updated my answer though I can not guarantee that it would work. Good luck with your new role! 🍻\n- Uhmm, still not; but thanks for the answer! I feel like I have some tweaking to do here and there, perhaps...\n- Edit: I adapted your approach to a simpler example where I'm using `getManager()` followed by `delete` a single function and it worked! I'm pretty sure that some further tweaking is necessary to make the chain of functions in `createQueryBuilder` to work (it's probably much more complicated...). Thanks again!\n- Wow, great. Glad I could help 🍻","metadata":{"transformedAt":"2026-08-18T18:33:44.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":328,"estimatedTokens":2863}}426{"id":"stack-62004119","source":"stackoverflow","questionId":62004119,"title":"Typeorm find with and & or where block","tags":["javascript","typescript","typeorm"],"text":"Title: Typeorm find with and & or where block\nTags: javascript, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to build below query in typeorm.\n\n```\nSELECT * from Department where\ntype = 'Employee' and\n((from_date BETWEEN '2013-01-03'AND '2013-01-09') OR \n(to_date BETWEEN '2013-01-03' AND '2013-01-09') OR \n(from_date = '2013-01-09'))\n```\n\nBelow is my typeorm equivalent.\n\n```\nconnection.find(Department, {\n where: [\n { fromDate: Between(filter.fromDate, filter.toDate) },\n { toDate: Between(filter.fromDate, filter.toDate) },\n {\n fromDate: LessThanOrEqual(filter.fromDate),\n toDate: MoreThanOrEqual(filter.toDate),\n },\n ],\n andWhere: { type: 'Employee' },\n });\n```\n\nBut somehow I am getting wrong number of output. It is as if andWhere is not working.\nThanks in advance\n\n========================================\n\nCode:\n```text\nSELECT * from Department where\ntype = 'Employee' and\n((from_date BETWEEN '2013-01-03'AND '2013-01-09') OR \n(to_date BETWEEN '2013-01-03' AND '2013-01-09') OR \n(from_date <= '2013-01-03' AND to_date >= '2013-01-09'))\n```\n\n```text\nconnection.find(Department, {\n where: [\n { fromDate: Between(filter.fromDate, filter.toDate) },\n { toDate: Between(filter.fromDate, filter.toDate) },\n {\n fromDate: LessThanOrEqual(filter.fromDate),\n toDate: MoreThanOrEqual(filter.toDate),\n },\n ],\n andWhere: { type: 'Employee' },\n });\n```\n\n```js\nlet qb = this.repository.createQueryBuilder(\"department\");\n\nqb.where(\"department.type= :type\", {type: \"Employee\"});\nqb.andWhere(\"((department.from_date BETWEEN '2013-01-03'AND '2013-01-09') OR \n(department.to_date BETWEEN '2013-01-03' AND '2013-01-09') OR \n(department.from_date <= '2013-01-03' AND department.to_date >= '2013-01-09'))\");\n```\n\n========================================\n\nComments:\n- I'm not sure it's a valid option. I think you have either 2 choices: add \"type\" to every \"or\" clause, or use the queryBuilder.","metadata":{"transformedAt":"2026-08-18T18:33:44.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":72,"estimatedTokens":491}}427{"id":"stack-69235421","source":"stackoverflow","questionId":69235421,"title":"Typeorm and operator without using querybuilder","tags":["typescript","nestjs","typeorm"],"text":"Title: Typeorm and operator without using querybuilder\nTags: typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn NestJS / Typeform I want to make a query that sues to conditions as an `AND` condition.\n\nI tried something like this\n\n```\nasync getByUniqueConstraints(user: User){\n const {email, phoneNumber} = user\n const foundUser = await this.userRepository.findOne({where: [email, phoneNumber], });\n\n }\n```\n\nThe problem with this is that it uses an `OR` condition. Is there a way to use this with an `AND` operator instead without using a querybuilder or any more advanced concepts?\n\n========================================\n\nCode:\n```text\nasync getByUniqueConstraints(user: User){\n const {email, phoneNumber} = user\n const foundUser = await this.userRepository.findOne({where: [email, phoneNumber], });\n\n }\n```\n\n```text\nAND\n```\n\n```text\nOR\n```\n\n```text\nAND\n```\n\n```text\nwhere\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":45,"estimatedTokens":228}}428{"id":"stack-68762485","source":"stackoverflow","questionId":68762485,"title":"Create Partioned Table in Postgres Database","tags":["typeorm"],"text":"Title: Create Partioned Table in Postgres Database\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nHi as a Postgres Database required that the partition is created with the table I want to supply this with typeorm but haven't found any docs on how to declare this in an entity.\nHas anyone already solved this and has an example for me?","metadata":{"transformedAt":"2026-08-18T18:33:44.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":0,"totalLines":7,"estimatedTokens":84}}429{"id":"stack-61510569","source":"stackoverflow","questionId":61510569,"title":"TypeORM. Two Foreign Keys referencing the same Primary Key in one table","tags":["node.js","typescript","nestjs","typeorm"],"text":"Title: TypeORM. Two Foreign Keys referencing the same Primary Key in one table\nTags: node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nIn my project I would like to have bi-directional ManyToOne - OneToMany relations with two foreign keys referencing to the same primary key. In my case it would be a table 'match' which contains two players from table 'player' (player1Id and player2Id are FK). I want to be able to get all matches where a particular player played as well as assign a player to the match. In Match entity I guess it should be something like this: \n\n```\n@Entity()\nexport class Match {\n\n@PrimaryGeneratedColumn()\nid!: number;\n\n@ManyToOne((type) => Player)\n@JoinColumn({ name: \"player1Id\", referencedColumnName: \"id\" })\nplayer1: Player;\n\n@ManyToOne((type) => Player)\n@JoinColumn({ name: \"player2Id\", referencedColumnName: \"id\" })\nplayer2: Player;\n//some other properties...\n```\n\nbut since I have to indicate one inverse-side entity in @OneToMany() decorator then how should it look like in Player entity? Is there any way to map such an association in TypeORM and is it a good and common practice to have two FK in one table referencing to the same primary key in another table? I'm new in NodeJS and webdev in general. Thanks for any help.\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class Match {\n\n@PrimaryGeneratedColumn()\nid!: number;\n\n@ManyToOne((type) => Player)\n@JoinColumn({ name: \"player1Id\", referencedColumnName: \"id\" })\nplayer1: Player;\n\n@ManyToOne((type) => Player)\n@JoinColumn({ name: \"player2Id\", referencedColumnName: \"id\" })\nplayer2: Player;\n//some other properties...\n```\n\n```text\n@Entity()\nexport class Match {\n\n@PrimaryGeneratedColumn()\nid!: number;\n\n@ManyToMany((type) => Player, (player) => player.matches)\nplayers: Player[];\n\n//some other properties...\n```\n\n```text\n@Entity()\nexport class Player{\n\n@PrimaryGeneratedColumn()\nid!: number;\n\n@ManyToMany((type) => Match, (match) => match.players)\n@JoinTable()\nmatches: Match[];\n\n//some other properties...\n```\n\n```text\n@JoinTable()\n```\n\n========================================\n\nComments:\n- One player can have many matches? Could you please attach the Player Entity code?\n- Thanks! It's a great idea I was so focused on the idea of having two players so I couldn't come up with that :) That solves my issue, thanks!","metadata":{"transformedAt":"2026-08-18T18:33:44.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":82,"estimatedTokens":588}}430{"id":"stack-63207240","source":"stackoverflow","questionId":63207240,"title":"Nest can't resolve dependencies of the JwtStrategy","tags":["nestjs","typeorm"],"text":"Title: Nest can't resolve dependencies of the JwtStrategy\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am a newbie in NestJs world. As far as I know, I imported everything needed in the JwtStrategy. I don't know where it went wrong. Can somebody help me with this?\n\nAs far as I referred to documetation, Whenever we want to use any entity in a module, we should import that entity in the imports field in the @Module() decorator. I did it.\n\n**jwt.strategy.ts**\n\n```\nimport { Injectable, UnauthorizedException } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport { Strategy, ExtractJwt } from \"passport-jwt\";\nimport { InjectRepository } from \"@nestjs/typeorm\";\nimport { Repository } from \"typeorm\";\nimport { UserEntity } from \"src/entities/user.entity\";\nimport { AuthPayload } from \"src/common/dtos/user.dto\";\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(\n @InjectRepository(UserEntity)\n private userRepo: Repository\n ) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: process.env.SECRETKEY\n });\n }\n\n async validate(payload: AuthPayload): Promise {\n const { username } = payload;\n const user = this.userRepo.findOne({ where: { username: username } });\n if(!user) {\n throw new UnauthorizedException();\n }\n return user;\n }\n}\n```\n\n**auth.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UserEntity } from 'src/entities/user.entity';\nimport { JwtModule } from '@nestjs/jwt';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtStrategy } from './jwt.strategy';\n\n@Module({\n imports: [\n TypeOrmModule.forFeature([UserEntity]),\n JwtModule.register({\n secret: process.env.SECRETKEY,\n }),\n PassportModule.register({\n defaultStrategy: 'jwt'\n })\n ],\n providers: [AuthService, JwtStrategy],\n controllers: [AuthController],\n exports: [PassportModule, JwtStrategy]\n})\nexport class AuthModule {}\n```\n\n**user.entity.ts**\n\n```\nimport { Entity, Column, OneToMany, JoinTable, BeforeInsert } from \"typeorm\";\nimport { AbstractEntity } from \"./abstract-entity.abstract\";\nimport { IsEmail } from \"class-validator\";\nimport { Exclude, classToPlain } from \"class-transformer\";\nimport * as bcrypt from \"bcryptjs\";\nimport { CategoryEntity } from \"./category.entity\";\nimport { ArticleEntity } from \"./article.entity\";\n\n@Entity('User')\nexport class UserEntity extends AbstractEntity {\n @Column({\n type: \"varchar\",\n length: 80\n })\n fullName: string;\n\n @Column({\n type: \"varchar\",\n unique: true\n })\n @IsEmail()\n email: string;\n\n @Column({\n type: \"varchar\",\n unique: true\n })\n username: string;\n\n @Column({\n type: \"varchar\"\n })\n @Exclude()\n password: string;\n\n @Column({\n default: null,\n nullable: true\n })\n avatar: string | null;\n\n @Column({\n type: \"varchar\",\n unique: true\n })\n phoneNumber: string;\n\n @Column({\n type: \"boolean\",\n default: false\n })\n isAdmin: boolean;\n\n @Column({\n type: \"boolean\",\n default: false\n })\n isStaff: boolean;\n\n @Column({\n type: \"boolean\",\n default: false\n })\n isEmailVerified: boolean;\n\n @OneToMany(type => CategoryEntity, category => category.createdBy)\n @JoinTable()\n categories: CategoryEntity[];\n\n @OneToMany(type => ArticleEntity, article => article.createdBy)\n @JoinTable()\n articles: ArticleEntity[];\n\n @BeforeInsert()\n async hashPassword() {\n this.password = await bcrypt.hash(this.password, 10);\n }\n\n async comparePassword(attempt: string): Promise {\n return await bcrypt.compare(attempt, this.password);\n }\n\n toJSON(): any {\n return classToPlain(this);\n }\n}\n```\n\n**app.module.ts**\n\n```\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { TypeOrmModule } from \"@nestjs/typeorm\";\nimport { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';\nimport { \n DatabaseConnectionService\n } from \"./utils/database-connection.service\";\nimport { AuthModule } from './auth/auth.module';\nimport { UsersModule } from './users/users.module';\nimport { ArticlesModule } from './articles/articles.module';\nimport { HttpExceptionFilter } from './common/exception-filters/http-exception.filter';\nimport { ResponseInterceptor } from './common/interceptors/response.interceptor';\nimport { CategoryModule } from './category/category.module';\n\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n useClass: DatabaseConnectionService\n }),\n AuthModule,\n UsersModule,\n ArticlesModule,\n CategoryModule,\n ],\n controllers: [AppController],\n providers: [\n // {\n // provide: APP_INTERCEPTOR,\n // useClass: ResponseInterceptor\n // },\n {\n provide: APP_FILTER,\n useClass: HttpExceptionFilter\n },\n AppService\n ],\n})\nexport class AppModule {}\n```\n\n**database-connection.service.ts**\n\n```\nimport { Injectable } from \"@nestjs/common\";\nimport { TypeOrmOptionsFactory, TypeOrmModuleOptions } from \"@nestjs/typeorm\";\nimport { truncate } from \"fs\";\n\n@Injectable()\nexport class DatabaseConnectionService implements TypeOrmOptionsFactory {\n createTypeOrmOptions(): TypeOrmModuleOptions {\n return {\n type: \"mysql\",\n host: process.env.HOST,\n port: parseInt(process.env.PORT),\n username: process.env.DB_USERNAME,\n password: process.env.DB_PASSWORD,\n database: process.env.DATABASE, \n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n dropSchema: true,\n autoLoadEntities: true,\n logger: \"simple-console\"\n };\n }\n}\n```\n\nThe Error is as follows:\nhttps://i.sstatic.net/thZbI.jpg\n\n========================================\n\nTop Answer:\nConsider to move to Active Record pattern. All what you need to do is just to let your `AbstractEntity` extends `BaseEntity` of TypeOrm.\n\nYou can remove all typeorm features imports like:\n\n```\nTypeOrmModule.forFeature([UserEntity])\n```\n\nand all dependency injections for repository like:\n\n```\n@InjectRepository(UserEntity)\nprivate userRepo: Repository\n```\n\nJust use the entity class for querying:\n\n```\nconst user = await UserEntity.findOne({ where: { username } });\n```\n\n========================================\n\nCode:\n```text\nimport { Injectable, UnauthorizedException } from \"@nestjs/common\";\nimport { PassportStrategy } from \"@nestjs/passport\";\nimport { Strategy, ExtractJwt } from \"passport-jwt\";\nimport { InjectRepository } from \"@nestjs/typeorm\";\nimport { Repository } from \"typeorm\";\nimport { UserEntity } from \"src/entities/user.entity\";\nimport { AuthPayload } from \"src/common/dtos/user.dto\";\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(\n @InjectRepository(UserEntity)\n private userRepo: Repository<UserEntity>\n ) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: process.env.SECRETKEY\n });\n }\n\n async validate(payload: AuthPayload): Promise<UserEntity> {\n const { username } = payload;\n const user = this.userRepo.findOne({ where: { username: username } });\n if(!user) {\n throw new UnauthorizedException();\n }\n return user;\n }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UserEntity } from 'src/entities/user.entity';\nimport { JwtModule } from '@nestjs/jwt';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtStrategy } from './jwt.strategy';\n\n@Module({\n imports: [\n TypeOrmModule.forFeature([UserEntity]),\n JwtModule.register({\n secret: process.env.SECRETKEY,\n }),\n PassportModule.register({\n defaultStrategy: 'jwt'\n })\n ],\n providers: [AuthService, JwtStrategy],\n controllers: [AuthController],\n exports: [PassportModule, JwtStrategy]\n})\nexport class AuthModule {}\n```\n\n```text\nimport { Entity, Column, OneToMany, JoinTable, BeforeInsert } from \"typeorm\";\nimport { AbstractEntity } from \"./abstract-entity.abstract\";\nimport { IsEmail } from \"class-validator\";\nimport { Exclude, classToPlain } from \"class-transformer\";\nimport * as bcrypt from \"bcryptjs\";\nimport { CategoryEntity } from \"./category.entity\";\nimport { ArticleEntity } from \"./article.entity\";\n\n@Entity('User')\nexport class UserEntity extends AbstractEntity {\n @Column({\n type: \"varchar\",\n length: 80\n })\n fullName: string;\n\n @Column({\n type: \"varchar\",\n unique: true\n })\n @IsEmail()\n email: string;\n\n @Column({\n type: \"varchar\",\n unique: true\n })\n username: string;\n\n @Column({\n type: \"varchar\"\n })\n @Exclude()\n password: string;\n\n @Column({\n default: null,\n nullable: true\n })\n avatar: string | null;\n\n @Column({\n type: \"varchar\",\n unique: true\n })\n phoneNumber: string;\n\n @Column({\n type: \"boolean\",\n default: false\n })\n isAdmin: boolean;\n\n @Column({\n type: \"boolean\",\n default: false\n })\n isStaff: boolean;\n\n @Column({\n type: \"boolean\",\n default: false\n })\n isEmailVerified: boolean;\n\n @OneToMany(type => CategoryEntity, category => category.createdBy)\n @JoinTable()\n categories: CategoryEntity[];\n\n @OneToMany(type => ArticleEntity, article => article.createdBy)\n @JoinTable()\n articles: ArticleEntity[];\n\n @BeforeInsert()\n async hashPassword() {\n this.password = await bcrypt.hash(this.password, 10);\n }\n\n async comparePassword(attempt: string): Promise<boolean> {\n return await bcrypt.compare(attempt, this.password);\n }\n\n toJSON(): any {\n return classToPlain(this);\n }\n}\n```\n\n```text\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { TypeOrmModule } from \"@nestjs/typeorm\";\nimport { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';\nimport { \n DatabaseConnectionService\n } from \"./utils/database-connection.service\";\nimport { AuthModule } from './auth/auth.module';\nimport { UsersModule } from './users/users.module';\nimport { ArticlesModule } from './articles/articles.module';\nimport { HttpExceptionFilter } from './common/exception-filters/http-exception.filter';\nimport { ResponseInterceptor } from './common/interceptors/response.interceptor';\nimport { CategoryModule } from './category/category.module';\n\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n useClass: DatabaseConnectionService\n }),\n AuthModule,\n UsersModule,\n ArticlesModule,\n CategoryModule,\n ],\n controllers: [AppController],\n providers: [\n // {\n // provide: APP_INTERCEPTOR,\n // useClass: ResponseInterceptor\n // },\n {\n provide: APP_FILTER,\n useClass: HttpExceptionFilter\n },\n AppService\n ],\n})\nexport class AppModule {}\n```\n\n```text\nimport { Injectable } from \"@nestjs/common\";\nimport { TypeOrmOptionsFactory, TypeOrmModuleOptions } from \"@nestjs/typeorm\";\nimport { truncate } from \"fs\";\n\n@Injectable()\nexport class DatabaseConnectionService implements TypeOrmOptionsFactory {\n createTypeOrmOptions(): TypeOrmModuleOptions {\n return {\n type: \"mysql\",\n host: process.env.HOST,\n port: parseInt(process.env.PORT),\n username: process.env.DB_USERNAME,\n password: process.env.DB_PASSWORD,\n database: process.env.DATABASE, \n entities: [__dirname + '/**/*.entity{.ts,.js}'],\n synchronize: true,\n dropSchema: true,\n autoLoadEntities: true,\n logger: \"simple-console\"\n };\n }\n}\n```\n\n```text\nJwtStrategy\n```\n\n```text\nimports\n```\n\n```text\nJwtStrategy\n```\n\n```text\nAuthModule\n```\n\n```text\nproviders\n```\n\n```text\nimports\n```\n\n```js\nTypeOrmModule.forFeature([UserEntity])\n```\n\n```js\n@InjectRepository(UserEntity)\nprivate userRepo: Repository<UserEntity>\n```\n\n```js\nconst user = await UserEntity.findOne({ where: { username } });\n```\n\n```text\nAbstractEntity\n```\n\n```text\nBaseEntity\n```\n\n========================================\n\nComments:\n- where did you define `TypeOrmModule.forRoot` ? the `user` entity feature should be imported in your typeorm module root import\n- Did it in app.module.ts. It used to work before. But it doesn't now? I'll update app.module.ts.\n- Ok I can see your problem\n- Thank you @yash. I will be waiting for your answer.\n- can you add your UsersModule here as well?\n- UserModule has nothing to do with it. I just created UserModule and left it untouched for future uses.\n- Because from your architecture, i think `TypeOrmModule.forFeature([UserEntity])` should be in your UsersModule?\n- Consider there is no UsersModule.\n- actually it shouldnt be related your error.. i have a nestjs project very similar architecture with your app. using Typeorm with Passport module, but it;s working well\n- It used to work 2 days back. Suddenly after a commit this error is raised. I didn't change anything in the AuthModule. I just added a new column 'tags: string[]' in user.entity.ts. Does it have anything to do with this?\n- I don't think so. i used to get similar dependency injections errors before.. I switched to Active Record pattern. it doesnt require a dependency injection and dont need to make a repository instance, you can just use the entity class directly,\n- If we use active record pattern, It doesn't go well with the testing right?\n- no, it's even better with testing.\n- Okay, Thank you @yash. I'll try to implement it.\n- I'll definitely give it a try @yash. Thank you for the answer.","metadata":{"transformedAt":"2026-08-18T18:33:44.716Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":542,"estimatedTokens":3406}}431{"id":"stack-61715052","source":"stackoverflow","questionId":61715052,"title":"NestJS TypeORM syntax error in migration file","tags":["postgresql","typescript","nestjs","typeorm"],"text":"Title: NestJS TypeORM syntax error in migration file\nTags: postgresql, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI was going through the NestJS official docs. I set up PostgreSQL on Heroku, connected with TypeORM, run a migration and after that my app started crushing. I tried different approaches and searched blogs/issues on github/questions here, but nothing helped.\n\nHere is an error:\n\n```\n[Nest] 46723 - 05/10/2020, 6:33:42 PM [InstanceLoader] TypeOrmModule dependencies initialized +84ms\n[Nest] 46723 - 05/10/2020, 6:33:43 PM [TypeOrmModule] Unable to connect to the database. Retrying (1)... +493ms\n/Users/Shared/diploma/be/migration/1589119433066-AddUser.ts:1\nimport {MigrationInterface, QueryRunner} from \"typeorm\";\n ^\n\nSyntaxError: Unexpected token {\n at Module._compile (internal/modules/cjs/loader.js:721:23)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)\n at Module.load (internal/modules/cjs/loader.js:653:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:593:12)\n at Function.Module._load (internal/modules/cjs/loader.js:585:3)\n at Module.require (internal/modules/cjs/loader.js:690:17)\n at require (internal/modules/cjs/helpers.js:25:18)\n at Function.PlatformTools.load (/***/PROJECT_ROOT/node_modules/typeorm/platform/PlatformTools.js:114:28)\n at /***/PROJECT_ROOT/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:39:69\n at Array.map ()\n```\n\nHere is my `ormconfig.json`:\n\n```\n\"type\": \"postgres\",\n \"url\": \"postgres://***\",\n \"ssl\": true,\n \"extra\": {\n \"ssl\": {\n \"rejectUnauthorized\": false\n }\n },\n \"entities\": [\"dist/**/*.entity{.ts,.js}\"],\n \"migrationsTableName\": \"custom_migration_table\",\n \"migrations\": [\"migration/*{.ts,.js}\"],\n \"cli\": {\n \"migrationsDir\": \"migration\"\n }\n}\n```\n\nmigration was generated using `ts-node ./node_modules/.bin/typeorm migration:generate -n AddUser`\nI'm using `nest start --watch` command to start the app.\n\nMigration file `{TIMESTAMP}-AddUser.ts`:\n\n```\nimport {MigrationInterface, QueryRunner} from \"typeorm\";\n\nexport class AddUser1589119433066 implements MigrationInterface {\n name = 'AddUser1589119433066'\n\n public async up(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`CREATE TABLE \"users\" (...)`, undefined);\n }\n\n public async down(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`DROP TABLE \"users\"`, undefined);\n }\n\n}\n```\n\n========================================\n\nCode:\n```text\n[Nest] 46723 - 05/10/2020, 6:33:42 PM [InstanceLoader] TypeOrmModule dependencies initialized +84ms\n[Nest] 46723 - 05/10/2020, 6:33:43 PM [TypeOrmModule] Unable to connect to the database. Retrying (1)... +493ms\n/Users/Shared/diploma/be/migration/1589119433066-AddUser.ts:1\nimport {MigrationInterface, QueryRunner} from \"typeorm\";\n ^\n\nSyntaxError: Unexpected token {\n at Module._compile (internal/modules/cjs/loader.js:721:23)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)\n at Module.load (internal/modules/cjs/loader.js:653:32)\n at tryModuleLoad (internal/modules/cjs/loader.js:593:12)\n at Function.Module._load (internal/modules/cjs/loader.js:585:3)\n at Module.require (internal/modules/cjs/loader.js:690:17)\n at require (internal/modules/cjs/helpers.js:25:18)\n at Function.PlatformTools.load (/***/PROJECT_ROOT/node_modules/typeorm/platform/PlatformTools.js:114:28)\n at /***/PROJECT_ROOT/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:39:69\n at Array.map (<anonymous>)\n```\n\n```text\n\"type\": \"postgres\",\n \"url\": \"postgres://***\",\n \"ssl\": true,\n \"extra\": {\n \"ssl\": {\n \"rejectUnauthorized\": false\n }\n },\n \"entities\": [\"dist/**/*.entity{.ts,.js}\"],\n \"migrationsTableName\": \"custom_migration_table\",\n \"migrations\": [\"migration/*{.ts,.js}\"],\n \"cli\": {\n \"migrationsDir\": \"migration\"\n }\n}\n```\n\n```text\nimport {MigrationInterface, QueryRunner} from \"typeorm\";\n\nexport class AddUser1589119433066 implements MigrationInterface {\n name = 'AddUser1589119433066'\n\n public async up(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(`CREATE TABLE \"users\" (...)`, undefined);\n }\n\n public async down(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(`DROP TABLE \"users\"`, undefined);\n }\n\n}\n```\n\n```text\normconfig.json\n```\n\n```text\nts-node ./node_modules/.bin/typeorm migration:generate -n AddUser\n```\n\n```text\nnest start --watch\n```\n\n```text\n{TIMESTAMP}-AddUser.ts\n```\n\n```text\n\"entities\": [\"dist/**/*.entity{.ts,.js}\"],\n\"migrations\": [\"dist/migration/*{.ts,.js}\"],\n```\n\n```text\normconfig.json\n```\n\n========================================\n\nComments:\n- Have you tried removing javascript files from the migrations (or vice versa)? Sounds like it's trying to execute as JS and not TS, can you show your migration file or atleast a minimal version of it?\n- @Isolated I added migration file to the main message. TypeORM generates .ts migration and it should be ok (according to their docs). I run it with ts-node (also specified in typeorm docs) and it applied to the database without problems\n- I'm not at a PC so this is just basic debugging, my final thought would be set `entitiesDir:` to your TS entities in CLI, I'll be at my PC shortly so I'll see if I can reproduce it in my nest.js\n- It worked for me as well, although it looks like a bug for me. Nest start should look only for stuff on sourceRoot","metadata":{"transformedAt":"2026-08-18T18:33:44.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":9,"totalLines":161,"estimatedTokens":1347}}432{"id":"stack-62146087","source":"stackoverflow","questionId":62146087,"title":"TypeORM, ManyToMany Get posts by category id (TreeEntity materialized-path)","tags":["typescript","query-builder","typeorm"],"text":"Title: TypeORM, ManyToMany Get posts by category id (TreeEntity materialized-path)\nTags: typescript, query-builder, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get posts by category like a CMS does.\n\nFor example query post by categorie A will include all posts attached to Categorie A and also post attached to child of Categorie A.\n\nI really don't know how to build this query, so any help would be greatly appreciated :) .\n\nHere is my entities:\n\n```\n@Tree(\"materialized-path\")\nexport class Category {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @ManyToMany((type) => Post, (post) => post.categories)\n posts: Post[];\n\n @Expose()\n @TreeChildren()\n children: Category[];\n\n @Expose()\n @TreeParent()\n parent: Category;\n}\n```\n\n```\nexport class Post{\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @ManyToMany((type) => Category, (category) => category.posts)\n @JoinTable()\n categories: Category[];\n}\n```\n\nFollowings SQL Query do the job(Example with category id 1)\n\n```\nSELECT * FROM post WHERE id IN (\n SELECT postId FROM post_categories_category as postCat WHERE postCat.categoryId IN (\n SELECT id FROM category WHERE category.mpath LIKE \"1.%\" OR category.mpath LIKE \"%.1.%\"\n )\n)\n```\n\nSo the question is, how to convert this SQL query into a typeORM query ?\n\n========================================\n\nCode:\n```text\n@Tree(\"materialized-path\")\nexport class Category {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n\n @ManyToMany((type) => Post, (post) => post.categories)\n posts: Post[];\n\n @Expose()\n @TreeChildren()\n children: Category[];\n\n @Expose()\n @TreeParent()\n parent: Category;\n}\n```\n\n```text\nexport class Post{\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @ManyToMany((type) => Category, (category) => category.posts)\n @JoinTable()\n categories: Category[];\n}\n```\n\n```text\nSELECT * FROM post WHERE id IN (\n SELECT postId FROM post_categories_category as postCat WHERE postCat.categoryId IN (\n SELECT id FROM category WHERE category.mpath LIKE \"1.%\" OR category.mpath LIKE \"%.1.%\"\n )\n)\n```\n\n```js\n@Entity()\n@Tree(\"materialized-path\")\nexport class Category extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @ManyToMany((type) => Post, (post) => post.categories)\n posts: Post[];\n\n @TreeChildren()\n children: Category[];\n\n @TreeParent()\n parent: Category;\n\n async getPosts(): Promise<Post[]> {\n const categories = await getConnection().getTreeRepository(Category).findDescendants(this); // gets all children\n categories.push(this); // adds parent\n\n const ids = categories.map(cat => cat.id) // get an array of ids\n\n return await Post.createQueryBuilder('post')\n .distinct(true) // dont get duplicates (posts in two categories)\n .innerJoin('post.categories', 'category', 'category.id IN (:...ids)', {ids}) // get posts where category is in categories array\n .innerJoinAndSelect('post.categories', 'cat') // add all categories to selected post \n .orderBy('post.id')\n .getMany()\n }\n}\n\n@Entity()\nexport class Post extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n\n @ManyToMany((type) => Category, (category) => category.posts)\n @JoinTable()\n categories: Category[];\n}\n```\n\n========================================\n\nComments:\n- Work well for parent categories but if i try to get a child category the post assigned to parent categorie is also returned. But we are near the result...\n- In fact it's return me every post every time, but maybe i miss something...\n- @ZecKa Whoops, it should be an innerJoin. i edited the answer\n- It seems work like that, thank you so much for taking the time to help me. I will make more tests to be sure always is right before mark it as accepted answer.\n- Ok it's work really well, in my case I just add `.innerJoinAndSelect('post.categories', 'cat')` to have also category in selected post like WordPress feed and `orderBy('post.id')`\n- And in fact we don't need this line `categories.push(this); // adds parent` `findDescendants` seems contain this\n- Can you please provide resource from where I can read how to implement materialised path solution, the documentation for typeorm is not detailed at all and doesn't include schema too, like the mpath variable and it's format etc","metadata":{"transformedAt":"2026-08-18T18:33:44.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":167,"estimatedTokens":1119}}433{"id":"stack-62280978","source":"stackoverflow","questionId":62280978,"title":"How to aggregate a table with tree-structure to a single nested JSON object?","tags":["sql","json","postgresql","recursive-query","typeorm"],"text":"Title: How to aggregate a table with tree-structure to a single nested JSON object?\nTags: sql, json, postgresql, recursive-query, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a table in a Postgres 11.4 database with a self-referencing tree structure:\n\n```\n+------------+\n| account | \n+------------+\n| id |\n| code | \n| type |\n| parentId | -- references account.id\n+------------+\n```\n\nEach child can have another child, there is no limit on the nesting level.\n\nI want to generate a single JSON object from it, nesting all children (resursivly).\n\nIs it possible to solve this with single query?\nOr any other solution using typeORM with one table?\n\nElse I'll have to bind the data manually at server side.\n\nI tried this query:\n\n```\nSELECT account.type, json_agg(account) as accounts\nFROM account\n-- LEFT JOIN \"account\" \"child\" ON \"child\".\"parentId\"=\"account\".\"id\" -- tried to make one column child\nGROUP BY account.type\n```\n\nResult:\n\n```\n[\n ...\n {\n \"type\": \"type03\",\n \"accounts\": [\n {\n \"id\": 28,\n \"code\": \"acc03.001\",\n \"type\": \"type03\",\n \"parentId\": null\n },\n {\n \"id\": 29,\n \"code\": \"acc03.001.001\",\n \"type\": \"type03\",\n \"parentId\": 28\n },\n {\n \"id\": 30,\n \"code\": \"acc03.001.002\",\n \"type\": \"type03\",\n \"parentId\": 28\n }\n ]\n }\n ...\n]\n```\n\nI expect this instead:\n\n```\n[\n ...\n {\n \"type\": \"type03\",\n \"accounts\": [\n {\n \"id\": 28,\n \"code\": \"acc03.001\",\n \"type\": \"type03\",\n \"parentId\": null,\n \"child\": [\n {\n \"id\": 29,\n \"code\": \"acc03.001.001\",\n \"type\": \"type03\",\n \"parentId\": 28\n },\n {\n \"id\": 30,\n \"code\": \"acc03.001.002\",\n \"type\": \"type03\",\n \"parentId\": 28\n }\n ]\n }\n ]\n }\n ...\n]\n```\n\n========================================\n\nCode:\n```text\n+------------+\n| account | \n+------------+\n| id |\n| code | \n| type |\n| parentId | -- references account.id\n+------------+\n```\n\n```text\nSELECT account.type, json_agg(account) as accounts\nFROM account\n-- LEFT JOIN \"account\" \"child\" ON \"child\".\"parentId\"=\"account\".\"id\" -- tried to make one column child\nGROUP BY account.type\n```\n\n```text\n[\n ...\n {\n \"type\": \"type03\",\n \"accounts\": [\n {\n \"id\": 28,\n \"code\": \"acc03.001\",\n \"type\": \"type03\",\n \"parentId\": null\n },\n {\n \"id\": 29,\n \"code\": \"acc03.001.001\",\n \"type\": \"type03\",\n \"parentId\": 28\n },\n {\n \"id\": 30,\n \"code\": \"acc03.001.002\",\n \"type\": \"type03\",\n \"parentId\": 28\n }\n ]\n }\n ...\n]\n```\n\n```text\n[\n ...\n {\n \"type\": \"type03\",\n \"accounts\": [\n {\n \"id\": 28,\n \"code\": \"acc03.001\",\n \"type\": \"type03\",\n \"parentId\": null,\n \"child\": [\n {\n \"id\": 29,\n \"code\": \"acc03.001.001\",\n \"type\": \"type03\",\n \"parentId\": 28\n },\n {\n \"id\": 30,\n \"code\": \"acc03.001.002\",\n \"type\": \"type03\",\n \"parentId\": 28\n }\n ]\n }\n ]\n }\n ...\n]\n```\n\n```sql\nCREATE OR REPLACE FUNCTION f_build_jsonb_tree(_type text = NULL)\n RETURNS jsonb\n LANGUAGE plpgsql AS\n$func$\nDECLARE\n _nest_lvl int;\n\nBEGIN\n -- add level of nesting recursively\n CREATE TEMP TABLE t ON COMMIT DROP AS\n WITH RECURSIVE t AS (\n SELECT *, 1 AS lvl\n FROM account\n WHERE \"parentId\" IS NULL\n AND (type = _type OR _type IS NULL) -- default: whole table\n\n UNION ALL\n SELECT a.*, lvl + 1\n FROM t\n JOIN account a ON a.\"parentId\" = t.id\n )\n TABLE t;\n \n -- optional idx for big tables with many levels of nesting\n -- CREATE INDEX ON t (lvl, id);\n\n _nest_lvl := (SELECT max(lvl) FROM t);\n\n -- no nesting found, return simple result\n IF _nest_lvl = 1 THEN \n RETURN ( -- exits functions\n SELECT jsonb_agg(sub) -- AS result\n FROM (\n SELECT type\n , jsonb_agg(sub) AS accounts\n FROM (\n SELECT id, code, type, \"parentId\", NULL AS children\n FROM t\n ORDER BY type, id\n ) sub\n GROUP BY 1\n ) sub\n );\n END IF;\n\n -- start collapsing with leaves at highest level\n CREATE TEMP TABLE j ON COMMIT DROP AS\n SELECT \"parentId\" AS id\n , jsonb_agg (sub) AS children\n FROM (\n SELECT id, code, type, \"parentId\" -- type redundant?\n FROM t\n WHERE lvl = _nest_lvl\n ORDER BY id\n ) sub\n GROUP BY \"parentId\";\n\n -- optional idx for big tables with many levels of nesting\n -- CREATE INDEX ON j (id);\n\n -- iterate all the way down to lvl 2\n -- write to same table; ID is enough to identify\n WHILE _nest_lvl > 2\n LOOP\n _nest_lvl := _nest_lvl - 1;\n\n INSERT INTO j(id, children)\n SELECT \"parentId\" -- AS id\n , jsonb_agg(sub) -- AS children\n FROM (\n SELECT id, t.code, t.type, \"parentId\", j.children -- type redundant?\n FROM t\n LEFT JOIN j USING (id) -- may or may not have children\n WHERE t.lvl = _nest_lvl\n ORDER BY id\n ) sub\n GROUP BY \"parentId\";\n END LOOP;\n\n -- nesting found, return nested result\n RETURN ( -- exits functions\n SELECT jsonb_agg(sub) -- AS result\n FROM (\n SELECT type\n , jsonb_agg (sub) AS accounts\n FROM (\n SELECT id, code, type, \"parentId\", j.children\n FROM t\n LEFT JOIN j USING (id)\n WHERE t.lvl = 1\n ORDER BY type, id\n ) sub\n GROUP BY 1\n ) sub\n );\nEND\n$func$;\n```\n\n```text\nSELECT jsonb_pretty(f_build_jsonb_tree());\n```\n\n```text\nchildren\n```\n\n```text\nchild\n```\n\n```text\njsonb_pretty()\n```\n\n```text\ncode\n```\n\n```text\nt\n```\n\n```text\nlvl\n```\n\n```text\njsonb\n```\n\n```text\nj\n```\n\n```text\n_type\n```\n\n```text\n\"parentId\"\n```\n\n========================================\n\nComments:\n- Can it have more level of nesting (like, for example \"\"acc03.001.001.0001\" which parent would be \"acc03.001.001\")? Can it have multiple roots in the table (with `parentId=null`) per type?\n- Your version of Postgres (always)? How many levels of nesting are possible?\n- ya, the child can have another nesting. the code just example, can be random. Sorry the parentId is null and have nested child. i already edited.\n- So this is for simpler version without multi-level nesting: ``` ;with nested_accounts as ( SELECT account.type, account.parentId, json_agg(account) as accounts from account group by type, parentId ) select a.type, na.accounts from nested_accounts na inner join account a on a.id = na.parentId; ``` For multi-nested, there should be some recurrency added probably.\n- @Adam: Yes, the right track. But \"some recurrency\" turned out to be tricky.\n- Nice one. I was thinking at some point about temp tables, but I fixed myself on that \"single query\" requirement.","metadata":{"transformedAt":"2026-08-18T18:33:44.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":16,"totalLines":338,"estimatedTokens":1678}}434{"id":"stack-72845400","source":"stackoverflow","questionId":72845400,"title":"TypeORM custom repository not overriding createQueryBuilder","tags":["javascript","node.js","typescript","express","typeorm"],"text":"Title: TypeORM custom repository not overriding createQueryBuilder\nTags: javascript, node.js, typescript, express, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to implement database i18n for TypeORM. I have been able to do that theoratically. But I also want to override built-in repository methods to use i18n (basically intercepting them and adding a query). How can I override `createQueryBuilder` in TypeORM repository? I can override methods like `findMany`, `findOne` and add new methods. But it is not working for `createQueryBuilder`. I know I can override all select methods in the repository. But I want to do it in one place and tried to override `createQueryBuilder`. The code shows my custom repository definitions.\n\n```\nexport function TranslatableRepository() {\n return {\n createQueryBuilder(\n alias?: string,\n queryRunner?: QueryRunner\n ): SelectQueryBuilder {\n throw new Error();\n let qb = this.manager.createQueryBuilder(\n this.metadata.target as any,\n alias || this.metadata.targetName,\n queryRunner || this.queryRunner\n );\n\n qb = qb.leftJoinAndSelect(\n `${alias || this.metadata.targetName}.translations`,\n 'translation',\n 'translation.locale = :locale',\n {\n locale: this.getLocale()\n }\n );\n\n return qb;\n },\n\n getLocale() {\n return getLocaleFromContext();\n }\n } as ThisType & TTranslatableRepository> &\n TTranslatableRepository;\n }\n```\n\nAnd I use it like `postRepository.extend(TranslatableRepository())`. The `createQueryBuilder` method above should throw the error. But it is using built-in method. This is the copy of extend method in TypeORM souce code.\n\n```\nextend(custom) {\n // return {\n // ...this,\n // ...custom\n // };\n const thisRepo = this.constructor;\n const { target, manager, queryRunner } = this;\n const cls = new (class extends thisRepo {})(target, manager, queryRunner);\n Object.assign(cls, custom);\n return cls;\n }\n```\n\nHow can I override `createQueryBuilder` or is there any other ways to intercept queries?\n\n========================================\n\nCode:\n```js\nexport function TranslatableRepository<T>() {\n return {\n createQueryBuilder<Entity>(\n alias?: string,\n queryRunner?: QueryRunner\n ): SelectQueryBuilder<Entity> {\n throw new Error();\n let qb = this.manager.createQueryBuilder<Entity>(\n this.metadata.target as any,\n alias || this.metadata.targetName,\n queryRunner || this.queryRunner\n );\n\n qb = qb.leftJoinAndSelect(\n `${alias || this.metadata.targetName}.translations`,\n 'translation',\n 'translation.locale = :locale',\n {\n locale: this.getLocale()\n }\n );\n\n return qb;\n },\n\n getLocale() {\n return getLocaleFromContext();\n }\n } as ThisType<Repository<T> & TTranslatableRepository<T>> &\n TTranslatableRepository<T>;\n }\n```\n\n```js\nextend(custom) {\n // return {\n // ...this,\n // ...custom\n // };\n const thisRepo = this.constructor;\n const { target, manager, queryRunner } = this;\n const cls = new (class extends thisRepo {})(target, manager, queryRunner);\n Object.assign(cls, custom);\n return cls;\n }\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\nfindMany\n```\n\n```text\nfindOne\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\npostRepository.extend(TranslatableRepository<Post>())\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\ncreateQueryBuilder\n```\n\n```js\nexport function TranslatableRepository(manager: EntityManager) {\n manager.createQueryBuilder = function createQueryBuilder<Entity>(\n entityClass?: EntityTarget<Entity> | QueryRunner,\n alias?: string,\n queryRunner?: QueryRunner\n ): SelectQueryBuilder<Entity> {\n let qb: SelectQueryBuilder<Entity>;\n if (alias) {\n qb = this.connection.createQueryBuilder(\n entityClass as EntityTarget<Entity>,\n alias,\n queryRunner || this.queryRunner\n );\n } else {\n qb = this.connection.createQueryBuilder(\n (entityClass as QueryRunner | undefined) ||\n queryRunner ||\n this.queryRunner\n );\n }\n\n return qb.leftJoinAndSelect(\n `${alias}.translations`,\n 'translation',\n 'translation.locale = :locale',\n {\n locale: getLocaleFromContext()\n }\n );\n };\n\n return {};\n}\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\nentityManager\n```\n\n```text\nentityManager\n```\n\n```text\nappDataSource.manager\n```\n\n```text\nentityManager\n```\n\n```text\nappDataSource.createEntityManager()\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":17,"totalLines":201,"estimatedTokens":1155}}435{"id":"stack-68920699","source":"stackoverflow","questionId":68920699,"title":"How to query id not in condition with another table typeorm","tags":["mysql","node.js","typescript","nestjs","typeorm"],"text":"Title: How to query id not in condition with another table typeorm\nTags: mysql, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nHere is the query\n\n```\nSELECT * from tableA WHERE tableA.id NOT IN (SELECT tableB.a_id FROM tableB);\n```\n\nSame query how to write using TypeORM typescript?\nBelow is code, I tried which is not working\n\n```\nthis.createQueryBuilder('tableA')\n.where(`tableA.id != :id`, { id })\n```\n\n========================================\n\nTop Answer:\nYou can select IDs from `tableB` first, and then use the IDs you've got (I assume that they are mapped and stored in `var ids: string[]`) to make a query for `tableA`.\n\n```\nthis.createQueryBuilder('tableA')\n .where(`tableA.id <> ALL(:ids)`, { ids })\n```\n\n========================================\n\nCode:\n```text\nSELECT * from tableA WHERE tableA.id NOT IN (SELECT tableB.a_id FROM tableB);\n```\n\n```text\nthis.createQueryBuilder('tableA')\n.where(`tableA.id != :id`, { id })\n```\n\n```text\nconst tableBqry = tableBRepository\n .createQueryBuilder('tableB')\n .select(\"tableb_id\");\n\nconst tableAqry = tableARepository\n .createQueryBuilder('tableA')\n .where(\"tableA.id NOT IN (\" + tableBqry.getSql() + \")\");\n\nconst results = await tableAqry.getMany();\n```\n\n```text\nthis.createQueryBuilder('tableA')\n .where(`tableA.id <> ALL(:ids)`, { ids })\n```\n\n```text\ntableB\n```\n\n```text\nvar ids: string[]\n```\n\n```text\ntableA\n```\n\n========================================\n\nComments:\n- without selecting those ids leftJoinAndSelect will it work?\n- I'm not sure, but you can try left joining and then where some field in tableB is null.","metadata":{"transformedAt":"2026-08-18T18:33:44.716Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":7,"totalLines":75,"estimatedTokens":405}}436{"id":"stack-59638438","source":"stackoverflow","questionId":59638438,"title":"NestJS/TypeORM - connecting to multiple databases - ConnectionNotFoundError","tags":["nestjs","typeorm"],"text":"Title: NestJS/TypeORM - connecting to multiple databases - ConnectionNotFoundError\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nConnecting to **two databases** using TypeORM and NestJS throws a **ConnectionNotFoundError** when a custom repository is registered using the connection **(UserConnection & PhotoConnection)** one for each database. I have created a minimal repo here https://github.com/masonridge/connissuewithndb. The TypeOrm registration is done in the AppModule of NestJS \n\n**(app.module.ts)**\n\n```\n@Module({\n imports: [\n\n TypeOrmModule.forRootAsync({\n name: 'PhotoConnection',\n useFactory: async () => {\n return {\n type: 'sqlite',\n synchronize: true,\n database: 'TestPhoto.sqlite',\n entities: [Photo],\n } as SqliteConnectionOptions;\n },\n }),\n TypeOrmModule.forRootAsync({\n name: 'UserConnection',\n useFactory: async () => {\n return {\n type: 'sqlite',\n synchronize: true,\n database: 'TestUser.sqlite',\n entities: [User],\n } as SqliteConnectionOptions;\n },\n }),\n // TypeOrmModule.forFeature([User, UserRepository], 'UserConnection'),\n // TypeOrmModule.forFeature([Photo, PhotoRepository], 'PhotoConnection'),\n PhotoModule, UserModule,\n ],\n```\n\n**(photo.module.ts) DB connection1 - PhotoConnection is registered here**\n\n```\n@Module({\n imports: [ \n TypeOrmModule.forFeature([PhotoRepository], 'PhotoConnection'),\n ],\n providers: [\n PhotoService,\n ],\n controllers: [PhotoController],\n exports: [TypeOrmModule],\n})\nexport class PhotoModule {}\n```\n\n**(user.module.ts) DB connection2 - UserConnection is registered here**\n\n```\n@Module({\n imports: [\n TypeOrmModule.forFeature([UserRepository], 'UserConnection'),\n ],\n providers: [\n UserService,\n ],\n exports: [TypeOrmModule],\n controllers: [UserController],\n})\nexport class UserModule {}\n```\n\n**(user.repository.ts) Custom repository**\n\n```\n@EntityRepository(User)\nexport class UserRepository extends Repository {\n async createUser(name: string): Promise {\n const user = this.create();\n user.username = name;\n user.salt = 'salt';\n user.password = 'xxkdkdk';\n user.save();\n return name;\n }\n}\n```\n\n**(photo.repository.ts)**\n\n```\n@EntityRepository(Photo)\nexport class PhotoRepository extends Repository {\n async createPhoto(name: string): Promise {\n const photo = this.create();\n photo.name = name;\n photo.save();\n return name;\n }\n}\n```\n\nThe repo is injected into the service using the connection (PhotoConnection)\n**(photo.service.ts)**\n\n```\nexport class PhotoService {\n constructor(\n @InjectRepository(Photo, 'PhotoConnection')\n private readonly photoRepository: PhotoRepository,\n ) {}\n```\n\nand here using **UserConnection (user.service.ts)**\n\n```\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(User, 'UserConnection')\n private readonly userRepository: UserRepository,\n ) {}\n```\n\nThe application starts fine but on a POST request it throws a ConnectionNotFoundError error \n\n (node:190812) UnhandledPromiseRejectionWarning: ConnectionNotFoundError: Connection \"default\" was not found.\n at new ConnectionNotFoundError (C:\\nestjs\\type-orm-dbscratch\\node_modules\\typeorm\\error\\ConnectionNotFoundError.js:10:28)\n at ConnectionManager.get (C:\\nestjs\\type-orm-dbscratch\\node_modules\\typeorm\\connection\\ConnectionManager.js:38:19)\n at Object.getConnection (C:\\nestjs\\type-orm-dbscratch\\node_modules\\typeorm\\index.js:244:35)\n at Function.BaseEntity.getRepository (C:\\nestjs\\type-orm-dbscratch\\node_modules\\typeorm\\repository\\BaseEntity.js:67:57)\n at Photo.BaseEntity.save (C:\\nestjs\\type-orm-dbscratch\\node_modules\\typeorm\\repository\\BaseEntity.js:27:33)\n at PhotoRepository.createPhoto (C:\\nestjs\\type-orm-dbscratch\\dist\\db\\photo\\photo.repository.js:15:15)\n at PhotoService.createPhoto (C:\\nestjs\\type-orm-dbscratch\\dist\\db\\photo\\photo.service.js:24:43)\n at PhotoController.addSetting (C:\\nestjs\\type-orm-dbscratch\\dist\\db\\photo\\photo.controller.js:22:27)\n at C:\\nestjs\\type-orm-dbscratch\\node_modules@nestjs\\core\\router\\router-execution-context.js:37:29\n at process._tickCallback (internal/process/next_tick.js:68:7)\n\nI would like to know if there is an issue with the registration. Any help would be appreciated.\n\n========================================\n\nCode:\n```text\n@Module({\n imports: [\n\n TypeOrmModule.forRootAsync({\n name: 'PhotoConnection',\n useFactory: async () => {\n return {\n type: 'sqlite',\n synchronize: true,\n database: 'TestPhoto.sqlite',\n entities: [Photo],\n } as SqliteConnectionOptions;\n },\n }),\n TypeOrmModule.forRootAsync({\n name: 'UserConnection',\n useFactory: async () => {\n return {\n type: 'sqlite',\n synchronize: true,\n database: 'TestUser.sqlite',\n entities: [User],\n } as SqliteConnectionOptions;\n },\n }),\n // TypeOrmModule.forFeature([User, UserRepository], 'UserConnection'),\n // TypeOrmModule.forFeature([Photo, PhotoRepository], 'PhotoConnection'),\n PhotoModule, UserModule,\n ],\n```\n\n```text\n@Module({\n imports: [ \n TypeOrmModule.forFeature([PhotoRepository], 'PhotoConnection'),\n ],\n providers: [\n PhotoService,\n ],\n controllers: [PhotoController],\n exports: [TypeOrmModule],\n})\nexport class PhotoModule {}\n```\n\n```text\n@Module({\n imports: [\n TypeOrmModule.forFeature([UserRepository], 'UserConnection'),\n ],\n providers: [\n UserService,\n ],\n exports: [TypeOrmModule],\n controllers: [UserController],\n})\nexport class UserModule {}\n```\n\n```text\n@EntityRepository(User)\nexport class UserRepository extends Repository<User> {\n async createUser(name: string): Promise<string> {\n const user = this.create();\n user.username = name;\n user.salt = 'salt';\n user.password = 'xxkdkdk';\n user.save();\n return name;\n }\n}\n```\n\n```text\n@EntityRepository(Photo)\nexport class PhotoRepository extends Repository<Photo> {\n async createPhoto(name: string): Promise<string> {\n const photo = this.create();\n photo.name = name;\n photo.save();\n return name;\n }\n}\n```\n\n```text\nexport class PhotoService {\n constructor(\n @InjectRepository(Photo, 'PhotoConnection')\n private readonly photoRepository: PhotoRepository,\n ) {}\n```\n\n```text\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(User, 'UserConnection')\n private readonly userRepository: UserRepository,\n ) {}\n```\n\n```text\nActiveRecord\n```\n\n```text\n'default'\n```\n\n```text\nextends BaseEntity\n```\n\n```text\nthis.save(user)\n```\n\n```text\nuser.save()\n```\n\n```text\nActiveRecord\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":270,"estimatedTokens":1620}}437{"id":"stack-69967226","source":"stackoverflow","questionId":69967226,"title":"TypeORM: Custom Many To Many Relationship","tags":["node.js","postgresql","many-to-many","nestjs","typeorm"],"text":"Title: TypeORM: Custom Many To Many Relationship\nTags: node.js, postgresql, many-to-many, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm working with Nest.js, TypeORM, and PostgreSQL, I have two entities(product and stone) with a many to many relation, based on my own business project, I have to add one extra column to that many to many table(product_stone), but I have some issue with my solution, at first I try to create a product with a set of stones:\n\n```\n\"stones\": [\n {\"id\": 1,\"count\":1},\n {\"id\": 2,\"count\": 3}\n]\n```\n\nand after that, I try to add the count to the product_stone table by updating it, the result will be like this:\nproduct_stone_table\ntill here everything is Okay, but every time that I restart the server all of the data in that extra column will be set to its default value(null):\nproduct_stone_table\n\nAnd also I tried to do not set the count to {nullable:true} in product_stone table and add count during the creation of a product, but when I want to restart the server I receive an error kile this:\n\n```\nQueryFailedError: column \"count\" of relation \"product_stone\" contains null values\n```\n\nIs there anybody to guide me?\n\n**product.entity.ts**\n\n```\n@Entity()\nexport class Product extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToMany(() => Stone)\n @JoinTable({\n name: 'product_stone',\n joinColumn: {\n name: 'productId',\n referencedColumnName: 'id',\n },\n inverseJoinColumn: {\n name: 'stoneId',\n referencedColumnName: 'id',\n },\n })\n stones: Stone[];\n}\n```\n\n**stone.entity.ts**\n\n```\n@Entity()\nexport class Stone extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n}\n```\n\n**product_stone.entity.ts**\n\n```\n@Entity('product_stone')\nexport class ProductStone extends BaseEntity {\n @Column({ nullable: true })\n count: number;\n\n @Column()\n @IsNotEmpty()\n @PrimaryColumn()\n productId: number;\n\n @Column()\n @IsNotEmpty()\n @PrimaryColumn()\n stoneId: number;\n}\n```\n\n========================================\n\nCode:\n```text\n\"stones\": [\n {\"id\": 1,\"count\":1},\n {\"id\": 2,\"count\": 3}\n]\n```\n\n```text\nQueryFailedError: column \"count\" of relation \"product_stone\" contains null values\n```\n\n```text\n@Entity()\nexport class Product extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToMany(() => Stone)\n @JoinTable({\n name: 'product_stone',\n joinColumn: {\n name: 'productId',\n referencedColumnName: 'id',\n },\n inverseJoinColumn: {\n name: 'stoneId',\n referencedColumnName: 'id',\n },\n })\n stones: Stone[];\n}\n```\n\n```text\n@Entity()\nexport class Stone extends BaseEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n title: string;\n}\n```\n\n```text\n@Entity('product_stone')\nexport class ProductStone extends BaseEntity {\n @Column({ nullable: true })\n count: number;\n\n @Column()\n @IsNotEmpty()\n @PrimaryColumn()\n productId: number;\n\n @Column()\n @IsNotEmpty()\n @PrimaryColumn()\n stoneId: number;\n}\n```\n\n```js\n// product_stone.entity.ts\n@Entity()\nexport class ProductToStone {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column()\n public productId: number;\n\n @Column()\n public stoneId: number;\n\n @Column()\n public count: number;\n\n @ManyToOne(() => Product, product => product.productToStone)\n public product: Product;\n\n @ManyToOne(() => Stone, stone => stone.productToStone)\n public stone: Stone;\n}\n```\n\n```js\n// product.entity.ts\n...\n@OneToMany(() => ProductToStone, productToStone => productToStone.product)\npublic productToStones!: ProductToStone[];\n```\n\n```js\n// stone.entity.ts\n...\n@OneToMany(() => ProductToStone, productToStone => productToStone.stone)\npublic productToStones!: ProductToStone[];\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.716Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":186,"estimatedTokens":923}}438{"id":"stack-63078720","source":"stackoverflow","questionId":63078720,"title":"How can I define many to many columns with NestJS and TypeORM?","tags":["nestjs","typeorm"],"text":"Title: How can I define many to many columns with NestJS and TypeORM?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm new to NestJS/TypeORM so apologies and forgiveness please.\n\nI have a many to many relationship created; my table is created automatically with the correct columns.\n\nI have a location that can have many users, and a user can have many locations.\n\nMy route looks like this:\n\n```\nhttp://localhost:3000/locations/:location-id/users\n```\n\nMy `location.entity.ts` looks like this:\n\n```\n@ManyToMany(type => User, user => user.locations, { eager: true })\n @JoinTable()\n users: User[];\n```\n\nMy `user.entity.ts` looks like this:\n\n```\n@ManyToMany(type => Location, location => location.users, { eager: false })\n locations: Location[];\n```\n\n`location_users_user` table is getting generated with these columns:\n\n```\nlocationId | userId\n```\n\nSo far, everything looks great! When I send a `GET` request to my route using Postman, I am seeing this error in the console:\n\n```\ncolumn location_users_user.locationid does not exist\n```\n\nI see that `locationid` is what it's looking for, when my column name is `locationId`. Is there somewhere I need to set the case of the column names?\n\nI have also worked through this SO thread to set additional params in the `JoinTable` decorator.\n\nThat leaves me with this:\n\n```\n// location.entitiy.ts\n@ManyToMany(type => User, user => user.locations, { eager: true })\n @JoinTable({\n name: 'location_user',\n joinColumn: {\n name: 'locationId',\n referencedColumnName: 'id',\n },\n inverseJoinColumn: {\n name: 'userId',\n referencedColumnName: 'id',\n },\n })\n users: User[];\n```\n\nHowever, I'm still getting this error:\n\n```\ncolumn location_users_user.locationid does not exist\n```\n\nI don't think I'm setting the correct `Join` or something. I only have that decorator on my location entity.\n\nThank you for any suggestions!\n\n**EDIT**\n\nI have updated my `user.repository.ts` file as follows:\n\n```\nasync getLocationUsers(locationId: number): Promise {\n const query = this.createQueryBuilder('location_user')\n .where('location_user.locationId = :locationId', { locationId });\n```\n\nThe error still thinks I am looking for a `locationid` column. I've changed it to `foo` to just see if I was even in the correct spot and I am. I'm not sure why it's missing the case of `locationId`.\n\n**EDIT2**\n\nI've found that it could be a possible Postgres thing? Using double quotes, I'm now seeing the correct table/column name in my error:\n\n```\nconst query = this.createQueryBuilder('location_user')\n .where('location_user.\"locationId\" = :locationId', { locationId });\n```\n\nResults in: `column location_user.locationId does not exist`\nWhich is still odd, because that table does exist and so does the column.\n\n**Edit**\n\nHere is the `location.entity.ts` file:\n\n```\n@PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @ManyToMany(type => User, user => user.locations, { eager: true })\n @JoinTable()\n users: User[];\n```\n\nHere is the `user.entity.ts` file:\n\n```\n@PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n email: string;\n\n @ManyToMany(type => Location, location => location.users, { eager: false })\n locations: Location[];\n```\n\nI'm able to see the users' relationship when I get a specific location, so I know that's working properly. I am trying to just get all users that belong to the location; here is what my `user.repository.ts` file looks like:\n\n```\nasync getLocationUsers(locationId: number): Promise {\n const query = this.createQueryBuilder('user')\n .where('location_users_user.\"locationId\" = :locationId', { locationId });\n});\n\n try {\n return await query.getMany();\n } catch (e) {\n console.log('error: ', e);\n }\n }\n```\n\n========================================\n\nTop Answer:\nMight be a little late to a party but here's an interesting article on the subject.\n\n========================================\n\nCode:\n```js\nhttp://localhost:3000/locations/:location-id/users\n```\n\n```js\n@ManyToMany(type => User, user => user.locations, { eager: true })\n @JoinTable()\n users: User[];\n```\n\n```js\n@ManyToMany(type => Location, location => location.users, { eager: false })\n locations: Location[];\n```\n\n```js\nlocationId | userId\n```\n\n```text\ncolumn location_users_user.locationid does not exist\n```\n\n```js\n// location.entitiy.ts\n@ManyToMany(type => User, user => user.locations, { eager: true })\n @JoinTable({\n name: 'location_user',\n joinColumn: {\n name: 'locationId',\n referencedColumnName: 'id',\n },\n inverseJoinColumn: {\n name: 'userId',\n referencedColumnName: 'id',\n },\n })\n users: User[];\n```\n\n```text\ncolumn location_users_user.locationid does not exist\n```\n\n```js\nasync getLocationUsers(locationId: number): Promise<User[]> {\n const query = this.createQueryBuilder('location_user')\n .where('location_user.locationId = :locationId', { locationId });\n```\n\n```js\nconst query = this.createQueryBuilder('location_user')\n .where('location_user.\"locationId\" = :locationId', { locationId });\n```\n\n```js\n@PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @ManyToMany(type => User, user => user.locations, { eager: true })\n @JoinTable()\n users: User[];\n```\n\n```js\n@PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n email: string;\n\n @ManyToMany(type => Location, location => location.users, { eager: false })\n locations: Location[];\n```\n\n```js\nasync getLocationUsers(locationId: number): Promise<User[]> {\n const query = this.createQueryBuilder('user')\n .where('location_users_user.\"locationId\" = :locationId', { locationId });\n});\n\n try {\n return await query.getMany();\n } catch (e) {\n console.log('error: ', e);\n }\n }\n```\n\n```text\nlocation.entity.ts\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nlocation_users_user\n```\n\n```text\nGET\n```\n\n```text\nlocationid\n```\n\n```text\nlocationId\n```\n\n```text\nJoinTable\n```\n\n```text\nJoin\n```\n\n```text\nuser.repository.ts\n```\n\n```text\nlocationid\n```\n\n```text\nfoo\n```\n\n```text\nlocationId\n```\n\n```text\ncolumn location_user.locationId does not exist\n```\n\n```text\nlocation.entity.ts\n```\n\n```text\nuser.entity.ts\n```\n\n```text\nuser.repository.ts\n```\n\n```js\nasync getLocationUsers(locationId: number): Promise<User[]> {\n const query = this.createQueryBuilder('user')\n .leftJoin('user.locations', 'location')\n .where('location.id = :locationId', { locationId });\n});\n\n try {\n return await query.getMany();\n } catch (e) {\n console.log('error: ', e);\n }\n }\n```\n\n```js\n@ManyToMany(type => Location, location => location.users, { eager: false })\n```\n\n```js\n@ManyToMany(() => Location, (location) => location.users, { eager: false })\n```\n\n```text\n@ManyToMany\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\nleftJoin\n```\n\n```text\ngetLocationUsers\n```\n\n```text\nuser.repository.ts\n```\n\n```text\ntype =>\n```\n\n```text\n() =>\n```\n\n========================================\n\nComments:\n- can you please add full code of the two entities?\n- Hi @yash I've just updated my question at the bottom to include the relationships and my repository method. Thank you!\n- This is really interesting. I had to use the double quote otherwise I wasn't getting the correct case for `locationId`. It seems this was the part that I was clearly not doing correctly: `.leftJoin('user.locations', 'location')`. Thank you so much for your time. It helped get me back on the right track!","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":38,"totalLines":367,"estimatedTokens":1835}}439{"id":"stack-57129014","source":"stackoverflow","questionId":57129014,"title":"Type-graphql with lerna --- Error: Cannot determine GraphQL output type for id","tags":["node.js","graphql","typeorm","lerna","typegraphql"],"text":"Title: Type-graphql with lerna --- Error: Cannot determine GraphQL output type for id\nTags: node.js, graphql, typeorm, lerna, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI have recently moved from yarn/workspaces to lerna/npm, and in that move I have unearthed an unexpected problem. I know get:\n\n`Error: Cannot determine GraphQL output type for id` when generating my schema\n\nI am using type-graphql along with typeorm (a wonderful combo)\n\nMy package structure looks like the following\n\n```\n/app\n /packages\n /utils (common functions)\n /data (my TypeORM entities, repos, factories, decorated with type-graphql)\n /server (my type-graphql server) deps on @app/data\n /server-test (tests my server) also deps on @app/data\n```\n\nafter I do a:\nlerna clean\ncd app/packages/server\nnpm run start\n\nI now get `Error: Cannot determine GraphQL output type for id`\n\nboth data and server's package.json refer to `\"type-graphql\": \"^0.17.4\"`\n\n======\nNote in: https://github.com/19majkel94/type-graphql/issues/69\n\n@19majkel94 states the following:\n\n The last error Cannot determine GraphQL output type for id basically\n comes from getGraphQLOutputType and convertTypeIfScalar which performs\n if type instanceof GraphQLScalarType. The problem is that separate\n project has separate node_modules so GraphQLScalarType !==\n GraphQLScalarType.\n\n \n From my experience there's always too much problems from separating\n things to projects/modules than the benefits of this. I would\n recommend restructuring your app to don't need this.\n\nSo that seems a bit nuclear for me to forgo lerna, and modularization. I would love to see if there is a way to make this work.\n\n========================================\n\nCode:\n```text\n/app\n /packages\n /utils (common functions)\n /data (my TypeORM entities, repos, factories, decorated with type-graphql)\n /server (my type-graphql server) deps on @app/data\n /server-test (tests my server) also deps on @app/data\n```\n\n```text\nError: Cannot determine GraphQL output type for id\n```\n\n```text\nError: Cannot determine GraphQL output type for id\n```\n\n```text\n\"type-graphql\": \"^0.17.4\"\n```\n\n```text\ngraphql\n```\n\n```text\nnode_modules\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":80,"estimatedTokens":542}}440{"id":"stack-61360247","source":"stackoverflow","questionId":61360247,"title":"NestJS > TypeORM Mapping complex entities to complex DTOs","tags":["node.js","typescript","nestjs","typeorm","class-transformer"],"text":"Title: NestJS > TypeORM Mapping complex entities to complex DTOs\nTags: node.js, typescript, nestjs, typeorm, class-transformer\nSource: Stack Overflow\n\nQuestion:\nIm using class-transformer > `plainToClass`(entity, DTO) to map entities to DTO's\n\nI've also implemented the associated transform.interceptor pattern described here.\n\nThen I use `@Expose()` on members of my DTO's. This works great but I have a limitation, I need to map member DTO's in my parent DTO and this isn't happening, see simple example below\n\n```\n@Exclude()\nexport class ParentDTO{\n\n @Expose()\n pMember2 : string;\n\n @Expose()\n pMember2 : ChildDto[];\n}\n\n@Exclude()\nexport class ChildDTO{\n\n @Expose()\n cMember2 : string;\n}\n\nexport class ParentEntity{\n pMember1 : number;\n pMember2 : string;\n pMember3 : string;\n pMember4\n : Child[];\n}\n\nexport class ChildEntity{\n cMember1 : number;\n cMember2 : string;\n cMember3 : string;\n}\n```\n\nNow if I run `plainToClass(parentEntityFromDB, ParentDTO)` I was hoping to get the following\n\n```\nParentDTO{\n pMember2 : string;\n pMember2 : ChildDto[];\n}\n```\n\nHowever, what I am getting is\n\n```\nParentDTO{\n pMember2 : string;\n pMember2 : Child[]; //Including all original members\n}\n```\n\nBasically plainToClass(entity, DTO) is not automatically mapping members to match the given DTO type.\n\nIs there a way to do this or is this a limitation of the method??\n\nThanks\n\n========================================\n\nCode:\n```text\n@Exclude()\nexport class ParentDTO{\n\n @Expose()\n pMember2 : string;\n\n @Expose()\n pMember2 : ChildDto[];\n}\n\n@Exclude()\nexport class ChildDTO{\n\n @Expose()\n cMember2 : string;\n}\n\nexport class ParentEntity{\n pMember1 : number;\n pMember2 : string;\n pMember3 : string;\n pMember4\n : Child[];\n}\n\nexport class ChildEntity{\n cMember1 : number;\n cMember2 : string;\n cMember3 : string;\n}\n```\n\n```text\nParentDTO{\n pMember2 : string;\n pMember2 : ChildDto[];\n}\n```\n\n```text\nParentDTO{\n pMember2 : string;\n pMember2 : Child[]; //Including all original members\n}\n```\n\n```text\nplainToClass\n```\n\n```text\n@Expose()\n```\n\n```text\nplainToClass(parentEntityFromDB, ParentDTO)\n```\n\n```text\n@Exclude()\nexport class ParentDTO{\n\n @Expose()\n pMember2 : string;\n\n @Expose()\n @Type(() => ChildDto)\n pMember2 : ChildDto[];\n}\n```\n\n```text\n@Type\n```\n\n```text\n@Type\n```\n\n```text\nplainToClass\n```\n\n```text\n@Exclude\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":158,"estimatedTokens":581}}441{"id":"stack-67527934","source":"stackoverflow","questionId":67527934,"title":"typeorm: force mysql2 if mysql is installed","tags":["mysql","node.js","typeorm","mysql-connector"],"text":"Title: typeorm: force mysql2 if mysql is installed\nTags: mysql, node.js, typeorm, mysql-connector\nSource: Stack Overflow\n\nQuestion:\nI know this is a special use case, but I have both `mysql` and `mysql2` packages installed and I need to test both of them.\nHowever as my understanding typeorm will first check if `mysql` is in the `node_modules` and use it.\n\nHow can I force `mysql2` to be used instead? Or programmatically switch between them?\nThanks\n\n========================================\n\nTop Answer:\nhttps://i.sstatic.net/GaC0j.png\n\nIn `MysqlConnectionOptions` have the driver object and defaults to `require(\"mysql\")`, you can set it to `require(\"mysql2\")`. Hope can help u.\n\n========================================\n\nCode:\n```text\nmysql\n```\n\n```text\nmysql2\n```\n\n```text\nmysql\n```\n\n```text\nnode_modules\n```\n\n```text\nmysql2\n```\n\n```js\n// for 0.2.x\n{\n driver: PlatformTools.load('mysql2'),\n //...other options\n}\n// for 0.3.x\n{\n connectorPackage: 'mysql2'\n //other options\n}\n```\n\n```yaml\ndefault:\n type: mysql #=TYPEORM_CONNECTION\n driver: {} #THIS'LL FORCE TO mysql2\n host: localhost #=TYPEORM_HOST\n port: 3306 #=TYPEORM_PORT\n username: xxxx #=TYPEORM_USERNAME\n password: xxxxx #=TYPEORM_PASSWORD\n database: xxx #=TYPEORM_DATABASE\n entities: #=TYPEORM_ENTITIES\n - dist/**/*.entity.js\n migrations: #=TYPEORM_MIGRATIONS\n - migration/*.js\n cli:\n migrationsDir: migration #=TYPEORM_MIGRATIONS_DIR\n```\n\n```text\nyml\n```\n\n```text\normconfig.yml\n```\n\n```text\ndefault.driver\n```\n\n```text\nyml\n```\n\n```text\normconfig.*\n```\n\n```text\nMysqlConnectionOptions\n```\n\n```text\nrequire(\"mysql\")\n```\n\n```text\nrequire(\"mysql2\")\n```\n\n========================================\n\nComments:\n- Not sure if this was released later. But thanks indeed! I will accept this as the correct answer.","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":15,"totalLines":107,"estimatedTokens":447}}442{"id":"stack-68187198","source":"stackoverflow","questionId":68187198,"title":"TypeORM relation with a field apart from id","tags":["javascript","node.js","typescript","typeorm"],"text":"Title: TypeORM relation with a field apart from id\nTags: javascript, node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI wanted to create a one-to-many relation in TypeORM with a field other than id, the usual relation looks like this, but in the same example, lets say for instance the `User` table's column `name` was also unique, now I want to reference that in the relation, which then the foreign key in photos would contain value of `name` and give it a different column name in `Photos` table other than `userId` to be e.g. `userName`, how exactly would i do that, am stuck and frankly hove no idea how to proceed.\n\n========================================\n\nTop Answer:\n```\n@Entity()\nexport class Photo {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n url: string;\n\n @ManyToOne(() => User, user => user.photos)\n @JoinColumn({ name: 'userName' }) // Photo, photo => photo.user)\n photos: Photo[];\n}\n```\n\n========================================\n\nCode:\n```text\nUser\n```\n\n```text\nname\n```\n\n```text\nname\n```\n\n```text\nPhotos\n```\n\n```text\nuserId\n```\n\n```text\nuserName\n```\n\n```js\n@Entity()\nexport class Photo {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n url: string;\n\n @ManyToOne(() => User, user => user.photos)\n @JoinColumn({ name: 'userName', referencedColumnName: 'name' })\n user: User;\n\n}\n```\n\n```js\nreferencedColumnName: 'userName'\n```\n\n```text\nid\n```\n\n```text\nreferencedColumnName: '<column name here>'\n```\n\n```text\n@JoinColumn()\n```\n\n```text\nuser_name\n```\n\n```text\nuserName\n```\n\n```text\n@Entity()\nexport class Photo {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n url: string;\n\n @ManyToOne(() => User, user => user.photos)\n @JoinColumn({ name: 'userName' }) // < -- add this line\n user: User;\n\n}\n\n\n@Entity()\nexport class User {\n\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n name: string;\n\n @OneToMany(() => Photo, photo => photo.user)\n photos: Photo[];\n}\n```\n\n========================================\n\nComments:\n- This will still use the primary id of user in photos table, i want to use the name to be the value of the `userName` column in the photos table","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":14,"totalLines":129,"estimatedTokens":543}}443{"id":"stack-57473726","source":"stackoverflow","questionId":57473726,"title":"NestJS can't resolve dependencies of the AuthServices","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: NestJS can't resolve dependencies of the AuthServices\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nAfter first problem with JWT_MODULE_OPTION, back to old problem who I thought I was fixed. It turned out that when I \"fix\" old problem create the new with JWT. \n\n**So again can't compile:**\n\n*Nest can't resolve dependencies of the AuthService (?, RoleRepository, JwtService). Please make sure that the argument at index [0] is available in the AppModule context. +25ms*\n\nIt's really strange, because this way work on another my project and can't understand where I'm wrong. Here is the **auth.service.ts**:\n\n```\n@Injectable()\nexport class AuthService {\n constructor(\n @InjectRepository(User) private readonly userRepo: Repository,\n @InjectRepository(Role) private readonly rolesRepo: Repository,\n private readonly jwtService: JwtService,\n ) { }\n```\n\nIt get role and `jwtService` but the problem is with `User`, the path is correct. Here is **app.module.ts**:\n\n```\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n imports: [ConfigModule, AuthModule],\n inject: [ConfigService],\n useFactory: async (configService: ConfigService) => ({\n type: configService.dbType as any,\n host: configService.dbHost,\n port: configService.dbPort,\n username: configService.dbUsername,\n password: configService.dbPassword,\n database: configService.dbName,\n entities: ['./src/data/entities/*.ts'],\n }),\n }),\n ],\n controllers: [AppController, AuthController],\n providers: [AuthService],\n})\nexport class AppModule { }\n```\n\nHave the same compile error for controllers & providers & can't understand what is wrong...\n\n========================================\n\nTop Answer:\nThe global problem was that I try to add AuthService & AuthController twice. So I remove them from **app.module.ts** and just export AuthService from **auth.module.ts**:\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class AuthService {\n constructor(\n @InjectRepository(User) private readonly userRepo: Repository<User>,\n @InjectRepository(Role) private readonly rolesRepo: Repository<Role>,\n private readonly jwtService: JwtService,\n ) { }\n```\n\n```text\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({\n imports: [ConfigModule, AuthModule],\n inject: [ConfigService],\n useFactory: async (configService: ConfigService) => ({\n type: configService.dbType as any,\n host: configService.dbHost,\n port: configService.dbPort,\n username: configService.dbUsername,\n password: configService.dbPassword,\n database: configService.dbName,\n entities: ['./src/data/entities/*.ts'],\n }),\n }),\n ],\n controllers: [AppController, AuthController],\n providers: [AuthService],\n})\nexport class AppModule { }\n```\n\n```text\njwtService\n```\n\n```text\nUser\n```\n\n```text\n@Module({\n imports: [\n TypeOrmModule.forRootAsync({...}),\n TypeOrmModule.forFeature([User, Role]),\n ],\n```\n\n```text\nTypeOrmModule.forFeature([User])\n```\n\n```text\nAppModule\n```\n\n```text\nforFeature\n```\n\n```text\nforRoot\n```\n\n========================================\n\nComments:\n- You are right, thanks. I have all entities in forFeature in CoreModule on my previous project. But when add User & Role in forFeature receive another compile error with AuthService: Nest can't resolve dependencies of the AuthService (UserRepository, RoleRepository, ?). Please make sure that the argument at index [2] is available in the AppModule context. +21ms I tried to add jwtService in forFeature but doesn't work...\n- I added - inject: [ConfigService, JwtService], and think it's ok for now, but get new error...\n- The `jwtService` has nothing to do with the `TypeormModule`. When you import the `JwtModule` it exposes the `JwtService`; but only in the module with the import. Have a look at this thread to learn how you can export a service to use it in other modules: stackoverflow.com/questions/51819504/…\n- Yes, when inject JwtService a receive this error --- Nest can't resolve dependencies of the TypeOrmModuleOptions (ConfigService, ?). Please make sure that the argument at index [1] is available in the TypeOrmCoreModule context. +25ms --- if I'll fix this, back to AuthService error...","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":9,"totalLines":130,"estimatedTokens":1068}}444{"id":"stack-55088017","source":"stackoverflow","questionId":55088017,"title":"How to query data in mutiple @ManyToMany in Nest.js","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: How to query data in mutiple @ManyToMany in Nest.js\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nAs we all know that use `relations` to query data which has a relation `ManyToMany`. But how to query in mutiple `ManyToMany`? Maybe you are confused, please let me explain to you.\n\n```\n@Entity()\nexport class Article {\n @ManyToMany(type => Classification, classification => classification.articles)\n classifications: Classification[];\n\n @ManyToMany(type => User, user => user.articles)\n users: User[];\n}\n\n@Entity()\nexport class Classification {\n @ManyToMany(type => Article, article => article.classifications)\n @JoinTable()\n articles: Article[];\n}\n\n@Entity()\nexport class User {\n @ManyToMany(type => Article, article => article.users)\n @JoinTable()\n articles: Article[];\n}\n```\n\nNow I wanna use `classificationRepository` to query data relate `Article`, and the `Article` should relate `User`.\n\nBut idk how to do that.\n\n========================================\n\nTop Answer:\nIf articles has a bi directional many-to-many relation to categories and you want to get the articles of a category. You can load the articles on the category and then return them\n\n```\nconst category = await this.categoryRepository.findOne(params.id, {\n relations: [\"articles\"]\n});\n\nreturn category.articles\n```\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class Article {\n @ManyToMany(type => Classification, classification => classification.articles)\n classifications: Classification[];\n\n @ManyToMany(type => User, user => user.articles)\n users: User[];\n}\n\n@Entity()\nexport class Classification {\n @ManyToMany(type => Article, article => article.classifications)\n @JoinTable()\n articles: Article[];\n}\n\n@Entity()\nexport class User {\n @ManyToMany(type => Article, article => article.users)\n @JoinTable()\n articles: Article[];\n}\n```\n\n```text\nrelations\n```\n\n```text\nManyToMany\n```\n\n```text\nManyToMany\n```\n\n```text\nclassificationRepository\n```\n\n```text\nArticle\n```\n\n```text\nArticle\n```\n\n```text\nUser\n```\n\n```text\nthis.categoryRepository.createQueryBuilder('classification')\n .leftJoinAndSelect(\n 'classification.articles',\n 'article',)\n .leftJoinAndSelect(\n 'article.users',\n 'user')\n .where('article.id = :id', { id: '1' })\n .getMany();\n```\n\n```text\nconst category = await this.categoryRepository.findOne(params.id, {\n relations: [\"articles\"]\n});\n\nreturn category.articles\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":124,"estimatedTokens":613}}445{"id":"stack-63788437","source":"stackoverflow","questionId":63788437,"title":"How can I get values from a TypeORM property decorator","tags":["javascript","typescript","typeorm"],"text":"Title: How can I get values from a TypeORM property decorator\nTags: javascript, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\n```\nimport { PrimaryColumn, Column } from 'typeorm';\n\nexport class LocationStatus {\n @PrimaryColumn({ name: 'location_id' })\n locationId: string;\n\n @Column({ name: 'area_code', type: 'int' })\n areaCode: number;\n}\n```\n\nI spent the past few hours trying to figure it out how to retrieve a name property value `location_id` and `area_code` from a property decorator `@Column()`, but no luck. I'm not sure whether it's even possible to get a list of properties or not.\n\n========================================\n\nCode:\n```js\nimport { PrimaryColumn, Column } from 'typeorm';\n\nexport class LocationStatus {\n @PrimaryColumn({ name: 'location_id' })\n locationId: string;\n\n @Column({ name: 'area_code', type: 'int' })\n areaCode: number;\n}\n```\n\n```text\nlocation_id\n```\n\n```text\narea_code\n```\n\n```text\n@Column()\n```\n\n```js\nconst global_context = ??? // depends on your environment\nconst property_to_look_for = `areaCode`\nconst name = global_context.typeormMetadataArgsStorage\n .columns\n .filter(col => col.propertyName === property_to_look_for && col.target === LocationStatus)\n .options\n .name\nconsole.log(name)\n```\n\n```js\nimport { getMetadataArgsStorage, InsertResult } from 'typeorm';\n\nexport class PinLocationStatusRepository extends Repository<PinLocationStatus> {\n // Column names in this array, the value should not be modified.\n // For instance, the location_id value \"location_ko_01\" won't be changed.\n private static immutableColumnNames = ['location_id', ...]; \n\n private static mutableColumnFound(name: string): boolean {\n return PinLocationStatusRepository.immutableColumnNames.every(colName => colName !== name);\n }\n\n savePinLocation(state: PinLocationStatus): Promise<InsertResult> {\n const columns = getMetadataArgsStorage()\n .columns.filter(({ target }) => target === PinLocationStatus)\n .map(({ options, propertyName }) => (!options.name ? propertyName : options.name))\n .reduce((columns, name) => {\n if (PinLocationStatusRepository.mutableColumnFound(name)) {\n columns.push(name);\n }\n return columns;\n }, []);\n\n return this.createQueryBuilder()\n .insert()\n .into(PinLocationStatus)\n .values(state)\n .orUpdate({ overwrite: columns }) // ['area_code']\n .execute();\n }\n}\n```\n\n```text\ntypeorm\n```\n\n```text\ntypeormMetadataArgsStorage\n```\n\n```text\nwindow.typeormMetadataArgsStorage\n```\n\n```text\nglobal.typeormMetadataArgsStorage\n```\n\n```text\nNest\n```\n\n```text\n@Column()\n```\n\n```text\noverwrite\n```\n\n```text\narea_code\n```\n\n========================================\n\nComments:\n- `globalThis` would be appropriate.\n- @AluanHaddad, thanks... but is it really universally accepted way by now?`Implementation progress` section on the *MDN* is not so optimistic.\n- True. My inclination would be to polyfill it but it's not a feature that can be polyfilled.\n- Thank you for your kind answer. I'd like to edit your answer, but the queue is currently full.\n- I've just added the code snippet below your answer. Once again, thank you very much!\n- @JeffMinsungKim, you're welcome. Accepted you edit, but I think it'd be nice if you explain: 1) what exactly are you trying to achieve with this snippet 2) what is the issue with immutable columns 3) and maybe remove `Promise`, as it seems to be unrelated to the part of code you've posted.\n- @x00, I've fixed the edit. I've also added the return statement, so kept the `Promise` as a return type.","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":132,"estimatedTokens":889}}446{"id":"stack-57774624","source":"stackoverflow","questionId":57774624,"title":"Typeorm get relations for array column of ids","tags":["postgresql","typeorm"],"text":"Title: Typeorm get relations for array column of ids\nTags: postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am looking to add a column of `id`'s to `Invoice` with the items from the invoice.\n\nI'm getting the error\n\n Entity metadata for Invoice#invoiceItems was not found.\n\nI've tried these two options:\n\n```\nclass Invoice {\n\n @OneToMany(type => InvoiceItem, invoiceItem => invoiceItem.id)\n @JoinColumn()\n invoiceItems: InvoiceItem[]\n @RelationId((self: Invoice) => self.invoiceItems)\n invoiceItemIds: number[]\n\n}\n```\n\nand\n\n```\nclass Invoice {\n\n @OneToMany(type => InvoiceItem, invoiceItem => invoiceItem.id)\n @JoinColumn()\n invoiceItems: InvoiceItem[]\n @Column({ type: PostgresColumns.number, array: true, nullable: false, default: {} })\n invoiceItemIds: number[]\n```\n\nHow can I add relations for an array of ids?\n\n========================================\n\nCode:\n```text\nclass Invoice {\n\n @OneToMany(type => InvoiceItem, invoiceItem => invoiceItem.id)\n @JoinColumn()\n invoiceItems: InvoiceItem[]\n @RelationId((self: Invoice) => self.invoiceItems)\n invoiceItemIds: number[]\n\n}\n```\n\n```text\nclass Invoice {\n\n @OneToMany(type => InvoiceItem, invoiceItem => invoiceItem.id)\n @JoinColumn()\n invoiceItems: InvoiceItem[]\n @Column({ type: PostgresColumns.number, array: true, nullable: false, default: {} })\n invoiceItemIds: number[]\n```\n\n```text\nid\n```\n\n```text\nInvoice\n```\n\n```text\n@Entity()\nclass Invoice { \n @OneToMany(type => InvoiceItem, invoiceItem => invoiceItem.invoice) \n invoiceItems: InvoiceItem[];\n\n @RelationId((self: Invoice) => self.invoiceItems) \n invoiceItemIds: number[] \n}\n\n@Entity()\nclass InvoiceItem { \n ...\n @ManyToOne(type => Invoice, invoice => invoice.invoiceItems) \n invoice: Invoice;\n ...\n}\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":90,"estimatedTokens":439}}447{"id":"stack-69026944","source":"stackoverflow","questionId":69026944,"title":"typeorm get repository from name","tags":["javascript","node.js","nestjs","typeorm"],"text":"Title: typeorm get repository from name\nTags: javascript, node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nTo create REST API for any entity.\nCan I use table name instead of `Entity` for queryBuilder?\n\n```\nconst repository = getRepository(\"Table_Name\"); // instead of Entity, I want use string `Any Table name`.\nrepository.createQueryBuilder( ... )\n .leftJoin(['TableA', 'TableB'])\n .orderBy(\"TableA.name\")\n .offset(5)\n .limit(10);\n```\n\n========================================\n\nCode:\n```js\nconst repository = getRepository(\"Table_Name\"); // instead of Entity, I want use string `Any Table name`.\nrepository.createQueryBuilder( ... )\n .leftJoin(['TableA', 'TableB'])\n .orderBy(\"TableA.name\")\n .offset(5)\n .limit(10);\n```\n\n```text\nEntity\n```\n\n```js\nconst tableName = \"Table_Name\";\nconst entityMetadata = getConnection().entityMetadatas.find((metadata) => metadata.tableName === tableName);\nconst repository = getRepository(entityMetadata.name);\n```\n\n```text\nTableA\n```\n\n```text\nTableB\n```\n\n========================================\n\nComments:\n- You mean something like `userRepository.createQueryBuilder('user')`?\n- thanks, `getRepository(\"TableName\")` is enoug for my answer. if possible, please update with only \"getRepository(\"TableName\")\"\n- Sorry, I didn't . In my answer, I am trying to show you how to get the entity's name so that you can pass it inside `getRepository` because it does not take the table name as a parameter\n- by the way, this is my answer, only I don't need `entityMetadata = getConnection().entityMetadatas.find((metadata) => metadata.tableName === tableName);`\n- Sorry, I'm confused. If you didn't need it, how are you going to pass the name of the entity to `getRepository` function? Maybe you can update my answer with the solution you have :-)","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":55,"estimatedTokens":449}}448{"id":"stack-69203861","source":"stackoverflow","questionId":69203861,"title":"How to return the entity with its relations after saving it?","tags":["express","typeorm","typegraphql"],"text":"Title: How to return the entity with its relations after saving it?\nTags: express, typeorm, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI am building a storage application, with GraphQL as the backend, using Typegraphql and TypeORM.\n\nThe categories need to be added separately and then when adding a product, you choose from a dropdown one of the available categories. This in turn passes the categoryId to the product in a one-to-many/many-to-one relationship.\n\nHere is my Category entity:\n\n```\nimport {\n Entity,\n PrimaryColumn,\n Column,\n BaseEntity,\n Generated,\n OneToMany\n} from 'typeorm';\nimport Product from './Product';\n\n@ObjectType()\n@Entity('categories')\nexport default class Category extends BaseEntity {\n @Field()\n @PrimaryColumn()\n @Generated('uuid')\n categoryId: string;\n\n @Field()\n @Column()\n categoryName: string;\n\n @OneToMany(() => Product, (product: Product) => product.category)\n products: Product[];\n}\n```\n\nand here is my Product entity\n\n```\nimport {\n Entity,\n PrimaryColumn,\n Column,\n BaseEntity,\n Generated,\n ManyToOne,\n JoinColumn\n} from 'typeorm';\nimport Category from './Category';\n\n@ObjectType()\n@Entity('products')\nexport default class Product extends BaseEntity {\n @Field()\n @PrimaryColumn()\n @Generated('uuid')\n productID: string;\n\n @Field()\n @Column()\n productName: string;\n\n @Field(() => Category)\n @ManyToOne(() => Category, (category: Category) => category.products, {\n cascade: true,\n lazy: true\n })\n @JoinColumn()\n category: Category;\n\n @Field()\n @Column()\n productQuantity: number;\n\n @Field()\n @Column({ type: 'decimal', precision: 2 })\n productPrice: number;\n\n @Field()\n @Column({ type: 'decimal', precision: 2 })\n productPriceRA: number;\n\n @Field()\n @Column({ type: 'decimal', precision: 2 })\n productPriceKK: number;\n\n @Field()\n @Column('varchar', { length: 255 })\n productSupplier: string;\n\n @Field()\n @Column('varchar', { length: 255 })\n productOrderLink: string;\n\n @Field()\n @Column('longtext')\n productImage: string;\n}\n```\n\nFor the save mutation, I've created an Input type as well:\n\n```\nexport default class ProductInput implements Partial {\n @Field()\n productName: string;\n\n @Field(() => String)\n category: Category;\n\n @Field()\n productQuantity: number;\n\n @Field()\n productPrice: number;\n\n @Field()\n productPriceRA: number;\n\n @Field()\n productPriceKK: number;\n\n @Field()\n productSupplier: string;\n\n @Field()\n productOrderLink: string;\n\n @Field()\n productImage: string;\n}\n```\n\nThe relations work, as I am able to query the products, along with their category data with the following query:\n\n```\n{\n getProducts {\n productID\n productName\n category {\n categoryId\n categoryName\n }\n }\n}\n```\n\nHowever, when saving a product it always returns\n`\"message\": \"Cannot return null for non-nullable field Category.categoryName.\"`\n\nThis is the Mutation's code in the Resolver:\n\n```\n@Mutation(() => Product, { description: 'Add new product' })\n async addProduct(\n @Arg('product') productInput: ProductInput\n ): Promise {\n try {\n const product = await Product.create(productInput).save();\n\n console.log('product: ', product);\n return product;\n } catch (error) {\n return error;\n }\n }\n```\n\nI've been trying different things, however nothing seems to work and I am wondering if it's even possible to directly return the entity with its relations. If it's not, the other option I can think of is to return true/false based on the result and re-query all of the data. But this seems very inefficient and I am actively trying to avoid going this route.\n\nAny help will be much appreciated.\n\n========================================\n\nTop Answer:\nGraphQL uses an notation to recognize data. You can see it as `__typename` object property. Of course, this must be turned on in the GraphQL server configuration. If you see it, it's already clear. You can reach the correct result without refetching the relation changes in the cached data on the client side with a trick like this.\nFor example, let's say we have updated the Product with category. In the data to return from the update mutation, it is sufficient to return only the `id` of the relation.\n\n***For this to work, category and product must be cached separately on the client beforehand.***\n\nfor example:\n\n```\nmutation UpdateProduct($product: UpdateProductInput!) {\n updateProduct(product: $product) {\n id\n title\n category {\n id\n }\n }\n}\n```\n\nYou can also write in writeFragment, which is a separate method, which is the most stingy, but it can make your job difficult in nested data.\n\n```\nexport class ProductFragmentService {\n constructor(private apollo: Apollo) {}\n\n updateProduct(product: Product): void {\n const client = this.apollo.client;\n client.writeFragment({\n id: `Product:${product.id}`,\n fragment: gql`\n fragment UpdateProductCategoryFragment on Product {\n __typename\n id\n title\n category {\n id\n }\n }\n `,\n data: {\n __typename: 'Product',\n ...product,\n },\n });\n }\n}\n```\n\nIf you want all the fields belonging to category, you need to send them to resolver and return as a response from there. Otherwise, yes, it gives a warning that I could not find the name property.\n\nThe more profitable way of doing it is to send this data to the resolver with the input, as I wrote above, and return to the client as a response from the server.\n\nIf you still have to make another SQL request, it is necessary to call the same id after registration.\n\n```\n@Authorized()\n@Mutation(() => Product, { description: 'Add new product' })\n async addProduct(\n @Arg('product') productInput: ProductInput\n ): Promise {\n await this.productRepo.save(productInput);\n return await this.productRepo.findOne({ where: { id: productInfo.id } });\n }\n```\n\nthat's all :)\n\n========================================\n\nCode:\n```text\nimport {\n Entity,\n PrimaryColumn,\n Column,\n BaseEntity,\n Generated,\n OneToMany\n} from 'typeorm';\nimport Product from './Product';\n\n@ObjectType()\n@Entity('categories')\nexport default class Category extends BaseEntity {\n @Field()\n @PrimaryColumn()\n @Generated('uuid')\n categoryId: string;\n\n @Field()\n @Column()\n categoryName: string;\n\n @OneToMany(() => Product, (product: Product) => product.category)\n products: Product[];\n}\n```\n\n```text\nimport {\n Entity,\n PrimaryColumn,\n Column,\n BaseEntity,\n Generated,\n ManyToOne,\n JoinColumn\n} from 'typeorm';\nimport Category from './Category';\n\n@ObjectType()\n@Entity('products')\nexport default class Product extends BaseEntity {\n @Field()\n @PrimaryColumn()\n @Generated('uuid')\n productID: string;\n\n @Field()\n @Column()\n productName: string;\n\n @Field(() => Category)\n @ManyToOne(() => Category, (category: Category) => category.products, {\n cascade: true,\n lazy: true\n })\n @JoinColumn()\n category: Category;\n\n @Field()\n @Column()\n productQuantity: number;\n\n @Field()\n @Column({ type: 'decimal', precision: 2 })\n productPrice: number;\n\n @Field()\n @Column({ type: 'decimal', precision: 2 })\n productPriceRA: number;\n\n @Field()\n @Column({ type: 'decimal', precision: 2 })\n productPriceKK: number;\n\n @Field()\n @Column('varchar', { length: 255 })\n productSupplier: string;\n\n @Field()\n @Column('varchar', { length: 255 })\n productOrderLink: string;\n\n @Field()\n @Column('longtext')\n productImage: string;\n}\n```\n\n```text\nexport default class ProductInput implements Partial<Product> {\n @Field()\n productName: string;\n\n @Field(() => String)\n category: Category;\n\n @Field()\n productQuantity: number;\n\n @Field()\n productPrice: number;\n\n @Field()\n productPriceRA: number;\n\n @Field()\n productPriceKK: number;\n\n @Field()\n productSupplier: string;\n\n @Field()\n productOrderLink: string;\n\n @Field()\n productImage: string;\n}\n```\n\n```text\n{\n getProducts {\n productID\n productName\n category {\n categoryId\n categoryName\n }\n }\n}\n```\n\n```text\n@Mutation(() => Product, { description: 'Add new product' })\n async addProduct(\n @Arg('product') productInput: ProductInput\n ): Promise<Product | any> {\n try {\n const product = await Product.create(productInput).save();\n\n console.log('product: ', product);\n return product;\n } catch (error) {\n return error;\n }\n }\n```\n\n```text\n\"message\": \"Cannot return null for non-nullable field Category.categoryName.\"\n```\n\n```text\ntry {\n const { productID } = await Product.create(productInput).save();\n\n return await Product.findOne(productID);\n } catch (error) {\n return error;\n }\n```\n\n```text\nmutation UpdateProduct($product: UpdateProductInput!) {\n updateProduct(product: $product) {\n id\n title\n category {\n id\n }\n }\n}\n```\n\n```js\nexport class ProductFragmentService {\n constructor(private apollo: Apollo) {}\n\n updateProduct(product: Product): void {\n const client = this.apollo.client;\n client.writeFragment({\n id: `Product:${product.id}`,\n fragment: gql`\n fragment UpdateProductCategoryFragment on Product {\n __typename\n id\n title\n category {\n id\n }\n }\n `,\n data: {\n __typename: 'Product',\n ...product,\n },\n });\n }\n}\n```\n\n```js\n@Authorized()\n@Mutation(() => Product, { description: 'Add new product' })\n async addProduct(\n @Arg('product') productInput: ProductInput\n ): Promise<Product> {\n await this.productRepo.save(productInput);\n return await this.productRepo.findOne({ where: { id: productInfo.id } });\n }\n```\n\n```text\n__typename\n```\n\n```text\nid\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":470,"estimatedTokens":2401}}449{"id":"stack-46915605","source":"stackoverflow","questionId":46915605,"title":"Express routing using TypeORM with Javascript","tags":["javascript","node.js","express","typeorm"],"text":"Title: Express routing using TypeORM with Javascript\nTags: javascript, node.js, express, typeorm\nSource: Stack Overflow\n\nQuestion:\nLooking at the TypeORM sites examples, there are some showing routing usage done with TypeScript.\nSince TypeORM can use javascript instead of TypeScript, would anyone be able to point me in the right direction on how to accomplish Express routing with javascript.\nTypeScript uses Controllers and builds routes using json route structure. \nNot really sure how to translate that to javascript as the javascript example doesnt even use controllers.\n\nWhat would be JS alternative to \n\n```\nimport {getConnection} from \"typeorm\";\n```\n\nI tried\n\n```\nvar orm = require(\"typeorm\"); \nvar conn = orm.getConnection();\n```\n\nbut it didnt work :(\n\nAdditionally, i wanted to create entities in javascript instead of typescript so i tried something like this :\n\n```\nmodule.exports = {\n name: \"EventType\",\n columns: {\n EventTypeId: {\n primary: true,\n type: \"int\",\n generated: true\n },\n EventTypeUUID: {\n type: \"uniqueidentifier\"\n },\n Title: {\n type: \"varchar\"\n },\n IconId: {\n type: \"int\"\n },\n BackgroundColor: {\n type: \"varchar\"\n }\n }\n};\n```\n\nand tried getting the result in controller like this :\n\n```\nreturn connection().manager.find(EventType);\n```\n\nand getting thos error :\n\n```\nEntityMetadataNotFound: No metadata for \"[object Object]\" was found.\n```\n\nThanks in advance.\n\n========================================\n\nTop Answer:\nFor appropriate use of TypeORM with JavaScript / node js, refer below url.\n\nUsage with Javascript\n\n========================================\n\nCode:\n```text\nimport {getConnection} from \"typeorm\";\n```\n\n```text\nvar orm = require(\"typeorm\"); \nvar conn = orm.getConnection();\n```\n\n```text\nmodule.exports = {\n name: \"EventType\",\n columns: {\n EventTypeId: {\n primary: true,\n type: \"int\",\n generated: true\n },\n EventTypeUUID: {\n type: \"uniqueidentifier\"\n },\n Title: {\n type: \"varchar\"\n },\n IconId: {\n type: \"int\"\n },\n BackgroundColor: {\n type: \"varchar\"\n }\n }\n};\n```\n\n```text\nreturn connection().manager.find(EventType);\n```\n\n```text\nEntityMetadataNotFound: No metadata for \"[object Object]\" was found.\n```\n\n```text\ntypeorm init --name my-project --express --database postgres\n```\n\n========================================\n\nComments:\n- Thanks for your reply pleerock. Is it possible for the init command to generate new project in javascript instead of typescript? (I'm trying to use TypeORM and javascript based entities and controllers, but cannot find such example)\n- What would be JS alternatiove to `import {getConnection} from \"typeorm\";`?\n- it really depend on which javascript version we are talking about... For example `import {getConnection} from \"typeorm\";` is a valid ES6 syntax. Another question if platform you are using supports it. I strongly recommend you to use typescript since it provides you all latest javascript features without pain. there is no generation functionality for vanilla javascript yet\n- alternative to `import {getConnection} from \"typeorm\";` is `var getConnection = require(\"typeorm\").getConnection`\n- I tried : `var orm = require(\"typeorm\"); var conn = orm.getConnection();` but it didnt work, seems like the same thing ..hm.. I'm gonna try this and then edit and adjust my question so you can answer it and get deserved credit, while the question and answer can help others as well. Thank you so much for the replies.\n- @MladenOršolić in the meanwhile, this example was created for typeorm using vanilla javascript. also, if you're worried about es6 modules support, the equivalent expression in commonjs would be `const {getConnection} = require('typeorm')` (if you still have sufficient engine support for destructuring), or `const getConnection = require('typeorm').getConnection` (if you don't).","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":131,"estimatedTokens":983}}450{"id":"stack-62922849","source":"stackoverflow","questionId":62922849,"title":"TypeORM Many-to-Many join table extra column","tags":["typescript","orm","typeorm"],"text":"Title: TypeORM Many-to-Many join table extra column\nTags: typescript, orm, typeorm\nSource: Stack Overflow\n\nQuestion:\nI've a simple many to many relationship with TypeORM\n\n### User Entity\n\n```\n@Entity({ name: 'users' })\nexport class User {\n @PrimaryColumn()\n id: string;\n\n @Column()\n email: string;\n\n @Column()\n password: string;\n\n @ManyToMany((type) => Organization, (organization) => organization.users)\n @JoinTable({\n name: 'user_organizations',\n joinColumn: {\n name: 'user_id',\n referencedColumnName: 'id',\n },\n inverseJoinColumn: {\n name: 'organization_id',\n referencedColumnName: 'id',\n },\n })\n organizations: Organization[];\n```\n\n### Organization Entity\n\n```\n@Entity({ name: 'organizations' })\nexport class Organization {\n @PrimaryColumn()\n id: string;\n\n @Column()\n name: string;\n\n @ManyToMany((type) => User, (user) => user.organizations)\n users: User[];\n\n}\n```\n\nMy goal is to create a relationship which not only defines which user relates to which organisation it should also contains information in which role the user is related to a organisation. My idea was to extend the relation table with an extra `role` column for that.\n\n```\ncreate table user_organizations(\n user_id varchar(64) not null,\n organization_id varchar(64) not null,\n role varchar(64) not null,\n foreign key (user_id) references users(id),\n foreign key (organization_id) references organizations(id),\n);\n```\n\nMy question is how to store the role in the database. Currently I'm doing something like this.\n\n```\nlet user = new User();\nlet organization = new Organization();\norganization.name = name;\norganization.users = [user];\norganization = await this.organizationRepository.save(organization);\n```\n\nHow can I fill also the `role` column via TypeORM?\n\n========================================\n\nCode:\n```text\n@Entity({ name: 'users' })\nexport class User {\n @PrimaryColumn()\n id: string;\n\n @Column()\n email: string;\n\n @Column()\n password: string;\n\n @ManyToMany((type) => Organization, (organization) => organization.users)\n @JoinTable({\n name: 'user_organizations',\n joinColumn: {\n name: 'user_id',\n referencedColumnName: 'id',\n },\n inverseJoinColumn: {\n name: 'organization_id',\n referencedColumnName: 'id',\n },\n })\n organizations: Organization[];\n```\n\n```text\n@Entity({ name: 'organizations' })\nexport class Organization {\n @PrimaryColumn()\n id: string;\n\n @Column()\n name: string;\n\n @ManyToMany((type) => User, (user) => user.organizations)\n users: User[];\n\n}\n```\n\n```text\ncreate table user_organizations(\n user_id varchar(64) not null,\n organization_id varchar(64) not null,\n role varchar(64) not null,\n foreign key (user_id) references users(id),\n foreign key (organization_id) references organizations(id),\n);\n```\n\n```text\nlet user = new User();\nlet organization = new Organization();\norganization.name = name;\norganization.users = [user];\norganization = await this.organizationRepository.save(organization);\n```\n\n```text\nrole\n```\n\n```text\nrole\n```\n\n```text\nRole\n```\n\n```text\nuser_organizations\n```\n\n```text\nuser_organisations\n```\n\n```text\nUser.ID\n```\n\n```text\nOrganisation.ID\n```\n\n```text\nRoles\n```\n\n```text\nUserOrganisations\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":175,"estimatedTokens":792}}451{"id":"stack-57973320","source":"stackoverflow","questionId":57973320,"title":"Many to Many Joins in TypeORM","tags":["nestjs","typeorm"],"text":"Title: Many to Many Joins in TypeORM\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nWe are currently working on implementing NestJS against our DB. We decided to use TypeORM to give us a strong ORM to use for most of our basic to intermediate queries. However, I am having issues setting up one particular relationship in our entities.\n\nOur table structure comes from an existing system that cannot be modified. It is as follows:\n\n**Employee Table**\n\n```\n+-----------+-----------+---------------+\n| HRCO (PK) | HRRef(PK) | udDisplayName |\n+-----------+-----------+---------------+\n| 2 | 323 | John |\n| 2 | 500 | Larry |\n| 1 | 29 | Jim |\n+-----------+-----------+---------------+\n```\n\n```\n**Skill Table**\n+----------+----------+----------------+\n| HRCo(PK) | Code(PK) | Description |\n+----------+----------+----------------+\n| 2 | CODE1 | Test Class |\n| 2 | CODE2 | Crane Training |\n| 1 | CODE1 | Truck Training |\n+----------+----------+----------------+\n```\n\n```\n**Join Table - EmployeeSkills**\n+-----------+---------------+-----------+------------+\n| HRCO (FK) | Employee (FK) | Code (FK) | Expires |\n+-----------+---------------+-----------+------------+\n| 2 | 323 | CODE1 | 2019-01-01 |\n| 2 | 323 | CODE2 | 2020-01-01 |\n| 1 | 29 | CODE1 | 2020-01-01 |\n+-----------+---------------+-----------+------------+\n```\n\nI recognize this is a many-to-many relationship that has a composite foreign key. Most of the NestJS docs lead you down using the ManyToMany and OneToMany x 2 pattern of establishing the relationship. However, those seem to only work if the joiner table has one key for each table rather than a composite.\n\nRight now my classes look like the following:\n\n**Skills**\n\n```\nimport { Entity, Column, PrimaryColumn, ManyToOne, OneToMany } from \"typeorm\";\nimport { EmployeeToSkillEntity } from \"../employee-to-skill/employee-skill.entity\";\n\n@Entity({name:\"skills\"})\nexport class SkillEntity {\n\n @PrimaryColumn({ name: \"HRCo\" })\n company: number;\n\n @PrimaryColumn({ name: \"Code\" })\n code: number;\n\n \n\n @Column({name:\"Description\"})\n description: Date;\n\n @OneToMany(type => EmployeeToSkillEntity, employeeToSkill => employeeToSkill.code)\n employeeToSkills: EmployeeToSkillEntity[]\n\n}\n```\n\n**Employee**\n\n```\nimport { Entity, Column, PrimaryColumn, OneToMany } from \"typeorm\";\nimport { EmployeeToSkillEntity } from \"../employee-to-skill/employee-skill.entity\";\n\n/**\n * @ignore\n */\n@Entity({name:\"employee\"})\nexport class EmployeeEntity {\n @PrimaryColumn({ name: \"HRCo\" })\n company: number;\n\n @PrimaryColumn({ name: \"HRRef\" })\n employeeNumber: number;\n\n @Column({name: \"udDisplayName\"})\n displayName: string;\n\n @OneToMany(type => EmployeeToSkillEntity, employeeToSkill => employeeToSkill.employee)\n employeeToSkills: EmployeeToSkillEntity[]\n\n}\n```\n\n```\nimport { Entity, Column, PrimaryColumn, ManyToOne, PrimaryGeneratedColumn } from \"typeorm\";\nimport { EmployeeEntity } from \"../employee/employee.entity\";\nimport { SkillEntity } from \"../skill/skill.entity\";\n\n/**\n * @ignore\n */\n@Entity({ name: \"employeeskills\" })\nexport class EmployeeToSkillEntity {\n @PrimaryColumn({ name: \"HRCo\" })\n companyNumber: number;\n\n @PrimaryColumn({ name: \"HRRef\" })\n employeeNumber: number;\n\n @PrimaryColumn({ name: \"Code\" })\n code: string;\n\n @Column({ name: \"CertDate\" })\n certDate: Date;\n\n @Column({ name: \"ExpireDate\" })\n expireDate: Date;\n\n @Column({ name: \"SkillTester\" })\n skillTester: string;\n\n @Column({ name: \"HistSeq\" })\n histSeq: string;\n\n @Column({ name: \"Notes\" })\n notes: string;\n\n @Column({ name: \"UniqueAttchID\" })\n attachmentID: number;\n\n @Column({ name: \"Type\" })\n type: string;\n\n @Column({ name: \"KeyID\" })\n keyID: number;\n\n @Column({ name: \"udLastModDate\" })\n lastModifiedDate: Date;\n\n @Column({ name: \"udLicense\" })\n license: number;\n\n @ManyToOne(type => EmployeeEntity, (employee) => employee.employeeToSkills)\n @JoinColumn([{ name: \"HRCo\", referencedColumnName: \"companyNumber\" }, { name: \"HRRef\", referencedColumnName: \"employeeNumber\" }])\n employee: EmployeeEntity;\n\n @ManyToOne(type => SkillEntity, (skill) => skill.employeeToSkills)\n @JoinColumn([{ name: \"HRCo\", referencedColumnName: \"companyNumber\" }, { name: \"Code\", referencedColumnName: \"code\" }])\n skill: SkillEntity;\n}\n```\n\nHowever, I am getting an error on query generation because I am getting columns for the relationship + the property name like \"skillCode\".\n\nAny help would be appreciated.\n\nThanks\n\n========================================\n\nTop Answer:\nAdding JoinColumn() to the ManyToOne relationships was the key.\n\nYou need to make the column of the current class, to the property of the associated entity. You must do this for each FK you have in the relationship.\n\n========================================\n\nCode:\n```text\n+-----------+-----------+---------------+\n| HRCO (PK) | HRRef(PK) | udDisplayName |\n+-----------+-----------+---------------+\n| 2 | 323 | John |\n| 2 | 500 | Larry |\n| 1 | 29 | Jim |\n+-----------+-----------+---------------+\n```\n\n```text\n**Skill Table**\n+----------+----------+----------------+\n| HRCo(PK) | Code(PK) | Description |\n+----------+----------+----------------+\n| 2 | CODE1 | Test Class |\n| 2 | CODE2 | Crane Training |\n| 1 | CODE1 | Truck Training |\n+----------+----------+----------------+\n```\n\n```text\n**Join Table - EmployeeSkills**\n+-----------+---------------+-----------+------------+\n| HRCO (FK) | Employee (FK) | Code (FK) | Expires |\n+-----------+---------------+-----------+------------+\n| 2 | 323 | CODE1 | 2019-01-01 |\n| 2 | 323 | CODE2 | 2020-01-01 |\n| 1 | 29 | CODE1 | 2020-01-01 |\n+-----------+---------------+-----------+------------+\n```\n\n```ts\nimport { Entity, Column, PrimaryColumn, ManyToOne, OneToMany } from \"typeorm\";\nimport { EmployeeToSkillEntity } from \"../employee-to-skill/employee-skill.entity\";\n\n@Entity({name:\"skills\"})\nexport class SkillEntity {\n\n @PrimaryColumn({ name: \"HRCo\" })\n company: number;\n\n @PrimaryColumn({ name: \"Code\" })\n code: number;\n\n \n\n @Column({name:\"Description\"})\n description: Date;\n\n @OneToMany(type => EmployeeToSkillEntity, employeeToSkill => employeeToSkill.code)\n employeeToSkills: EmployeeToSkillEntity[]\n\n}\n```\n\n```ts\nimport { Entity, Column, PrimaryColumn, OneToMany } from \"typeorm\";\nimport { EmployeeToSkillEntity } from \"../employee-to-skill/employee-skill.entity\";\n\n/**\n * @ignore\n */\n@Entity({name:\"employee\"})\nexport class EmployeeEntity {\n @PrimaryColumn({ name: \"HRCo\" })\n company: number;\n\n @PrimaryColumn({ name: \"HRRef\" })\n employeeNumber: number;\n\n @Column({name: \"udDisplayName\"})\n displayName: string;\n\n @OneToMany(type => EmployeeToSkillEntity, employeeToSkill => employeeToSkill.employee)\n employeeToSkills: EmployeeToSkillEntity[]\n\n}\n```\n\n```ts\nimport { Entity, Column, PrimaryColumn, ManyToOne, PrimaryGeneratedColumn } from \"typeorm\";\nimport { EmployeeEntity } from \"../employee/employee.entity\";\nimport { SkillEntity } from \"../skill/skill.entity\";\n\n/**\n * @ignore\n */\n@Entity({ name: \"employeeskills\" })\nexport class EmployeeToSkillEntity {\n @PrimaryColumn({ name: \"HRCo\" })\n companyNumber: number;\n\n @PrimaryColumn({ name: \"HRRef\" })\n employeeNumber: number;\n\n @PrimaryColumn({ name: \"Code\" })\n code: string;\n\n @Column({ name: \"CertDate\" })\n certDate: Date;\n\n @Column({ name: \"ExpireDate\" })\n expireDate: Date;\n\n @Column({ name: \"SkillTester\" })\n skillTester: string;\n\n @Column({ name: \"HistSeq\" })\n histSeq: string;\n\n @Column({ name: \"Notes\" })\n notes: string;\n\n @Column({ name: \"UniqueAttchID\" })\n attachmentID: number;\n\n @Column({ name: \"Type\" })\n type: string;\n\n @Column({ name: \"KeyID\" })\n keyID: number;\n\n @Column({ name: \"udLastModDate\" })\n lastModifiedDate: Date;\n\n @Column({ name: \"udLicense\" })\n license: number;\n\n @ManyToOne(type => EmployeeEntity, (employee) => employee.employeeToSkills)\n @JoinColumn([{ name: \"HRCo\", referencedColumnName: \"companyNumber\" }, { name: \"HRRef\", referencedColumnName: \"employeeNumber\" }])\n employee: EmployeeEntity;\n\n @ManyToOne(type => SkillEntity, (skill) => skill.employeeToSkills)\n @JoinColumn([{ name: \"HRCo\", referencedColumnName: \"companyNumber\" }, { name: \"Code\", referencedColumnName: \"code\" }])\n skill: SkillEntity;\n}\n```\n\n========================================\n\nComments:\n- Thanks for the reply. We just got it figured out this morning. We ended up using JoinColumn to override the joining columns and set them up correctly. I have updated the example to show how we ended up solving the issue. See the JoinColumn() decorator for the Many to One relationships in the EmployeeToSkill class","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":6,"totalLines":317,"estimatedTokens":2168}}452{"id":"stack-50006365","source":"stackoverflow","questionId":50006365,"title":"typescript express typeorm createconnection","tags":["node.js","typescript","express","typeorm"],"text":"Title: typescript express typeorm createconnection\nTags: node.js, typescript, express, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am creating an app with typescript express node typeorm. I am having this issue where when I make a call through a service class to the database using typeorm, I get connection default was not found. Here are my code snippets:\n\n```\n//dataservice class\nimport { Connection, getConnection, EntityManager, Repository, \ngetManager } from \"typeorm\";\n\nexport class LeaveDataService {\nprivate _db: Repository;\n\nconstructor() {\n this._db = getManager().getRepository(Leave);\n}\n\n/**\n * applyForLeave\n */\npublic applyForLeave(leave: Leave): void {\n if(leave !== null) {\n let entity: Leave = this._db.create(leave);\n this._db.save(entity);\n }\n}\n\n/**\n * getAllLeaves\n */\npublic async getAllLeaves(): Promise> {\n let leaves: Promise> = this._db.find({\n select: [\"leaveDays\",\"casualLeaveDays\",\"id\",\"staff\",\"leaveType\",\"endorsedBy\",\"approvedBy\"],\n relations: [\"staff\", \"leaveType\"],\n skip: 5,\n take: 15\n });\n\n return leaves;\n}\n```\n\nthis is my ormconfig.json\n\n```\n{\n \"type\":\"sqlite\",\n \"entities\": [\"./models/*.js\"],\n \"database\": \"./leaveappdb.sql\"\n}\n```\n\nand this is the \"controller\" that responds to requests by calling the service class which is the first snippet:\n\n```\nimport { Request, Response } from \"express\";\nimport { LeaveDataService } from \"../services/leaveDataService\";\nimport { LeaveIndexApiModel } from '../ApiModels/leaveIndexApiModel';\n\nconst dataService: LeaveDataService = new LeaveDataService();\n\nexport let index = async (req: Request, res: Response) => {\nlet result = await dataService.getAllLeaves();\nlet viewresult = new Array();\n\nresult.forEach(leave => {\n let apmodel = \n new LeaveIndexApiModel(leave.leaveType.name, \n`${leave.staff.firstname} ${leave.staff.lastname}`, leave.id);\n viewresult.push(apmodel);\n});\n\nreturn res.status(200).send(viewresult);\n}\n```\n\nthen this is where I bootstrap my app.\n\n```\nimport express = require('express');\nimport bodyParser = require('body-parser');\nimport path = require('path');\nimport * as home from './controllers/home';\nimport { createConnection } from 'typeorm';\nimport * as leavectrl from \"./controllers/leaveController\";\n//create express server\n\n//create app db connection.\ncreateConnection().then(async connection => {\nconst app = express();\nconsole.log(\"DB online!\");\nconst approot = './';\nconst appport = process.env.Port || 8001;\n//setup express for json parsing even with urlencoding\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(express.static(path.join(approot,'dist')));\n\n//serve and respond to routes by api\napp.get('/home', home.home);\napp.get('/login',home.login);\n\n//routes for leave\napp.get('/api/leaves', leavectrl.index);\n//default fall through\n// app.get('*', (req: Request, res: Response)=>{\n// res.sendFile(approot,'dist/index.html');\n// });\n\napp.listen(appport, ()=> console.log(`api is alive on port \n${appport}`));\n\n}).catch(error => console.log(\"Data Access Error : \", error));\n```\n\n========================================\n\nCode:\n```text\n//dataservice class\nimport { Connection, getConnection, EntityManager, Repository, \ngetManager } from \"typeorm\";\n\nexport class LeaveDataService {\nprivate _db: Repository<Leave>;\n\nconstructor() {\n this._db = getManager().getRepository(Leave);\n}\n\n/**\n * applyForLeave\n */\npublic applyForLeave(leave: Leave): void {\n if(leave !== null) {\n let entity: Leave = this._db.create(leave);\n this._db.save(entity);\n }\n}\n\n/**\n * getAllLeaves\n */\npublic async getAllLeaves(): Promise<Array<Leave>> {\n let leaves: Promise<Array<Leave>> = this._db.find({\n select: [\"leaveDays\",\"casualLeaveDays\",\"id\",\"staff\",\"leaveType\",\"endorsedBy\",\"approvedBy\"],\n relations: [\"staff\", \"leaveType\"],\n skip: 5,\n take: 15\n });\n\n return leaves;\n}\n```\n\n```text\n{\n \"type\":\"sqlite\",\n \"entities\": [\"./models/*.js\"],\n \"database\": \"./leaveappdb.sql\"\n}\n```\n\n```text\nimport { Request, Response } from \"express\";\nimport { LeaveDataService } from \"../services/leaveDataService\";\nimport { LeaveIndexApiModel } from '../ApiModels/leaveIndexApiModel';\n\n\n\nconst dataService: LeaveDataService = new LeaveDataService();\n\nexport let index = async (req: Request, res: Response) => {\nlet result = await dataService.getAllLeaves();\nlet viewresult = new Array<LeaveIndexApiModel>();\n\nresult.forEach(leave => {\n let apmodel = \n new LeaveIndexApiModel(leave.leaveType.name, \n`${leave.staff.firstname} ${leave.staff.lastname}`, leave.id);\n viewresult.push(apmodel);\n});\n\n\nreturn res.status(200).send(viewresult);\n}\n```\n\n```text\nimport express = require('express');\nimport bodyParser = require('body-parser');\nimport path = require('path');\nimport * as home from './controllers/home';\nimport { createConnection } from 'typeorm';\nimport * as leavectrl from \"./controllers/leaveController\";\n//create express server\n\n\n//create app db connection.\ncreateConnection().then(async connection => {\nconst app = express();\nconsole.log(\"DB online!\");\nconst approot = './';\nconst appport = process.env.Port || 8001;\n//setup express for json parsing even with urlencoding\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(express.static(path.join(approot,'dist')));\n\n//serve and respond to routes by api\napp.get('/home', home.home);\napp.get('/login',home.login);\n\n//routes for leave\napp.get('/api/leaves', leavectrl.index);\n//default fall through\n// app.get('*', (req: Request, res: Response)=>{\n// res.sendFile(approot,'dist/index.html');\n// });\n\napp.listen(appport, ()=> console.log(`api is alive on port \n${appport}`));\n\n}).catch(error => console.log(\"Data Access Error : \", error));\n```\n\n```text\ncreateConnection(./ormconfig.json).then(async connection => {\n}).catch(error => console.log(\"Data Access Error : \", error));\n```\n\n```text\nimport \"reflect-metadata\";\nimport { ConnectionOptions } from \"typeorm\";\nimport { abc } from \"../DatabaseEntities/abc\";\nimport { def } from '../DatabaseEntities/def';\n\nexport let dbOptions: ConnectionOptions = {\n type: \"sqlite\",\n name: app,\n database: \"./leaveappdb.sqlite3\", \n entities: [abc, def],\n synchronize: true,\n}\n```\n\n```text\nimport { createConnection, createConnections } from 'typeorm';\nimport * as appConfig from './Config/config';\ncreateConnection(appConfig.dbOptions).then(async connection => {\n console.log(\"Connected to DB\");\n}).catch(error => console.log(\"TypeORM connection error: \", error));\n```\n\n========================================\n\nComments:\n- what line are you getting the error on? If you are only have one connection (vs. ones for development and staging ...) you can name your one connection in your ormconfig 'default'\n- Well, I don't know very much about express, but if I remember, you can use getConnection().manager.getReposiory method, that should read your connection config file and create what you need. My doubt is in your config file, database should be the database name?\n- @jonathan default is given by default if you only have one database configuration\n- @Jesus Gilberto database is not supposed to be a path! You r right. So u r right","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":263,"estimatedTokens":1803}}453{"id":"stack-79138045","source":"stackoverflow","questionId":79138045,"title":"TypeORM One-To-One Relationship Showing as Many-To-One/One-To-Many in PostgreSQL ERD","tags":["postgresql","nestjs","typeorm"],"text":"Title: TypeORM One-To-One Relationship Showing as Many-To-One/One-To-Many in PostgreSQL ERD\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using TypeORM with NestJS to establish a one-to-one relationship between two tables, but when I view the ERD in pgAdmin, it's showing up as a many-to-one/one-to-many relationship instead. I have included my code snippets and an image of the ERD for reference.\n\n```\n@Entity({ name: 'users' })\n@ObjectType()\nexport class User {\n @PrimaryGeneratedColumn()\n @Field((type) => Int)\n id: number\n\n @Column()\n @Field()\n username: string\n\n @Column({ nullable: true })\n @Field({ nullable: true })\n displayName?: string\n\n @OneToOne(() => UserSetting)\n @JoinColumn()\n @Field({ nullable: true })\n settings?: UserSetting\n}\n\n@Entity({ name: 'user_settings' })\n@ObjectType()\nexport class UserSetting {\n @PrimaryColumn()\n @Field((type) => Int)\n userId: number\n\n @Column({ default: false })\n @Field({ defaultValue: false })\n receiveNotifications: boolean\n\n @Column({ default: false })\n @Field({ defaultValue: false })\n receiveEmails: boolean\n}\n```\n\nhttps://i.sstatic.net/FcXbk5Vo.png\n\nIn pgAdmin, you can check relationship, this should appear as one-to-one. Has anyone else encountered this? Could there be something I'm missing in the configuration?\n\n========================================\n\nTop Answer:\n**Why PostgreSQL Shows it as Many-to-One/One-to-Many:**\n\nI Think it's because UserSetting didn't have userId set as a primary key, PostgreSQL treated it as a One-to-Many relationship, where multiple settings could be linked to a single user.\n\nBy making userId the primary key in UserSetting, you ensure that each user can only have one setting, thus enforcing the one-to-one relationship.\n\n**Here’s how you can modify your entities:**\n\n```\n@Entity({ name: 'users' })\n@ObjectType()\nexport class User {\n @PrimaryGeneratedColumn()\n @Field((type) => Int)\n id: number;\n\n @Column()\n @Field()\n username: string;\n\n @Column({ nullable: true })\n @Field({ nullable: true })\n displayName?: string;\n\n @OneToOne(() => UserSetting, (setting) => setting.user, { cascade: true })\n @JoinColumn({ name: 'userSettingId' })\n @Field({ nullable: true })\n settings?: UserSetting;\n}\n\n@Entity({ name: 'user_settings' })\n@ObjectType()\nexport class UserSetting {\n @PrimaryColumn()\n @Field((type) => Int)\n userId: number;\n\n @OneToOne(() => User, (user) => user.settings)\n @JoinColumn({ name: 'userId' })\n user: User;\n\n @Column({ default: false })\n @Field({ defaultValue: false })\n receiveNotifications: boolean;\n\n @Column({ default: false })\n @Field({ defaultValue: false })\n receiveEmails: boolean;\n}\n```\n\n========================================\n\nCode:\n```js\n@Entity({ name: 'users' })\n@ObjectType()\nexport class User {\n @PrimaryGeneratedColumn()\n @Field((type) => Int)\n id: number\n\n @Column()\n @Field()\n username: string\n\n @Column({ nullable: true })\n @Field({ nullable: true })\n displayName?: string\n\n @OneToOne(() => UserSetting)\n @JoinColumn()\n @Field({ nullable: true })\n settings?: UserSetting\n}\n\n@Entity({ name: 'user_settings' })\n@ObjectType()\nexport class UserSetting {\n @PrimaryColumn()\n @Field((type) => Int)\n userId: number\n\n @Column({ default: false })\n @Field({ defaultValue: false })\n receiveNotifications: boolean\n\n @Column({ default: false })\n @Field({ defaultValue: false })\n receiveEmails: boolean\n}\n```\n\n```text\n@Entity({ name: 'users' })\n@ObjectType()\nexport class User {\n @PrimaryGeneratedColumn()\n @Field((type) => Int)\n id: number;\n\n @Column()\n @Field()\n username: string;\n\n @Column({ nullable: true })\n @Field({ nullable: true })\n displayName?: string;\n\n @OneToOne(() => UserSetting, (setting) => setting.user, { cascade: true })\n @JoinColumn({ name: 'userSettingId' })\n @Field({ nullable: true })\n settings?: UserSetting;\n}\n\n@Entity({ name: 'user_settings' })\n@ObjectType()\nexport class UserSetting {\n @PrimaryColumn()\n @Field((type) => Int)\n userId: number;\n\n @OneToOne(() => User, (user) => user.settings)\n @JoinColumn({ name: 'userId' })\n user: User;\n\n @Column({ default: false })\n @Field({ defaultValue: false })\n receiveNotifications: boolean;\n\n @Column({ default: false })\n @Field({ defaultValue: false })\n receiveEmails: boolean;\n}\n```\n\n========================================\n\nComments:\n- After some research, this issue is not because of typeorm and its relationship. It is because of pgAdmin. You can check the answer that I have added.\n- Thank you for sharing this answer as this is useful for bidirectional relationships. I have added answer as it may help somebody in future.","metadata":{"transformedAt":"2026-08-18T18:33:44.717Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":194,"estimatedTokens":1171}}454{"id":"stack-73954724","source":"stackoverflow","questionId":73954724,"title":"Find records where its @OneToMany relation is not empty","tags":["nestjs","typeorm"],"text":"Title: Find records where its @OneToMany relation is not empty\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'd like to select all `Users` where its `photos` property is not empty. In other words, \"select users where photos is not empty\".\n\n```\nimport { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from \"typeorm\"\nimport { User } from \"./User\"\n\n@Entity()\nexport class Photo {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column()\n url: string\n\n @ManyToOne(() => User, (user) => user.photos)\n user: User\n}\n\nimport { Entity, PrimaryGeneratedColumn, Column, OneToMany } from \"typeorm\"\nimport { Photo } from \"./Photo\"\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column()\n name: string\n\n @OneToMany(() => Photo, (photo) => photo.user)\n photos: Photo[]\n}\n```\n\nIs this possible in `typeorm`, or is `SQL` the only way to go? Thank you.\n\n========================================\n\nTop Answer:\nYou can achieve this by using TypeORM QueryBuilder.\n\nThere are two joining options in their docs leftJoinAndSelect and innerJoinAndSelect\n\nThe difference between LEFT JOIN and INNER JOIN is that INNER JOIN\nwon't return a user if it does not have any photos. LEFT JOIN will\nreturn you the user even if it doesn't have photos.\n\nSo, if you want to return only those users who have atleast one photo you can use .innerJoinAndSelect().\n\n```\nconst queryBuilder = this.repository.createQueryBuilder(\"users\");\n\nqueryBuilder\n .where(...)\n .innerJoinAndSelect(\"users.photos\", \"photos\", [Optional where], [Optional where variables object])\n .orderBy(order)\n .skip(skip)\n .take(take);\n\n const { entities } = await queryBuilder.getRawAndEntities();\n```\n\n========================================\n\nCode:\n```text\nimport { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from \"typeorm\"\nimport { User } from \"./User\"\n\n@Entity()\nexport class Photo {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column()\n url: string\n\n @ManyToOne(() => User, (user) => user.photos)\n user: User\n}\n\n\nimport { Entity, PrimaryGeneratedColumn, Column, OneToMany } from \"typeorm\"\nimport { Photo } from \"./Photo\"\n\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column()\n name: string\n\n @OneToMany(() => Photo, (photo) => photo.user)\n photos: Photo[]\n}\n```\n\n```text\nUsers\n```\n\n```text\nphotos\n```\n\n```text\ntypeorm\n```\n\n```text\nSQL\n```\n\n```text\nconst users = await userRepository.createQueryBuilder('user')\n .leftJoinAndSelect('user.photos', 'photos')\n .where('photos.id IS NOT NULL')\n .getRawMany();\n```\n\n```text\nconst users = await userRepository.createQueryBuilder('user')\n .leftJoinAndSelect('user.photos', 'photos')\n .where('photos.id IS NOT NULL')\n .getMany();\n```\n\n```text\nQueryBuilder\n```\n\n```text\nleftJoinAndSelect\n```\n\n```text\ngetRawMany\n```\n\n```text\ngetMany\n```\n\n```text\nconst queryBuilder = this.repository.createQueryBuilder(\"users\");\n\nqueryBuilder\n .where(...)\n .innerJoinAndSelect(\"users.photos\", \"photos\", [Optional where], [Optional where variables object])\n .orderBy(order)\n .skip(skip)\n .take(take);\n\n const { entities } = await queryBuilder.getRawAndEntities();\n```\n\n========================================\n\nComments:\n- I checked the typeorm repo and it seems someone recently committed for a `whereExists` feature similar to `whereHas` we see in other ORMs. You could check this thread for more info github.com/typeorm/typeorm/issues/2815\n- Thanks Istiyak. I'll keep an eye on your suggestion and see if it solves the issue I have.\n- Thanks Rahul, but the output is not correct. Why: if a user has N photos, I would expect the output to be 1 User object with the photos property containing N photos. Instead, I receive an array of N elements (one for each photo), each one containing the user properties + photo properties merged.\n- Your question doesn't mention about the format of the output you expect. Anyways, just replace `getRawMany` with `getMany` and you would get the desired result. See edit.\n- Yup. That did it. Thanks Rahul.","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":12,"totalLines":170,"estimatedTokens":1009}}455{"id":"stack-48753097","source":"stackoverflow","questionId":48753097,"title":"unexpected token import nodejs, typescript","tags":["node.js","typescript","typeorm"],"text":"Title: unexpected token import nodejs, typescript\nTags: node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am using typescript, gruntjs, typeorm, typeorm-model-generator in my project for developing a Web API, when I try to start my app\nI receive an `unexpected token import` error, but that is because is reading where I got my typescript files when it has to read the dist directory which is where all my js files are, and this error only happens if I add the code required to establish the connection to my database.\n\n`app.ts`\n\n```\nexport class Server {\n\n public app: express.Application; \n\n public static bootstrap(): Server {\n return new Server();\n }\n\n constructor() {\n this.app = express();\n\n this.config();\n this.api();\n }\n\n private config(): void {\n this.app.use(express.static(path.join(__dirname, \"public\")));\n\n this.app.use(logger('dev'));\n this.app.use(bodyParser.json());\n this.app.use(bodyParser.urlencoded({\n extended: true\n }));\n\n this.app.use(function (error: any,\n request: express.Request, response: express.Response,\n next: express.NextFunction) {\n console.log(error);\n error.status = 404;\n response.json(error);\n });\n }\n\n private api(): void {\n // code that causes error\n // the output I recieve says\n // ./src/entity/myEntity.ts:1 unexpected token import\n // but if I remove it everything works fine\n typeorm.createConnection().then(async connection => {\n console.log(\"Conexion establecida\");\n }).catch(error => {\n console.log(error)\n });\n }\n\n}\n```\n\nThis is my `tsconfig.json`\n\n```\n{\n \"compilerOptions\": {\n \"lib\": [\n \"es5\",\n \"es6\"\n ],\n \"target\": \"es5\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"rootDir\": \"src\",\n \"outDir\": \"./dist/\",\n \"experimentalDecorators\": true,\n \"emitDecoratorMetadata\": true,\n \"sourceMap\": false,\n \"noImplicitAny\": false\n },\n \"include\": [\n \"src/**/*\"\n ],\n \"exclude\": [\n \"node_modules\",\n \"**/*.spec.ts\"\n ]\n}\n```\n\nWhat am I doing wrong? Should I kill myself already.\n\n========================================\n\nCode:\n```text\nexport class Server {\n\n public app: express.Application; \n\n public static bootstrap(): Server {\n return new Server();\n }\n\n constructor() {\n this.app = express();\n\n this.config();\n this.api();\n }\n\n private config(): void {\n this.app.use(express.static(path.join(__dirname, \"public\")));\n\n this.app.use(logger('dev'));\n this.app.use(bodyParser.json());\n this.app.use(bodyParser.urlencoded({\n extended: true\n }));\n\n this.app.use(function (error: any,\n request: express.Request, response: express.Response,\n next: express.NextFunction) {\n console.log(error);\n error.status = 404;\n response.json(error);\n });\n }\n\n private api(): void {\n // code that causes error\n // the output I recieve says\n // ./src/entity/myEntity.ts:1 unexpected token import\n // but if I remove it everything works fine\n typeorm.createConnection().then(async connection => {\n console.log(\"Conexion establecida\");\n }).catch(error => {\n console.log(error)\n });\n }\n\n}\n```\n\n```text\n{\n \"compilerOptions\": {\n \"lib\": [\n \"es5\",\n \"es6\"\n ],\n \"target\": \"es5\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"rootDir\": \"src\",\n \"outDir\": \"./dist/\",\n \"experimentalDecorators\": true,\n \"emitDecoratorMetadata\": true,\n \"sourceMap\": false,\n \"noImplicitAny\": false\n },\n \"include\": [\n \"src/**/*\"\n ],\n \"exclude\": [\n \"node_modules\",\n \"**/*.spec.ts\"\n ]\n}\n```\n\n```text\nunexpected token import\n```\n\n```text\napp.ts\n```\n\n```text\ntsconfig.json\n```\n\n```text\normconfig.json\n```\n\n```text\normconfig.json\n```\n\n========================================\n\nComments:\n- **Should I kill myself already.** - no don't\n- How are running the code? It is probably pointing at the wrong directory. FYI: `\"lib\": [\"es5\", \"es6\"]` doesn't make sense.\n- I run it with `npm run dev`, which points to `./bin/www.js` which is the file that starts the app, there I have a require statement for `dist/app.js`, so It should work fine. I am sorry my mistake it was `lib: [\"es6\"]`\n- When I do that, I don't receive any output.\n- Well, that is because you apps entry point does not produce any. Not sure what you expect but I would argue strongly that wrapping your logic in a class is entirely unhelpful.\n- Really? Why? Should I change it?\n- Well you can, but you need to do something more fundamental first and regardless. Figure out how you expect your code behave. Given what you have I would expect `node dist/app.js` to emit no output and so would say that it is behaving correctly\n- Well I'll check it in more detail, but given that www.js points to dist/app.js should the output would lead me to the location, I am only calling app.js\n- Well, I think I do use it, if you see the `bootstrap` method I return an instance of the class, then in `www.js` through that instance I gain access to the public `app` property which I use to start the app.\n- Well you did not say that before. So if you run `node bin/www.js` does it work?\n- Yeah, I am sorry for that, I am so worried for this thing not working. Nope I received the error of unexpected token import, it says that the error is in src/entity/aviso.ts but it should not be reading that file e.e\n- search for it, maybe you have a incorrect import somewhere.\n- Maybe I did a mistake with the ormconfig.json e.e, I will check it out, thank you :)\n- Yeah I figured it out later, thank you very much for your response anyway :).\n- Haha yea, I saw it was 3 months old, but figured I should just post my answer anyways.","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":207,"estimatedTokens":1416}}456{"id":"stack-72744071","source":"stackoverflow","questionId":72744071,"title":"Typescript Add types to libraries method arguments","tags":["javascript","node.js","typescript","typescript-typings","typeorm"],"text":"Title: Typescript Add types to libraries method arguments\nTags: javascript, node.js, typescript, typescript-typings, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am using an external library `pg-mem` which exposes `LibAdapters` and it has a method `createTypeormConnection` which accepts few arguments but of type `any`.\n\n```\nexport interface LibAdapters {\n createTypeormConnection(typeOrmConnection: any, queryLatency?: number): any;\n}\n```\n\nI want to specify the exact type of these arguments as I am getting a lot of lint errors:\n\n`Unsafe return of an `any` typed value.eslint@typescript-eslint/no-unsafe-return`\n\nHow can I specify the types of the arguments & return type of the method?\n\n========================================\n\nCode:\n```text\nexport interface LibAdapters {\n createTypeormConnection(typeOrmConnection: any, queryLatency?: number): any;\n}\n```\n\n```text\npg-mem\n```\n\n```text\nLibAdapters\n```\n\n```text\ncreateTypeormConnection\n```\n\n```text\nany\n```\n\n```text\nUnsafe return of an `any` typed value.eslint@typescript-eslint/no-unsafe-return\n```\n\n```js\ndeclare module \"pg-mem\" {\n interface LibAdapters {\n createTypeormConnection(typeOrmConnection: SomeType, queryLatency?: number): SomeOtherType\n }\n}\n```\n\n```text\ncreateTypeormConnection\n```\n\n```text\ncreateTypeormConnection\n```\n\n```text\nSomeType\n```\n\n```text\nany\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":71,"estimatedTokens":335}}457{"id":"stack-71062479","source":"stackoverflow","questionId":71062479,"title":"How to reference only one entity in a one-to-many relationship in TypeORM","tags":["typescript","one-to-many","typeorm","many-to-one"],"text":"Title: How to reference only one entity in a one-to-many relationship in TypeORM\nTags: typescript, one-to-many, typeorm, many-to-one\nSource: Stack Overflow\n\nQuestion:\nI'm wondering what's the best way to reference just one related entity instead of all of them in a one to many relationship.\n\nFor example, let's say I have a user, and it can have multiple photos.\nI want each photo to be related to the user, but from the user perspective I only care about one specific photo (the last uploaded one for example).\n\nOne approach is:\n\n```\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n currentPhotoId: number;\n\n async getCurrentPhoto(): Photo {\n ...\n }\n\n ... \n}\n\n@Entity()\nexport class Photo {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(() => User, user => user.photos)\n user: User;\n\n ...\n}\n```\n\nBut, is there a TypeORM-way for doing things like this? For example, it would be nice if it would be an eager solution and won't require another async operation to fetch the related entity.\n\nI'm probably not the first to come up with this requirement, but I haven't found anything, maybe I'm not searching properly.\n\n========================================\n\nCode:\n```text\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n currentPhotoId: number;\n\n async getCurrentPhoto(): Photo {\n ...\n }\n\n ... \n}\n\n@Entity()\nexport class Photo {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(() => User, user => user.photos)\n user: User;\n\n ...\n}\n```\n\n```text\ncurrentPhotoId\n```\n\n```text\noneToOne\n```\n\n```text\nPhoto\n```\n\n========================================\n\nComments:\n- Thanks. Yes, that's also the conclusion we came to, that we need to different relations between the entities, a `ManyToOne` and a different `OneToOne`","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":91,"estimatedTokens":459}}458{"id":"stack-71219103","source":"stackoverflow","questionId":71219103,"title":"TypeORM results to undefined on OneToOne relationship","tags":["javascript","node.js","nestjs","typeorm"],"text":"Title: TypeORM results to undefined on OneToOne relationship\nTags: javascript, node.js, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm new to NestJS (I had a bit of experience in Angular). I'm tasked to create a new microservice. I'm getting `undefined` when I console.log a JoinTable (the tables are new).\n\nSo `Unit` and `Hub` has `One to One` relationship.\n\nHere is the unit\n\n```\n@Entity({\n name: 'units',\n })\n export class UnitEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @OneToOne(() => HubEntity)\n @JoinColumn({name: \"hub_id\"})\n hub: HubEntity;\n```\n\nI also tried coding it like this:\n\n```\n@OneToOne(type => HubEntity, hub => hub.unit)\n @JoinColumn({name: \"hub_id\"})\n hub: HubEntity;\n```\n\nFor the HUB:\n\n```\n@Entity({\n name: 'hubs',\n })\n export class HubEntity {\n @PrimaryGeneratedColumn()\n id: number;\n \n @OneToOne(type => UnitEntity, unit => unit.hub)\n @JoinColumn({name: \"hub_id\"})\n unit: UnitEntity;\n```\n\nFor testing, this is how I consoled it.\n\n```\nasync findAllByUnit(unitId: number) {\n const unit = await this.unitRepository.findOne(unitId)\n\n console.log(unit.hub)\n }\n```\n\nIt returns `undefined`. What am I missing?\n\n========================================\n\nCode:\n```text\n@Entity({\n name: 'units',\n })\n export class UnitEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @OneToOne(() => HubEntity)\n @JoinColumn({name: \"hub_id\"})\n hub: HubEntity;\n```\n\n```text\n@OneToOne(type => HubEntity, hub => hub.unit)\n @JoinColumn({name: \"hub_id\"})\n hub: HubEntity;\n```\n\n```text\n@Entity({\n name: 'hubs',\n })\n export class HubEntity {\n @PrimaryGeneratedColumn()\n id: number;\n \n @OneToOne(type => UnitEntity, unit => unit.hub)\n @JoinColumn({name: \"hub_id\"})\n unit: UnitEntity;\n```\n\n```text\nasync findAllByUnit(unitId: number) {\n const unit = await this.unitRepository.findOne(unitId)\n\n console.log(unit.hub)\n }\n```\n\n```text\nundefined\n```\n\n```text\nUnit\n```\n\n```text\nHub\n```\n\n```text\nOne to One\n```\n\n```text\nundefined\n```\n\n```text\nawait this.unitRepository.findOne(unitId, {\n relations: ['hub']\n})\n```\n\n========================================\n\nComments:\n- hi! i stil get this error :( `UnhandledPromiseRejectionWarning: FindRelationsNotFoundError: Relation \"hubs\" was not found; please check if it is correct and really exists in your entity.`\n- Have you entered \"hub\" as singular in the relations array?\n- thank you! I finally got it. I missed this, and also removed the @JoinColumn in the hub entity. thank you!","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":134,"estimatedTokens":620}}459{"id":"stack-71818100","source":"stackoverflow","questionId":71818100,"title":"NestJS and TypeORM Exception Filter: Get Status is not a function","tags":["javascript","node.js","typescript","nestjs","typeorm"],"text":"Title: NestJS and TypeORM Exception Filter: Get Status is not a function\nTags: javascript, node.js, typescript, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm developing an app using NestJS and TypeORM. My goal is to catch TypeORM errors and it could be done using exception filters.\n\nBut my problem is, I'm encountering this error:\n\n`(node:345) UnhandledPromiseRejectionWarning: TypeError: exception.getStatus is not a function`\n\nThis is similar to this github post discussing the problem but it's not working on my end.\n\nHere's my setup:\n\n```\n@Catch(QueryFailedError)\nexport class TypeORMQueryExceptionFilter implements ExceptionFilter {\n catch(exception: HttpException, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse();\n const request = ctx.getRequest();\n const status = exception.getStatus(); //error here\n....\n```\n\nI've declared this globally so,\n\n**main.ts**\n\n`app.useGlobalFilters(new TypeORMQueryExceptionFilter())`\n\n**app.module.ts**\n\n```\n....\nproviders: [\n\n {\n provide: APP_FILTER,\n useClass: TypeORMQueryExceptionFilter\n }\n ]\n...\n```\n\nIf you have an idea resolving why `getStatus()` of HttpException is undefined, it would be a big help.\n\n**Update**\n\nAs this line suggests `catch(exception: HttpException, host: ArgumentsHost) {` in relation to `@Catch(QueryFailedError)`, I could assume that `HttpException` is the wrong type for param exception. It should be,if ever, `catch(exception: QueryFailedError, host: ArgumentsHost) {` instead.\n\nThus, since the `QueryFailedError` data structure is this:\n\n```\nexport declare class QueryFailedError extends TypeORMError {\n readonly query: string;\n readonly parameters: any[] | undefined;\n readonly driverError: any;\n constructor(query: string, parameters: any[] | undefined, driverError: any);\n}\n```\n\nI believe that `const status = exception.getStatus();` is not needed so we could re-write or eliminate `const status = exception.getStatus()` to `const status = exception.driverError()`. This is relation to the example here.\n\nSince `QueryFailedError` doesn't represent any http error codes in its properties, one solution could have to hard code the http status response like this:\n\n```\nresponse\n .status(500)\n .json({\n statusCode: 500,\n timestamp: new Date().toISOString(),\n path: request.url,\n });\n```\n\nCan someone validate this as it could be I just did something wrong as `exception: HttpException` should be working anyway?\n\n========================================\n\nCode:\n```text\n@Catch(QueryFailedError)\nexport class TypeORMQueryExceptionFilter implements ExceptionFilter {\n catch(exception: HttpException, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse<Response>();\n const request = ctx.getRequest<Request>();\n const status = exception.getStatus(); //error here\n....\n```\n\n```text\n....\nproviders: [\n\n {\n provide: APP_FILTER,\n useClass: TypeORMQueryExceptionFilter\n }\n ]\n...\n```\n\n```text\nexport declare class QueryFailedError extends TypeORMError {\n readonly query: string;\n readonly parameters: any[] | undefined;\n readonly driverError: any;\n constructor(query: string, parameters: any[] | undefined, driverError: any);\n}\n```\n\n```text\nresponse\n .status(500)\n .json({\n statusCode: 500,\n timestamp: new Date().toISOString(),\n path: request.url,\n });\n```\n\n```text\n(node:345) UnhandledPromiseRejectionWarning: TypeError: exception.getStatus is not a function\n```\n\n```text\napp.useGlobalFilters(new TypeORMQueryExceptionFilter())\n```\n\n```text\ngetStatus()\n```\n\n```text\ncatch(exception: HttpException, host: ArgumentsHost) {\n```\n\n```text\n@Catch(QueryFailedError)\n```\n\n```text\nHttpException\n```\n\n```text\ncatch(exception: QueryFailedError, host: ArgumentsHost) {\n```\n\n```text\nQueryFailedError\n```\n\n```text\nconst status = exception.getStatus();\n```\n\n```text\nconst status = exception.getStatus()\n```\n\n```text\nconst status = exception.driverError()\n```\n\n```text\nQueryFailedError\n```\n\n```text\nexception: HttpException\n```\n\n```js\n@Catch(QueryFailedError)\nexport class TypeORMQueryExceptionFilter implements ExceptionFilter {\n catch(exception: QueryFailedError, host: ArgumentsHost) {\n const ctx = host.switchToHttp();\n const response = ctx.getResponse<Response>();\n const request = ctx.getRequest<Request>();\n```\n\n```text\nQueryFailedError\n```\n\n```text\ngetStatus\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":192,"estimatedTokens":1123}}460{"id":"stack-71852377","source":"stackoverflow","questionId":71852377,"title":"TypeORM Polymorphic Relationship can not get data from parent","tags":["javascript","typescript","polymorphism","typeorm"],"text":"Title: TypeORM Polymorphic Relationship can not get data from parent\nTags: javascript, typescript, polymorphism, typeorm\nSource: Stack Overflow\n\nQuestion:\nSo I'm using https://github.com/bashleigh/typeorm-polymorphic as polymorphic relation in my model. There a few models\n\n```\n// Device Entity\n@Entity()\n@TableInheritance({ column: { type: 'varchar', name: 'type' } })\nexport class Device extends BaseModel { // Base model is just primary generated id and timestamp\n// Device stuff\n}\n```\n\n```\n// lock entity\n@ChildEntity()\nexport class Lock extends Device {\n// Lock stuff\n\n@PolymorphicChildren(()=>ConnectionData, {\n eager: false\n })\nproviders: ConnectionData[]\n}\n```\n\n```\n// connection data entity\n@Entity()\n@TableInheritance({ column: { type: 'varchar', name: 'type' } })\nexport class ConnectionData extends BaseModel {\n// connection data basic stuff\n}\n```\n\n```\n// first user type entity\n@ChildEntity()\nexport class FirstUserType extends ConnectionData implements PolymorphicChildInterface {\n // other first user type stuff\n\n @PolymorphicParent(()=>[Lock,Key]) // Key is also a parent like lock\n connectable: Lock | Key\n\n @Column({name: 'connectableId'})\n entityId: string;\n\n @Column({name: 'connectableType'})\n entityType: string;\n}\n```\n\nusing these script\n\n```\nlet repo = connection.getCustomRepository(FirstUserTypeRepository) // extends AbstractPolymorphicRepository\n\nlet result = repo.findOne(1) // find with some id\n```\n\nI'm able to get these data\n\n```\n{\n id: // first user type id\n prop: // first user type other properties\n connectable : {\n // Lock object\n }\n}\n```\n\nBut I want the other way. I want the output to be\n\n```\n{\n id: //some lock id\n data: // some lock data\n providers: [\n // I want here to be list of ConnectionData\n ]\n}\n```\n\nI tried to create these script that I thought will be able to do such thing\n\n```\nlet repo = connection.getCustomRepository(LockRepository) // extends AbstractPolymorphicRepository\n\nlet result = repo.findOne(1) // find with lock id\n```\n\nbut got these error\n\n```\nTypeORMError: Function parameter isn't supported in the parameters. Please check \"orm_param_1\" parameter.\n```\n\nI'm not sure how would I get the data. I've been spending a few days to do so but still no luck for me until now.\n\n========================================\n\nTop Answer:\nThis happens due to a bug in the package. I've created a pull request with a fix.\n\n========================================\n\nCode:\n```js\n// Device Entity\n@Entity()\n@TableInheritance({ column: { type: 'varchar', name: 'type' } })\nexport class Device extends BaseModel { // Base model is just primary generated id and timestamp\n// Device stuff\n}\n```\n\n```js\n// lock entity\n@ChildEntity()\nexport class Lock extends Device {\n// Lock stuff\n\n@PolymorphicChildren(()=>ConnectionData, {\n eager: false\n })\nproviders: ConnectionData[]\n}\n```\n\n```js\n// connection data entity\n@Entity()\n@TableInheritance({ column: { type: 'varchar', name: 'type' } })\nexport class ConnectionData extends BaseModel {\n// connection data basic stuff\n}\n```\n\n```js\n// first user type entity\n@ChildEntity()\nexport class FirstUserType extends ConnectionData implements PolymorphicChildInterface {\n // other first user type stuff\n\n @PolymorphicParent(()=>[Lock,Key]) // Key is also a parent like lock\n connectable: Lock | Key\n\n @Column({name: 'connectableId'})\n entityId: string;\n\n @Column({name: 'connectableType'})\n entityType: string;\n}\n```\n\n```js\nlet repo = connection.getCustomRepository(FirstUserTypeRepository) // extends AbstractPolymorphicRepository\n\nlet result = repo.findOne(1) // find with some id\n```\n\n```json\n{\n id: // first user type id\n prop: // first user type other properties\n connectable : {\n // Lock object\n }\n}\n```\n\n```json\n{\n id: //some lock id\n data: // some lock data\n providers: [\n // I want here to be list of ConnectionData\n ]\n}\n```\n\n```js\nlet repo = connection.getCustomRepository(LockRepository) // extends AbstractPolymorphicRepository\n\nlet result = repo.findOne(1) // find with lock id\n```\n\n```text\nTypeORMError: Function parameter isn't supported in the parameters. Please check \"orm_param_1\" parameter.\n```\n\n```js\nconst locks = connection.getRepository(Lock)\n const result = await locks\n .createQueryBuilder(\"lock\")\n .innerJoinAndMapMany(\"lock.providers\",ConnectionData,\"pc\", `pc.\"connectableId\"::text = lock.id::text`)\n .where({\n id:'a725b986-71d7-4f65-bbbf-26f537c13026'\n })\n .getOne()\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":10,"totalLines":205,"estimatedTokens":1127}}461{"id":"stack-51663956","source":"stackoverflow","questionId":51663956,"title":"Get connection after bootstraping in express js","tags":["node.js","typescript","typeorm"],"text":"Title: Get connection after bootstraping in express js\nTags: node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI use TypeORM with expressjs but I am unable to the connection after bootstrapping it.\n\nIn my `app.js`, I have \n\n```\nimport 'reflect-metadata';\nimport { createConnection, ConnectionOptions } from 'typeorm';\n// Other imports\n\nconst app: Application = express();\n\n// Setup express-async-errors\nasyncHandler;\n\ncreateConnection({\n \"type\": \"sqlite\",\n \"database\": \"database.sqlite\",\n \"synchronize\": true,\n \"logging\": true,\n \"entities\": [\n path.join(__dirname, \"app/entity/**/*.js\")\n ],\n}).then(async connection => {\n\n // Set Environment & middleware\n middleware(app);\n\n // setup routes\n routes(app);\n\n app.listen(3000);\n}).catch(error => console.log(error));\n\n export default app;\n```\n\nThen, I have a `UsersController.ts` which is linked to a the user routes\n\n```\nimport { Request, Response } from 'express';\nimport { User } from '../entity/User';\nimport { getConnection } from \"typeorm\";\n\nclass UsersController {\n private userRepository;\n\n constructor() {\n this.userRepository = getConnection().getRepository(User);\n }\n\n async index(req: Request, res: Response) {\n const users = await this.userRepository.find();\n\n res.json({\n users\n });\n }\n}\n\nexport default UsersController;\n```\n\nHowever, if I try to run the above code, I always get \n\n `ConnectionNotFoundError: Connection \"default\" was not found.`.\n\n \n [ 'ConnectionNotFoundError: Connection \"default\" was not found.',\n ' at new ConnectionNotFoundError (C:[user]\\node_modules\\typeorm\\error\\ConnectionNotFoundError.js:19:28)',\n ' at ConnectionManager.get (C:[user]\\node_modules\\typeorm\\connection\\ConnectionManager.js:38:19)',\n ' at Object.getConnection (C:[user]\\node_modules\\typeorm\\index.js:268:35)',\n ' at new UsersController (C:[user]\\build\\app\\controllers\\users.controller.js:7:41)',\n ' at Object. (C:[user]\\build\\app\\routes\\users.route.js:12:19)',\n ' at Module._compile (internal/modules/cjs/loader.js:689:30)',\n ' at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)',\n ' at Module.load (internal/modules/cjs/loader.js:599:32)',\n ' at tryModuleLoad (internal/modules/cjs/loader.js:538:12)',\n ' at Function.Module._load (internal/modules/cjs/loader.js:530:3)' ] }\n\nI have checked the typeORM online documentation and what I have above is the recommended way to setup TypeORM so, I am confused.\n\nAny pointer, in the right direction will be appreciated.\n\n========================================\n\nCode:\n```text\nimport 'reflect-metadata';\nimport { createConnection, ConnectionOptions } from 'typeorm';\n// Other imports\n\nconst app: Application = express();\n\n// Setup express-async-errors\nasyncHandler;\n\ncreateConnection({\n \"type\": \"sqlite\",\n \"database\": \"database.sqlite\",\n \"synchronize\": true,\n \"logging\": true,\n \"entities\": [\n path.join(__dirname, \"app/entity/**/*.js\")\n ],\n}).then(async connection => {\n\n // Set Environment & middleware\n middleware(app);\n\n // setup routes\n routes(app);\n\n app.listen(3000);\n}).catch(error => console.log(error));\n\n export default app;\n```\n\n```text\nimport { Request, Response } from 'express';\nimport { User } from '../entity/User';\nimport { getConnection } from \"typeorm\";\n\nclass UsersController {\n private userRepository;\n\n constructor() {\n this.userRepository = getConnection().getRepository(User);\n }\n\n async index(req: Request, res: Response) {\n const users = await this.userRepository.find();\n\n res.json({\n users\n });\n }\n}\n\nexport default UsersController;\n```\n\n```text\napp.js\n```\n\n```text\nUsersController.ts\n```\n\n```text\nConnectionNotFoundError: Connection \"default\" was not found.\n```\n\n========================================\n\nComments:\n- FYI. I spent much time to get things working w/o this approach but its seems to be impossible so I guess this is the only answer to this question.","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":163,"estimatedTokens":965}}462{"id":"stack-67508861","source":"stackoverflow","questionId":67508861,"title":"Duplicate migrations when using \"enumName\" ColumnOption for a Postgres enum type","tags":["postgresql","enums","nestjs","typeorm"],"text":"Title: Duplicate migrations when using \"enumName\" ColumnOption for a Postgres enum type\nTags: postgresql, enums, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have an entity called `TaskNotification` where I have an enum field called `type`. I use `enumName` option to give a specific name `TaskNotificationType` to it inside the database.\n\n```\nimport { Entity, Column } from 'typeorm';\n\nexport enum TaskNotificationType {\n ASSIGNED\n}\n\n@Entity('taskNotifications')\nexport class TaskNotification {\n @Column({\n type: 'enum',\n enum: TaskNotificationType,\n enumName: 'TaskNotificationType',\n default: TaskNotificationType.ASSIGNED,\n })\n type: TaskNotificationType;\n\n /* Some more code */\n}\n```\n\nWhen I create the new migration for this entity class, I get the following migration. This is correct and what is expected.\n\n```\nimport {MigrationInterface, QueryRunner} from \"typeorm\";\n\nexport class addNotifications1620795716886 implements MigrationInterface {\n name = 'addNotifications1620795716886'\n\n public async up(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`CREATE TYPE \"TaskNotificationType\" AS ENUM('0')`);\n await queryRunner.query(`CREATE TABLE \"taskNotifications\" (\"id\" character varying(21) NOT NULL, \"senderID\" character varying(21) NOT NULL, \"taskID\" character varying(21) NOT NULL, \"type\" \"TaskNotificationType\" NOT NULL DEFAULT '0', CONSTRAINT \"PK_bf03149248aee7c64532028321e\" PRIMARY KEY (\"id\"))`);\n await queryRunner.query(`CREATE TABLE \"notificationStatuses\" (\"id\" character varying(21) NOT NULL, \"receiverID\" character varying(21) NOT NULL, \"createdAt\" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), \"sentAt\" TIMESTAMP WITH TIME ZONE, \"readAt\" TIMESTAMP WITH TIME ZONE, \"taskNotificationID\" character varying(21) NOT NULL, CONSTRAINT \"PK_735fedb2f492dc91b0adf8233b0\" PRIMARY KEY (\"id\"))`);\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" ADD CONSTRAINT \"FK_9b92958e250c1f46393e0e88066\" FOREIGN KEY (\"taskID\") REFERENCES \"tasks\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`);\n await queryRunner.query(`ALTER TABLE \"notificationStatuses\" ADD CONSTRAINT \"FK_14dbeaea4a320e7375cb22e7e7a\" FOREIGN KEY (\"taskNotificationID\") REFERENCES \"taskNotifications\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`);\n }\n\n public async down(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`ALTER TABLE \"notificationStatuses\" DROP CONSTRAINT \"FK_14dbeaea4a320e7375cb22e7e7a\"`);\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" DROP CONSTRAINT \"FK_9b92958e250c1f46393e0e88066\"`);\n await queryRunner.query(`DROP TABLE \"notificationStatuses\"`);\n await queryRunner.query(`DROP TABLE \"taskNotifications\"`);\n await queryRunner.query(`DROP TYPE \"TaskNotificationType\"`);\n }\n\n}\n```\n\nWhen I rebuild the app and run the migrations, the database gets updated as I wanted. So there is no issue upto now. 🍾\n\nBut, if I try to create another migration without changing any of the entities, I am getting another migration like below. Notice the name difference in the enum between `up` and `down` methods. (What is happening here? 🤒)\n\n```\nimport {MigrationInterface, QueryRunner} from \"typeorm\";\n\nexport class addNotificationsDuplicate1620795984398 implements MigrationInterface {\n name = 'addNotificationsDuplicate1620795984398'\n\n public async up(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" DROP COLUMN \"type\"`);\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" ADD \"type\" \"TaskNotificationType\" NOT NULL DEFAULT '0'`);\n }\n\n public async down(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" DROP COLUMN \"type\"`);\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" ADD \"type\" \"tasknotificationtype\" NOT NULL DEFAULT '0'`);\n }\n\n}\n```\n\nIf I didn't use `enumName` in column options, typeorm would assign a default name `taskNotifications_type_enum`.\n\nHere's the migration for that:\n\n```\nimport {MigrationInterface, QueryRunner} from \"typeorm\";\n \nexport class addNotifications1620796454176 implements MigrationInterface {\n name = 'addNotifications1620796454176'\n \n public async up(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`CREATE TYPE \"taskNotifications_type_enum\" AS ENUM('0')`);\n await queryRunner.query(`CREATE TABLE \"taskNotifications\" (\"id\" character varying(21) NOT NULL, \"senderID\" character varying(21) NOT NULL, \"taskID\" character varying(21) NOT NULL, \"type\" \"taskNotifications_type_enum\" NOT NULL DEFAULT '0', CONSTRAINT \"PK_bf03149248aee7c64532028321e\" PRIMARY KEY (\"id\"))`);\n await queryRunner.query(`CREATE TABLE \"notificationStatuses\" (\"id\" character varying(21) NOT NULL, \"receiverID\" character varying(21) NOT NULL, \"createdAt\" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), \"sentAt\" TIMESTAMP WITH TIME ZONE, \"readAt\" TIMESTAMP WITH TIME ZONE, \"taskNotificationID\" character varying(21) NOT NULL, CONSTRAINT \"PK_735fedb2f492dc91b0adf8233b0\" PRIMARY KEY (\"id\"))`);\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" ADD CONSTRAINT \"FK_9b92958e250c1f46393e0e88066\" FOREIGN KEY (\"taskID\") REFERENCES \"tasks\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`);\n await queryRunner.query(`ALTER TABLE \"notificationStatuses\" ADD CONSTRAINT \"FK_14dbeaea4a320e7375cb22e7e7a\" FOREIGN KEY (\"taskNotificationID\") REFERENCES \"taskNotifications\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`);\n }\n \n public async down(queryRunner: QueryRunner): Promise {\n await queryRunner.query(`ALTER TABLE \"notificationStatuses\" DROP CONSTRAINT \"FK_14dbeaea4a320e7375cb22e7e7a\"`);\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" DROP CONSTRAINT \"FK_9b92958e250c1f46393e0e88066\"`);\n await queryRunner.query(`DROP TABLE \"notificationStatuses\"`);\n await queryRunner.query(`DROP TABLE \"taskNotifications\"`);\n await queryRunner.query(`DROP TYPE \"taskNotifications_type_enum\"`);\n }\n \n}\n```\n\nThen if I try to generate a migration without changing entities, it would not generate new migrations. (This is correct and expected behavior)\n\nHowever, if I add `enumName` after that, it would not generate a new migration for the name change. It will throw the usual error we see when we try to run migrations without changing any entity. (Busted again 😩)\n\n```\n╰>>> npm run typeorm:novadelite migration:generate -- -n addNotificationsDuplicate\n\n> novade-lite-backend@0.1.4 typeorm:novadelite /Users/eranga/Documents/Projects/Novade/NovadeLiteBackend\n> ts-node ./node_modules/.bin/typeorm --config src/modules/Database/OrmConfigs/novadeLiteOrmConfig \"migration:generate\" \"-n\" \"addNotificationsDuplicate\"\n\nNo changes in database schema were found - cannot generate a migration. To create a new empty migration use \"typeorm migration:create\" command\n```\n\nWhat is wrong here and how can I give a specific name to my enum type using typeorm?\n\nAny help is much appreciated! 🙏\n\n(In the rare occasion of this being an issue in typeorm, I have already created an issue in Github)\n\n========================================\n\nCode:\n```js\nimport { Entity, Column } from 'typeorm';\n\nexport enum TaskNotificationType {\n ASSIGNED\n}\n\n@Entity('taskNotifications')\nexport class TaskNotification {\n @Column({\n type: 'enum',\n enum: TaskNotificationType,\n enumName: 'TaskNotificationType',\n default: TaskNotificationType.ASSIGNED,\n })\n type: TaskNotificationType;\n\n /* Some more code */\n}\n```\n\n```js\nimport {MigrationInterface, QueryRunner} from \"typeorm\";\n\nexport class addNotifications1620795716886 implements MigrationInterface {\n name = 'addNotifications1620795716886'\n\n public async up(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(`CREATE TYPE \"TaskNotificationType\" AS ENUM('0')`);\n await queryRunner.query(`CREATE TABLE \"taskNotifications\" (\"id\" character varying(21) NOT NULL, \"senderID\" character varying(21) NOT NULL, \"taskID\" character varying(21) NOT NULL, \"type\" \"TaskNotificationType\" NOT NULL DEFAULT '0', CONSTRAINT \"PK_bf03149248aee7c64532028321e\" PRIMARY KEY (\"id\"))`);\n await queryRunner.query(`CREATE TABLE \"notificationStatuses\" (\"id\" character varying(21) NOT NULL, \"receiverID\" character varying(21) NOT NULL, \"createdAt\" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), \"sentAt\" TIMESTAMP WITH TIME ZONE, \"readAt\" TIMESTAMP WITH TIME ZONE, \"taskNotificationID\" character varying(21) NOT NULL, CONSTRAINT \"PK_735fedb2f492dc91b0adf8233b0\" PRIMARY KEY (\"id\"))`);\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" ADD CONSTRAINT \"FK_9b92958e250c1f46393e0e88066\" FOREIGN KEY (\"taskID\") REFERENCES \"tasks\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`);\n await queryRunner.query(`ALTER TABLE \"notificationStatuses\" ADD CONSTRAINT \"FK_14dbeaea4a320e7375cb22e7e7a\" FOREIGN KEY (\"taskNotificationID\") REFERENCES \"taskNotifications\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`);\n }\n\n public async down(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(`ALTER TABLE \"notificationStatuses\" DROP CONSTRAINT \"FK_14dbeaea4a320e7375cb22e7e7a\"`);\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" DROP CONSTRAINT \"FK_9b92958e250c1f46393e0e88066\"`);\n await queryRunner.query(`DROP TABLE \"notificationStatuses\"`);\n await queryRunner.query(`DROP TABLE \"taskNotifications\"`);\n await queryRunner.query(`DROP TYPE \"TaskNotificationType\"`);\n }\n\n}\n```\n\n```js\nimport {MigrationInterface, QueryRunner} from \"typeorm\";\n\nexport class addNotificationsDuplicate1620795984398 implements MigrationInterface {\n name = 'addNotificationsDuplicate1620795984398'\n\n public async up(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" DROP COLUMN \"type\"`);\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" ADD \"type\" \"TaskNotificationType\" NOT NULL DEFAULT '0'`);\n }\n\n public async down(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" DROP COLUMN \"type\"`);\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" ADD \"type\" \"tasknotificationtype\" NOT NULL DEFAULT '0'`);\n }\n\n}\n```\n\n```js\nimport {MigrationInterface, QueryRunner} from \"typeorm\";\n \nexport class addNotifications1620796454176 implements MigrationInterface {\n name = 'addNotifications1620796454176'\n \n public async up(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(`CREATE TYPE \"taskNotifications_type_enum\" AS ENUM('0')`);\n await queryRunner.query(`CREATE TABLE \"taskNotifications\" (\"id\" character varying(21) NOT NULL, \"senderID\" character varying(21) NOT NULL, \"taskID\" character varying(21) NOT NULL, \"type\" \"taskNotifications_type_enum\" NOT NULL DEFAULT '0', CONSTRAINT \"PK_bf03149248aee7c64532028321e\" PRIMARY KEY (\"id\"))`);\n await queryRunner.query(`CREATE TABLE \"notificationStatuses\" (\"id\" character varying(21) NOT NULL, \"receiverID\" character varying(21) NOT NULL, \"createdAt\" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), \"sentAt\" TIMESTAMP WITH TIME ZONE, \"readAt\" TIMESTAMP WITH TIME ZONE, \"taskNotificationID\" character varying(21) NOT NULL, CONSTRAINT \"PK_735fedb2f492dc91b0adf8233b0\" PRIMARY KEY (\"id\"))`);\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" ADD CONSTRAINT \"FK_9b92958e250c1f46393e0e88066\" FOREIGN KEY (\"taskID\") REFERENCES \"tasks\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`);\n await queryRunner.query(`ALTER TABLE \"notificationStatuses\" ADD CONSTRAINT \"FK_14dbeaea4a320e7375cb22e7e7a\" FOREIGN KEY (\"taskNotificationID\") REFERENCES \"taskNotifications\"(\"id\") ON DELETE NO ACTION ON UPDATE NO ACTION`);\n }\n \n public async down(queryRunner: QueryRunner): Promise<void> {\n await queryRunner.query(`ALTER TABLE \"notificationStatuses\" DROP CONSTRAINT \"FK_14dbeaea4a320e7375cb22e7e7a\"`);\n await queryRunner.query(`ALTER TABLE \"taskNotifications\" DROP CONSTRAINT \"FK_9b92958e250c1f46393e0e88066\"`);\n await queryRunner.query(`DROP TABLE \"notificationStatuses\"`);\n await queryRunner.query(`DROP TABLE \"taskNotifications\"`);\n await queryRunner.query(`DROP TYPE \"taskNotifications_type_enum\"`);\n }\n \n}\n```\n\n```sh\n╰>>> npm run typeorm:novadelite migration:generate -- -n addNotificationsDuplicate\n\n> novade-lite-backend@0.1.4 typeorm:novadelite /Users/eranga/Documents/Projects/Novade/NovadeLiteBackend\n> ts-node ./node_modules/.bin/typeorm --config src/modules/Database/OrmConfigs/novadeLiteOrmConfig \"migration:generate\" \"-n\" \"addNotificationsDuplicate\"\n\nNo changes in database schema were found - cannot generate a migration. To create a new empty migration use \"typeorm migration:create\" command\n```\n\n```text\nTaskNotification\n```\n\n```text\ntype\n```\n\n```text\nenumName\n```\n\n```text\nTaskNotificationType\n```\n\n```text\nup\n```\n\n```text\ndown\n```\n\n```text\nenumName\n```\n\n```text\ntaskNotifications_type_enum\n```\n\n```text\nenumName\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":14,"totalLines":263,"estimatedTokens":3224}}463{"id":"stack-69245030","source":"stackoverflow","questionId":69245030,"title":"TypeORM migration:generate working great except for DROP","tags":["postgresql","database-migration","typeorm","nest","drop"],"text":"Title: TypeORM migration:generate working great except for DROP\nTags: postgresql, database-migration, typeorm, nest, drop\nSource: Stack Overflow\n\nQuestion:\nI have a NestJS / TypeORM Project with PostGRE SQL.\n\nI want to delete some tables, so I have deleted the concerned folders. I also removed the dist folder to build the project again but even with that, typeORM does not detect that it have to DROP these tables on migration:generate.\n\nAll others cases of migrations are working well..\n\nIs there any way to force TypeORM to detect Entity deletion ? I can't find solution for this.. I could do it manually, but I can't believe that typeORM can't do this simple process.\n\n========================================\n\nCode:\n```text\ndown\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":1,"totalLines":19,"estimatedTokens":185}}464{"id":"stack-69177760","source":"stackoverflow","questionId":69177760,"title":"NestJS - Inject service into Pipe to fetch from DB","tags":["nestjs","typeorm"],"text":"Title: NestJS - Inject service into Pipe to fetch from DB\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am trying to inject a service into a PipeTransform class to fetch an entry from DB.\n\nI have tried the solution in this answer but I am getting a different error\nInject service into pipe in NestJs\n\n*`sample.pipe.ts`*\n\n```\n@Injectable()\nexport class SamplePipe implements PipeTransform {\n constructor(private readonly sampleService: SampleService) {}\n\n async transform(value: any, metadata: ArgumentMetadata) {\n const id = parseInt(value, 10);\n let sample: SampleEntiy = await this.sampleService.findOne(id);\n if (!sample) throw new NotFoundException('Sample Not Found');\n return sample;\n }\n}\n```\n\n*`sample.controller.ts`*\n\n```\n@Controller('sample')\nexport class SampleController {\n constructor(private readonly sampleService: SampleService) {}\n\n @Get(':id')\n async findOne(@Param('id', SamplePipe) id: SampleEntiy): Promise {\n return sample;\n }\n\n}\n```\n\nI get the following error at `return sample` in the controller\n\n```\nType '(notifier: Observable) => MonoTypeOperatorFunction' is missing the following properties from type 'SampleEntiy': id, value, isActivets(2739)\n```\n\nOn forcing it to return using `any` I get the following response in my browser\n\n```\nfunction sample(notifier) {\nreturn lift_1.operate(function (source, subscriber) {\nvar hasValue = false;\nvar lastValue = null;\nsource.subscribe(new OperatorSubscriber_1.OperatorSubscriber(subscriber, function (value) {\nhasValue = true;\nlastValue = value;\n}));\nvar emit = function () {\nif (hasValue) {\nhasValue = false;\nvar value = lastValue;\nlastValue = null;\nsubscriber.next(value);\n}\n};\nnotifier.subscribe(new OperatorSubscriber_1.OperatorSubscriber(subscriber, emit, noop_1.noop));\n});\n}\n```\n\nI understand that it is to do with async. The docs say async is supported\n\nFirst, note that the transform() method is marked as async. This is possible because Nest supports both synchronous and asynchronous pipes. We make this method async because some of the class-validator validations can be async (utilize Promises).\n\nAnd I am trying something mentioned in the docs:\n\nAnother useful transformation case would be to select an existing user entity from the database using an id supplied in the request:\n\n```\n@Get(':id') \nfindOne(@Param('id', UserByIdPipe) userEntity:UserEntity) {\n return userEntity; \n}\n```\n\n========================================\n\nCode:\n```js\n@Injectable()\nexport class SamplePipe implements PipeTransform<any> {\n constructor(private readonly sampleService: SampleService) {}\n\n async transform(value: any, metadata: ArgumentMetadata) {\n const id = parseInt(value, 10);\n let sample: SampleEntiy = await this.sampleService.findOne(id);\n if (!sample) throw new NotFoundException('Sample Not Found');\n return sample;\n }\n}\n```\n\n```js\n@Controller('sample')\nexport class SampleController {\n constructor(private readonly sampleService: SampleService) {}\n\n @Get(':id')\n async findOne(@Param('id', SamplePipe) id: SampleEntiy): Promise<SampleEntiy> {\n return sample;\n }\n\n}\n```\n\n```text\nType '<T>(notifier: Observable<any>) => MonoTypeOperatorFunction<T>' is missing the following properties from type 'SampleEntiy': id, value, isActivets(2739)\n```\n\n```js\nfunction sample(notifier) {\nreturn lift_1.operate(function (source, subscriber) {\nvar hasValue = false;\nvar lastValue = null;\nsource.subscribe(new OperatorSubscriber_1.OperatorSubscriber(subscriber, function (value) {\nhasValue = true;\nlastValue = value;\n}));\nvar emit = function () {\nif (hasValue) {\nhasValue = false;\nvar value = lastValue;\nlastValue = null;\nsubscriber.next(value);\n}\n};\nnotifier.subscribe(new OperatorSubscriber_1.OperatorSubscriber(subscriber, emit, noop_1.noop));\n});\n}\n```\n\n```text\n@Get(':id') \nfindOne(@Param('id', UserByIdPipe) userEntity:UserEntity) {\n return userEntity; \n}\n```\n\n```text\nsample.pipe.ts\n```\n\n```text\nsample.controller.ts\n```\n\n```text\nreturn sample\n```\n\n```text\nany\n```\n\n```text\n@Get(':id')\nasync findOne(@Param('id', SamplePipe) id: SampleEntiy): Promise<SampleEntiy> {\n return sample;\n}\n```\n\n```text\n@Get(':id')\nasync findOne(@Param('id', SamplePipe) sample: SampleEntiy): Promise<SampleEntiy> {\n return sample;\n}\n```\n\n```text\nsample\n```\n\n```text\nrxjs\n```\n\n```text\nid\n```\n\n```text\nsample\n```\n\n========================================\n\nComments:\n- I really need to find myself a buddy to review my code. Thank you so much! wasted hours on this. VSCode auto-imported `sample` from `rxjs` I realized that now. Using TS I was confident that I would get an error if it was not defined.","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":15,"totalLines":199,"estimatedTokens":1146}}465{"id":"stack-67334396","source":"stackoverflow","questionId":67334396,"title":"Typeorm listeners with parameters","tags":["javascript","node.js","typescript","typeorm"],"text":"Title: Typeorm listeners with parameters\nTags: javascript, node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nIs it possible to use TypeORM listeners with parameters?\n\nExample:\n\n```\n@BeforeInsert()\npublic async doSomething(myImportantParam) {\n // using myImportantParam here\n}\n```\n\n========================================\n\nCode:\n```text\n@BeforeInsert()\npublic async doSomething(myImportantParam) {\n // using myImportantParam here\n}\n```\n\n```js\n@Entity()\nexport class Post {\n constructor(myImportantParam: string) {\n this.myImportantParam = myImportantParam;\n }\n\n myImportantParam: string;\n\n @BeforeInsert()\n updateDates() {\n // Now you can use `this.myImportantParam` to access your value\n foo(this.myImportantParam);\n }\n \n /*... more code here ...*/\n}\n```\n\n```js\nexport class PostService {\n async addNewPost() {\n const myImportantParam = 'This is what I need!';\n const post = new Post(myImportantParam);\n\n // Add any other properties the post might have\n /*... more code here ...*/\n\n // Insert the updated post\n await getRepository(Post).insert(post);\n }\n\n /*... more code here ...*/\n}\n```\n\n```text\nmyImportantParam\n```\n\n```text\nthis.myImportantParam\n```\n\n```text\nmyImportantParam\n```\n\n========================================\n\nComments:\n- It is not a global variable. It is an instance variable which only belongs to the entity object you created. That is why we have to use `this` to access it.\n- This works just as I wanted, thank you very much!","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":79,"estimatedTokens":390}}466{"id":"stack-63296783","source":"stackoverflow","questionId":63296783,"title":"jest mock does not see that it has been called inside if statement in function","tags":["typescript","jestjs","typeorm"],"text":"Title: jest mock does not see that it has been called inside if statement in function\nTags: typescript, jestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am using typescript with typeORM and I have a jest test that looks as followed:\n\n```\ntest('add test', async () => {\n testRepoMock = {\n innerTestRepo: ({\n findOne: jest.fn().mockReturnValue(null),\n create: jest.fn().mockReturnValue({ id: 2 }),\n } as unknown) as Repository,\n };\n\n TestService.addvalue(id, testRepoMock);\n\n expect(testRepoMock.innerTestRepo.findOne).toHaveBeenCalledTimes(1);\n expect(testRepoMock.innerTestRepo.create).toHaveBeenCalledTimes(1);\n });\n```\n\nThe function I'm testing looks like this:\n\n```\nstatic async addvalue(\n id: number,\n repos?: { innerTestRepo: Repository },\n ): Promise {\n let repo;\n if (repos) {\n // basically use our mocks if this is a unit test\n repo = repos.innerTestRepo;\n } else {\n repo = await SqlDb.getRepository(ValuesModel);\n }\n\n let perms = await repo.findOne({ id });\n\n if (!perms) {\n perms = repo.create();\n perms = {\n ...perms,\n };\n await repo.save(perms);\n }\n\n return perms;\n }\n```\n\nWhat I cannot figure out is that the `expect(testRepoMock.innerTestRepo.create).toHaveBeenCalledTimes(1);` keeps reporting that `testRepoMock.innerTestRepo.create` was never called, even though I can log that perms is set to `{id:2}` via the mock and that the if statement is indeed entered.\n\nI even checked what happened if I move the repo.create out of that if statement as a sanity check and then the test passes, so it looks like something about the scope of the if statement confuses jest such that it does not realize that create has been called.\n\n========================================\n\nCode:\n```text\ntest('add test', async () => {\n testRepoMock = {\n innerTestRepo: ({\n findOne: jest.fn().mockReturnValue(null),\n create: jest.fn().mockReturnValue({ id: 2 }),\n } as unknown) as Repository<ValuesModel>,\n };\n\n TestService.addvalue(id, testRepoMock);\n\n expect(testRepoMock.innerTestRepo.findOne).toHaveBeenCalledTimes(1);\n expect(testRepoMock.innerTestRepo.create).toHaveBeenCalledTimes(1);\n });\n```\n\n```text\nstatic async addvalue(\n id: number,\n repos?: { innerTestRepo: Repository<ValuesModel> },\n ): Promise<Values> {\n let repo;\n if (repos) {\n // basically use our mocks if this is a unit test\n repo = repos.innerTestRepo;\n } else {\n repo = await SqlDb.getRepository(ValuesModel);\n }\n\n let perms = await repo.findOne({ id });\n\n if (!perms) {\n perms = repo.create();\n perms = {\n ...perms,\n };\n await repo.save(perms);\n }\n\n return perms;\n }\n```\n\n```text\nexpect(testRepoMock.innerTestRepo.create).toHaveBeenCalledTimes(1);\n```\n\n```text\ntestRepoMock.innerTestRepo.create\n```\n\n```text\n{id:2}\n```\n\n```text\ntest('add test', async () => {\n testRepoMock = {\n innerTestRepo: ({\n findOne: jest.fn().mockReturnValue(null),\n create: jest.fn().mockReturnValue({ id: 2 }),\n } as unknown) as Repository<ValuesModel>,\n };\n\n await TestService.addvalue(id, testRepoMock);\n\n expect(testRepoMock.innerTestRepo.findOne).toHaveBeenCalledTimes(1);\n expect(testRepoMock.innerTestRepo.create).toHaveBeenCalledTimes(1);\n});\n```\n\n```text\nawait\n```\n\n```text\naddValue\n```\n\n========================================\n\nComments:\n- Firstly you shouldn't have a conditional for testing in your production code. Secondly what *is* orgPermsRepoMock, how does it relate to the testRepoMock you're *actually* passing into addvalue?\n- @jonrsharpe orgPerms was a typo, good catch, I fixed that. And the conditional is not in the test, just the function I'm testing, if I understand correctly.\n- `findOne` is called asynchronously. thats why you can not check synchronously that consequent `create` was called\n- The conditional being in the function you're testing is the problem I refer to. Testing setup shouldn't bleed into production code. I guess you've had the classic issue (this function is hard to test because it creates its own collaborators) and applied the standard solution (so we'll invert the dependency and inject the collaborators to decouple it) but doing so *only* for the test means what you're testing isn't what actually runs in production.\n- That did it. Dang, maybe I need to go to bed. Thanks a bunch!\n- Is it weird that moving the create out of the if statement would get the test to pass? It passed every time too, so this does not seem like a timing matter. Either way, thanks again.\n- if you move it out and put it above `findOne`, yes it will pass, but if put after I don't see how it can pass ....","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":148,"estimatedTokens":1198}}467{"id":"stack-67534817","source":"stackoverflow","questionId":67534817,"title":"How to join 3 relation table using typeorm nestjs","tags":["mysql","express","nestjs","typeorm"],"text":"Title: How to join 3 relation table using typeorm nestjs\nTags: mysql, express, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am using typeorm with NestJs, I try to join 3 relations but got an error `path comment.user in entity was not found`\n\nHere is my table User\n\nId\nusername\n\n1\nrow\n\n```\n@PrimaryGeneratedColumn()\n id: number;\n @Column()\n username: string;\n @OneToMany(() => PostEntity, (post) => post.user, { eager: true })\n posts: PostEntity[];\n```\n\nHere is my table Posts\n\nId\ndesc\nuser_id\n\n1\ntext\n1\n\n```\n@PrimaryGeneratedColumn()\n id: number;\n @Column()\n desc: string;\n @Column()\n userId: number;\n\n @ManyToOne(() => User, (user) => user.posts, {\n eager: false,\n onDelete: 'CASCADE',\n })\n user: User[];\n @OneToMany(() => CommentEntity, (comment: CommentEntity) => comment.post, {\n eager: true,\n onDelete: 'CASCADE',\n })\n comment: CommentEntity[];\n```\n\nHere is my table comment\n\nId\ncomment\nuser_id\npostId\n\n1\ncomment post 1\n1\n1\n\n```\n@PrimaryGeneratedColumn()\n id: number;\n @Column()\n comment: string;\n @Column()\n userId: number;\n @Column()\n postId: number;\n @ManyToOne(() => PostEntity, () => (post: PostEntity) => post.comment, {\n eager: false,\n onDelete: 'CASCADE',\n })\n\n post: PostEntity[];\n @OneToOne(() => User)\n @JoinColumn()\n user: User;\n```\n\nIn here I use OneToOne because 1 comment can comment by only 1 user\n\nthis is what my data look like\n\n```\n```\nthis.createQueryBuilder('post')\n .leftJoinAndSelect('post.user', 'user')\n .leftJoinAndSelect('post.comment', 'comment')\n .select(['post', 'user.id', 'user.username', 'comment'])\n .getMany();\n```\n```\n\nthis is what I get\n\n```\n[\n {\n id: 1,\n description: 'comment post 1',\n userId: 1,\n user: {\n id: 1,\n username: 'row',\n },\n comment: [\n {\n id: 1,\n description: 'comment',\n userId: 1,\n postId: 1,\n },\n ],\n },\n];\n```\n\nIn comment I want to join userId for user that comment . I want data look like this\n\n```\n[\n {\n id: 1,\n description: 'comment post 1',\n userId: 1,\n user: {\n id: 1,\n username: 'row',\n },\n comment: [\n {\n id: 1,\n description: 'comment',\n userId: 1,\n postId: 1,\n user: {\n // if different user comment will show different username\n id: 1, \n username: 'row',\n },\n },\n ],\n },\n];\n```\n\nThis is what I try to do\n\n```\nthis.createQueryBuilder('post')\n .leftJoinAndSelect('post.user', 'user')\n .leftJoinAndSelect('post.comment', 'comment')\n .leftJoinAndSelect('post.comment.user', 'user') \n .select(['post', 'user.id', 'user.username', 'comment'])\n .orderBy('post.updated_at', 'DESC')\n .getMany();\n\n .leftJoinAndSelect('post.comment.user', 'user') // In this line I want to join userId but Its show an error path comment.user in entity was not found\n```\n\n**UPDATE**\n\nI try to use this ( this mean PostEntity)\n\n```\nthis.find({ relations: ['user', 'comment', 'comment.user']\n```\n\nbut still not working\n\n========================================\n\nCode:\n```text\n@PrimaryGeneratedColumn()\n id: number;\n @Column()\n username: string;\n @OneToMany(() => PostEntity, (post) => post.user, { eager: true })\n posts: PostEntity[];\n```\n\n```text\n@PrimaryGeneratedColumn()\n id: number;\n @Column()\n desc: string;\n @Column()\n userId: number;\n\n @ManyToOne(() => User, (user) => user.posts, {\n eager: false,\n onDelete: 'CASCADE',\n })\n user: User[];\n @OneToMany(() => CommentEntity, (comment: CommentEntity) => comment.post, {\n eager: true,\n onDelete: 'CASCADE',\n })\n comment: CommentEntity[];\n```\n\n```text\n@PrimaryGeneratedColumn()\n id: number;\n @Column()\n comment: string;\n @Column()\n userId: number;\n @Column()\n postId: number;\n @ManyToOne(() => PostEntity, () => (post: PostEntity) => post.comment, {\n eager: false,\n onDelete: 'CASCADE',\n })\n\n post: PostEntity[];\n @OneToOne(() => User)\n @JoinColumn()\n user: User;\n```\n\n```text\n```\nthis.createQueryBuilder('post')\n .leftJoinAndSelect('post.user', 'user')\n .leftJoinAndSelect('post.comment', 'comment')\n .select(['post', 'user.id', 'user.username', 'comment'])\n .getMany();\n```\n```\n\n```text\n[\n {\n id: 1,\n description: 'comment post 1',\n userId: 1,\n user: {\n id: 1,\n username: 'row',\n },\n comment: [\n {\n id: 1,\n description: 'comment',\n userId: 1,\n postId: 1,\n },\n ],\n },\n];\n```\n\n```text\n[\n {\n id: 1,\n description: 'comment post 1',\n userId: 1,\n user: {\n id: 1,\n username: 'row',\n },\n comment: [\n {\n id: 1,\n description: 'comment',\n userId: 1,\n postId: 1,\n user: {\n // if different user comment will show different username\n id: 1, \n username: 'row',\n },\n },\n ],\n },\n];\n```\n\n```text\nthis.createQueryBuilder('post')\n .leftJoinAndSelect('post.user', 'user')\n .leftJoinAndSelect('post.comment', 'comment')\n .leftJoinAndSelect('post.comment.user', 'user') \n .select(['post', 'user.id', 'user.username', 'comment'])\n .orderBy('post.updated_at', 'DESC')\n .getMany();\n\n\n .leftJoinAndSelect('post.comment.user', 'user') // In this line I want to join userId but Its show an error path comment.user in entity was not found\n```\n\n```text\nthis.find({ relations: ['user', 'comment', 'comment.user']\n```\n\n```text\npath comment.user in entity was not found\n```\n\n```js\n@OneToOne(() => User)\n@JoinColumn({name: 'userId'})\nuser: User;\n```\n\n```js\nthis.createQueryBuilder('post')\n .leftJoinAndSelect('post.user', 'user')\n .leftJoinAndSelect('post.comment', 'comment')\n .leftJoinAndSelect('comment.user', 'commentedUser') \n .select(['post', 'user.id', 'user.username', 'comment', 'commentedUser'])\n .orderBy('post.updated_at', 'DESC')\n .getMany();\n```\n\n```text\nComment\n```\n\n========================================\n\nComments:\n- didn't work I got same result. Do I have to change or add any entity about commentedUser ?\n- comment is return in an array so am not sure how to work with that\n- I updated my answer, could you check now. (You don't need to do anything about `commentedUser` it is just an alias)\n- I try the still not return userDaata in post.comment[]\n- no error but the user still didnt join I already add @JoinColumn({ name: 'userId' })\n- Then try changing this `.select(['post', 'user.id', 'user.username', 'comment', 'commentedUser'])`\n- Glad to be of help. Good luck! 🍻","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":12,"totalLines":339,"estimatedTokens":1568}}468{"id":"stack-64849855","source":"stackoverflow","questionId":64849855,"title":"TypeORM conditional nullable?","tags":["postgresql","nestjs","typeorm"],"text":"Title: TypeORM conditional nullable?\nTags: postgresql, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am developing a log in system in NestJS using TypeORM and Postgres.\nIn my login options, I propose the user to use a couple email / password or to use an OAuth authentication. But once an account is created, they are not mutually exclusive (a user can have an email + password and a Google account attached to his account, for example).\n\nTherefore, I would like to make the password OR the OAuthLogin nullable, but at least one of them should never be nullable.\n\nIs it possible to achieve this with TypeORM ?\n\n```\n@Entity()\nclass User {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ unique: true })\n public email: string;\n\n @Column({ nullable: true })\n @Exclude()\n public password?: string;\n\n @JoinColumn()\n @OneToMany(() => OAuthLogin, (provider: OAuthLogin) => provider.user, {\n cascade: true,\n })\n public oAuthLogins: OAuthLogin[];\n}\n\nexport default User;\n```\n\n(P. S.: for my current code, I chose to make the password only nullable...)\n\n========================================\n\nCode:\n```js\n@Entity()\nclass User {\n @PrimaryGeneratedColumn()\n public id: number;\n\n @Column({ unique: true })\n public email: string;\n\n @Column({ nullable: true })\n @Exclude()\n public password?: string;\n\n @JoinColumn()\n @OneToMany(() => OAuthLogin, (provider: OAuthLogin) => provider.user, {\n cascade: true,\n })\n public oAuthLogins: OAuthLogin[];\n}\n\nexport default User;\n```\n\n```js\n@Column({ nullable: true })\n@Exclude()\n@IsNotEmpty()\n@ValidateIf(u => !u.oAuthLogins || u.oAuthLogins.length === 0)\npublic password?: string;\n\n@JoinColumn()\n@IsArray()\n@ValidateIf(u => !u.password)\n@OneToMany(() => OAuthLogin, (provider: OAuthLogin) => provider.user, {\ncascade: true,\n})\npublic oAuthLogins?: OAuthLogin[];\n```\n\n```js\nimport { validate } from 'class-validator';\n...\nvalidate(user)\n```\n\n```js\n// main.ts\napp.useGlobalPipes(new ValidationPipe({ whitelist: true }));\n```\n\n```text\nValidateIf\n```\n\n```text\nclass-validator\n```\n\n```text\nValidationPipe\n```\n\n========================================\n\nComments:\n- I don't know about typeorm, but in postgres you need to make both columns nullable and add a `CHECK` constraint on the table with `num_nonnulls(password, o_auth_logins) >= 1` or something similar.\n- I'm looking into this: there seems to be a Check decorator I can do some verification with, but I don't find how to check if the relation exists... `@Check(`\"password\" IS NOT NULL OR \"oAuthLogins\" IS NOT NULL`)` isn't working because Postgres looks for a oAuthLogins property instead of a relation.\n- Oh, I missed that it's a relation as you spoke of \"nullable\". No, you can't do that with a check constraint. If you wanted to do this on a database level, you'd need a trigger.\n- Well it's not really the relation that should be nullable, but rather the data at the other end. Handling relation data is the one thing ORMs aren't good for and therefore, make it a bit more complicated ^^","metadata":{"transformedAt":"2026-08-18T18:33:44.718Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":109,"estimatedTokens":758}}469{"id":"stack-68583728","source":"stackoverflow","questionId":68583728,"title":"How to correct implement the Repository Adapter?","tags":["typescript","backend","nestjs","typeorm","clean-architecture"],"text":"Title: How to correct implement the Repository Adapter?\nTags: typescript, backend, nestjs, typeorm, clean-architecture\nSource: Stack Overflow\n\nQuestion:\nI started learning how to build Clean Architecture based on TypeScript and NestJS. Everything was ok until I started implementing the Repository Adapter and Controllers. The main problem is incompatible return types for the API methods and use-cases.\n\nThe idea was to put entities and use-cases in the **core** folderin which use-cases use repository adapter (through DI). This adapter implements the repository interface from the **core** folder too.\n\nImplementation of the repository adapter contains in **app**. **app** also contains NestJS implementation, TypeOrm entities etc. But also I want to use a repository for some controllers like `getAll query`.\n\n**!!!AND THE PROBLEM!!!**\n\nFor almost every command, I have to use `Mappers` because TypeORM entity and Domain Entity are incompatible types. And I think that's okay if we pass that data to the use-case because we need to transform data from TypeOrm shape to the domain shape.\n\nBut if I just call the repository adapter method in the controller I need to map data back again... And I don't know how to skip unnecessary steps.\nIn my imagination, I can just call the repository method in **app** service, and that is it.\nAnd if I skip the mapping back then all data properties will have the prefix `_`(\n\nMaybe someone met the same problem?\n\n//CORE ZONE\n\nAccount entity (`/domain/account`):\n\n```\nexport type AccountId = string;\nexport class Account {\nconstructor(\n private readonly _id: AccountId,\n private readonly _firstName: string\n) {}\n\n get id(): AccountId {\n return this._id;\n }\n\n get firstName() {\n return this._firstName;\n }\n}\n```\n\nRepository interface (`repositories/account-repository`):\n\n```\nimport { Account } from '../domains/account';\n\nexport interface AccountRepository {\n getAccountById(id: string): Promise;\n getAllAccounts(): Promise;\n}\n```\n\nExample of use-case with repositoty:\n\n```\nimport { AccountRepository } from '../../repositories/account-repository';\n\nexport class ToDoSomething {\n constructor(private readonly _accountRepository: AccountRepository) {}\n\n async doSomethingWithAccount(command): Promise {\n const account = await this._accountRepository.getAccountById(\n command.accountId,\n );\n\n if (!account) {\n return false;\n }\n\n return true;\n }\n}\n```\n\n//APP ZONE\n\nRepository Adapter:\n\n```\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\nimport { Account } from '../../../../core/domains/account';\nimport { AccountRepository } from '../../../../core/repositories/account-repository';\nimport { AccountEntity } from '../account.entity';\nimport { AccountMapper } from '../account.mapper';\n\n@Injectable()\nexport class AccountRepositoryAdapter implements AccountRepository {\n constructor(\n @InjectRepository(AccountEntity)\n private readonly _accountRepository: Repository,\n ) {}\n\n async getAccountById(id: string): Promise {\n return this._accountRepository.findOne({ id: id });\n // will return { id: 1, firstName: \"name\" }\n // and because I need to use MapToDomain\n }\n\n async getAllAccounts(): Promise {\n return this._accountRepository.find();\n // Here too I need to use MapToDomain for every item\n }\n}\n```\n\nTypeOrm Account:\n\n```\nimport {\n Column,\n Entity,\n PrimaryGeneratedColumn,\n} from 'typeorm';\n\n@Entity({ name: 'account' })\nexport class AccountEntity {\n @PrimaryGeneratedColumn()\n id: string;\n\n @Column()\n firstName: string;\n}\n```\n\n========================================\n\nCode:\n```text\nexport type AccountId = string;\nexport class Account {\nconstructor(\n private readonly _id: AccountId,\n private readonly _firstName: string\n) {}\n\n get id(): AccountId {\n return this._id;\n }\n\n get firstName() {\n return this._firstName;\n }\n}\n```\n\n```text\nimport { Account } from '../domains/account';\n\nexport interface AccountRepository {\n getAccountById(id: string): Promise<Account>;\n getAllAccounts(): Promise<Account[]>;\n}\n```\n\n```text\nimport { AccountRepository } from '../../repositories/account-repository';\n\nexport class ToDoSomething {\n constructor(private readonly _accountRepository: AccountRepository) {}\n\n async doSomethingWithAccount(command): Promise<boolean> {\n const account = await this._accountRepository.getAccountById(\n command.accountId,\n );\n\n if (!account) {\n return false;\n }\n\n return true;\n }\n}\n```\n\n```text\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\nimport { Account } from '../../../../core/domains/account';\nimport { AccountRepository } from '../../../../core/repositories/account-repository';\nimport { AccountEntity } from '../account.entity';\nimport { AccountMapper } from '../account.mapper';\n\n@Injectable()\nexport class AccountRepositoryAdapter implements AccountRepository {\n constructor(\n @InjectRepository(AccountEntity)\n private readonly _accountRepository: Repository<AccountEntity>,\n ) {}\n\n async getAccountById(id: string): Promise<Account> {\n return this._accountRepository.findOne({ id: id });\n // will return { id: 1, firstName: \"name\" }\n // and because I need to use MapToDomain\n }\n\n async getAllAccounts(): Promise<Account[]> {\n return this._accountRepository.find();\n // Here too I need to use MapToDomain for every item\n }\n}\n```\n\n```text\nimport {\n Column,\n Entity,\n PrimaryGeneratedColumn,\n} from 'typeorm';\n\n@Entity({ name: 'account' })\nexport class AccountEntity {\n @PrimaryGeneratedColumn()\n id: string;\n\n @Column()\n firstName: string;\n}\n```\n\n```text\ngetAll query\n```\n\n```text\nMappers\n```\n\n```text\n_\n```\n\n```text\n/domain/account\n```\n\n```text\nrepositories/account-repository\n```\n\n========================================\n\nComments:\n- Great. I've thought I'm doing extra steps with data mapping. But anyway we should form Request data to Domain form. And of course, need to form back. We don't have another way. Can you suggest creating the use-case for almost every API call? Like GET:/get-all- users and etc. The reason why I got this question is. Should we convert every item in the list if we don't need to do some domain logic? Because in my point of view we can avoid it, but I don't know how to do it..( Maybe we can skip the convert to Domain model and immediately pass data to the Presenter. And of course, that is correct?\n- As to my experience \"short cuts\" are ok in the beginning of the project or when there is almost no logic needed for respond to a request. Over time projects usually get more complex and then short cuts should be removed and then really every request will us use cases.","metadata":{"transformedAt":"2026-08-18T18:33:44.719Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":10,"totalLines":249,"estimatedTokens":1682}}470{"id":"stack-65604757","source":"stackoverflow","questionId":65604757,"title":"How can i post a DTO that contain an array of entities?","tags":["nestjs","typeorm"],"text":"Title: How can i post a DTO that contain an array of entities?\nTags: nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have a couple of questions about NestJS and TypeOrm.\nFirst, how to pass an array of strings to DTO? I tried just to use :string[] type, but the compiler gives an error.\nThis is my Post entity:\n\n```\n@Entity('posts')\nexport class Post {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(() => User, user => user.posts, { cascade: true })\n author: number;\n\n @Column({ type: 'timestamp' })\n date: Date;\n\n @Column()\n text: string;\n \n @Column({ default: 0 })\n likes: number;\n\n @OneToMany(() => Photo, photo => photo.post, { cascade: true })\n photos: Photo[];\n}\n```\n\nAnd CreatePostDto:\n\n```\nexport class CreatePostDto {\n authorId: number;\n date: Date;\n text?: string;\n // photos?: string[];\n}\n```\n\nAnd the second question: How can i save to the repository every photo (keeping the connection with post), posts to the posts repo and update user by adding new post binded to him.\nI tried something like this, but it won't work obviously.\n\n```\nasync create(createPostDto: CreatePostDto) {\n const post = this.postsRepository.create(createPostDto);\n const user = await this.usersRepository.findOne(createPostDto.authorId);\n \n return this.postsRepository.save({author: user, date: createPostDto.date, text: createPostDto.text});\n }\n```\n\n========================================\n\nTop Answer:\n```\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column(\"simple-array\")\n names: string[]\n}\n```\n\n========================================\n\nCode:\n```text\n@Entity('posts')\nexport class Post {\n @PrimaryGeneratedColumn()\n id: number;\n\n @ManyToOne(() => User, user => user.posts, { cascade: true })\n author: number;\n\n @Column({ type: 'timestamp' })\n date: Date;\n\n @Column()\n text: string;\n \n @Column({ default: 0 })\n likes: number;\n\n @OneToMany(() => Photo, photo => photo.post, { cascade: true })\n photos: Photo[];\n}\n```\n\n```text\nexport class CreatePostDto {\n authorId: number;\n date: Date;\n text?: string;\n // photos?: string[];\n}\n```\n\n```text\nasync create(createPostDto: CreatePostDto) {\n const post = this.postsRepository.create(createPostDto);\n const user = await this.usersRepository.findOne(createPostDto.authorId);\n \n return this.postsRepository.save({author: user, date: createPostDto.date, text: createPostDto.text});\n }\n```\n\n```text\nasync create(createPostDto: CreatePostDto) {\n let photos:Array<Photo> = [] ; array of type photo entity\n for(let urlPhoto of createPostDto.photos)\n {\n let photo = await this.imageRepository.save({url : urlPhoto }); you must save the photos first\n photos.push(photo); \n }\n const user = await this.usersRepository.findOne(createPostDto.authorId);\n \n return this.postsRepository.save({author: user, date: createPostDto.date, text: \n createPostDto.text,photos:photos});\n }\n```\n\n```text\n@Entity()\nexport class User {\n @PrimaryGeneratedColumn()\n id: number\n\n @Column(\"simple-array\")\n names: string[]\n}\n```\n\n========================================\n\nComments:\n- are the photos already saved in the database? what is the content of the photos array will be?can you photo entity?\n- @Youba, no, photos are created too. The content of photos array will be the string. Array of strings (urls). I already found a solution, but don't know how correct is it: prnt.sc/wi6d1p\n- check my answer\n- Thank you. It worked for me, but image's postId is null. How can i pass the post object to the photo before Post initialization? (my post entity has url and post: PostEntity)\n- can you the photo entity?\n- prnt.sc/wi7619 Sorry for the link. Can't send the formatted code.\n- Wait, everything works nice. I used forEach instead of for (let ... of ..). Thank you!\n- good luck, next time try to edit your post with the code asked for it's better to make a screenshot,\n- Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you edit your answer to include an explanation of what you're doing** and why you believe it is the best approach?\n- This is not an entity array. And as far as I know, not every database supports array types. The answer is to map the array DTO and save every entity with a connection to its parent.","metadata":{"transformedAt":"2026-08-18T18:33:44.719Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":5,"totalLines":152,"estimatedTokens":1136}}471{"id":"stack-62838538","source":"stackoverflow","questionId":62838538,"title":"Nested AND and OR conditions on find methods (not queryBuilder)","tags":["javascript","node.js","typescript","typeorm"],"text":"Title: Nested AND and OR conditions on find methods (not queryBuilder)\nTags: javascript, node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nPrecondition: I'm using Typeorm to perform database queries and I can't use the `queryBuilder` methods to create this query, but only the `find` method.\n\nI need to translate a query like:\n\n```\nSELECT * FROM address where zip = 123 and (street = 'asd' or city = 'New York');\n```\n\nI know that the solution can be trivial using the usual `queryBuilder`, but in this particular case I cannot use it.\n\nIs it possible to implement these nested and/or conditions only using the `find` method?\n\n========================================\n\nCode:\n```text\nSELECT * FROM address where zip = 123 and (street = 'asd' or city = 'New York');\n```\n\n```text\nqueryBuilder\n```\n\n```text\nfind\n```\n\n```text\nqueryBuilder\n```\n\n```text\nfind\n```\n\n```text\nAddress.find([{\n zip: 123, street: 'asd'\n}, {\n zip: 123, city: 'New York'\n}]);\n```\n\n```text\nzip = 123 and (street = 'asd' or city = 'New York')\n```\n\n```text\n(zip = 123 and street = 'asd') or (zip = 123 and city = 'New York')\n```\n\n```text\nand\n```\n\n```text\nor\n```\n\n```text\nfind\n```\n\n```text\ntypeorm\n```\n\n```text\nor\n```\n\n========================================\n\nComments:\n- is this on an array?\n- Does this answer your question? Find object by id in an array of JavaScript objects\n- Soory @Anthony, but it involves the use of the Typeorm library, it is not on a array\n- Well, you are right. The problem is that inverting the position of the OR and AND conditions can generate a less efficient query. But, at the moment, it seems to be the unique possibility.","metadata":{"transformedAt":"2026-08-18T18:33:44.719Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":83,"estimatedTokens":409}}472{"id":"stack-66904523","source":"stackoverflow","questionId":66904523,"title":"What would be a proper way to test TypeORM's QueryBuilder chaining methods?","tags":["node.js","postgresql","jestjs","nestjs","typeorm"],"text":"Title: What would be a proper way to test TypeORM's QueryBuilder chaining methods?\nTags: node.js, postgresql, jestjs, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nThis is users.service.ts\n\n```\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(User) private readonly users: Repository,\n @InjectRepository(Verification)\n private readonly verifications: Repository,\n private readonly jwtService: JwtService,\n private readonly mailService: MailService,\n ) {}\n\n async findById(id: number): Promise {\n try {\n const user = await this.users.findOneOrFail({ id });\n return {\n ok: true,\n user: user,\n };\n } catch (error) {\n return { ok: false, error: 'User Not Found' };\n }\n }\n```\n\nI'm using TypeORM's Repository API(e.g. users.findOne, users.find, users.delete, etc).\nAnd The below file is a test file to test \"users.service\".\n\nThis is \"users.service.spec.ts\"\n\n```\nconst mockRepository = () => ({\n findOne: jest.fn(),\n findOneOrFail: jest.fn(),\n save: jest.fn(),\n create: jest.fn(),\n delete: jest.fn(),\n});\n\nconst mockJwtService = {\n sign: jest.fn(() => 'signed-token'),\n verify: jest.fn(),\n};\n\nconst mockMailService = () => ({\n sendVerificationEmail: jest.fn(),\n});\n\ntype MockRepository = Partial, jest.Mock>>;\n\ndescribe('UserService', () => {\n let service: UserService;\n let usersRepository: MockRepository;\n let verificationsRepository: MockRepository;\n let mailService: MailService;\n let jwtService: JwtService;\n\n beforeEach(async () => {\n const module = await Test.createTestingModule({\n providers: [\n UserService,\n {\n provide: getRepositoryToken(User),\n useValue: mockRepository(),\n },\n {\n provide: getRepositoryToken(Verification),\n useValue: mockRepository(),\n },\n {\n provide: JwtService,\n useValue: mockJwtService,\n },\n {\n provide: MailService,\n useValue: mockMailService(),\n },\n ],\n }).compile();\n service = module.get(UserService);\n mailService = module.get(MailService);\n jwtService = module.get(JwtService);\n usersRepository = module.get(getRepositoryToken(User));\n verificationsRepository = module.get(getRepositoryToken(Verification));\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n\n describe('findById', () => {\n it('should fail if user is not found', async () => {\n usersRepository.findOneOrFail.mockRejectedValue(new Error());\n const result = await service.findById(1);\n expect(result).toEqual({\n ok: false,\n error: 'User Not Found',\n });\n });\n\n it('should find an existing user', async () => {\n const findByIdArgs = {\n id: 1,\n };\n usersRepository.findOneOrFail.mockResolvedValue(findByIdArgs);\n const result = await service.findById(1);\n expect(result).toEqual({\n ok: true,\n user: findByIdArgs,\n });\n });\n });\n```\n\nWhat if I switch to use TypeORM's querybuilder method.\n\n```\nasync findByIdWithQueryBuilder(id: number): Promise {\n try {\n const user = await this.users\n .createQueryBuilder('user')\n .where('bundle.id = :id', { id })\n .getOneOrFail();\n\n return {\n ok: true,\n user,\n };\n } catch (error) {\n return { ok: false, error: 'User Not Found' };\n }\n }\n```\n\nThe question is\nHow can I mock QueryBuilder's chaining methods?\n\nI tried\n\n```\nconst mockRepository = () => ({\n findOne: jest.fn(),\n findOneOrFail: jest.fn(),\n save: jest.fn(),\n create: jest.fn(),\n delete: jest.fn(),\n createQueryBuilder: jest.fn(() => ({\n delete: () => jest.fn().mockReturnThis(),\n innerJoinAndSelect: () => jest.fn().mockReturnThis(),\n innerJoin: () => jest.fn().mockReturnThis(),\n leftJoinAndSelect: () => jest.fn().mockReturnThis(),\n leftJoin: () => jest.fn().mockReturnThis(),\n from: () => jest.fn().mockReturnThis(),\n where: () => jest.fn().mockReturnThis(),\n orWhere: () => jest.fn().mockReturnThis(),\n andWhere: () => jest.fn().mockReturnThis(),\n execute: () => jest.fn().mockReturnThis(),\n orderBy: () => jest.fn().mockReturnThis(),\n take: () => jest.fn().mockReturnThis(),\n skip: () => jest.fn().mockReturnThis(),\n getOne: () => jest.fn(),\n getMany: () => jest.fn(),\n getManyAndCount: () => jest.fn(),\n })),\n});\n```\n\nhttps://i.sstatic.net/EHeVq.png\n\nI got stuck here...\n\nWhat would be the proper way to mock the chaining methods of QueryBuilder api?\n\n========================================\n\nCode:\n```text\n@Injectable()\nexport class UserService {\n constructor(\n @InjectRepository(User) private readonly users: Repository<User>,\n @InjectRepository(Verification)\n private readonly verifications: Repository<Verification>,\n private readonly jwtService: JwtService,\n private readonly mailService: MailService,\n ) {}\n\n async findById(id: number): Promise<UserProfileOutput> {\n try {\n const user = await this.users.findOneOrFail({ id });\n return {\n ok: true,\n user: user,\n };\n } catch (error) {\n return { ok: false, error: 'User Not Found' };\n }\n }\n```\n\n```text\nconst mockRepository = () => ({\n findOne: jest.fn(),\n findOneOrFail: jest.fn(),\n save: jest.fn(),\n create: jest.fn(),\n delete: jest.fn(),\n});\n\nconst mockJwtService = {\n sign: jest.fn(() => 'signed-token'),\n verify: jest.fn(),\n};\n\nconst mockMailService = () => ({\n sendVerificationEmail: jest.fn(),\n});\n\ntype MockRepository<T = any> = Partial<Record<keyof Repository<T>, jest.Mock>>;\n\ndescribe('UserService', () => {\n let service: UserService;\n let usersRepository: MockRepository<User>;\n let verificationsRepository: MockRepository<Verification>;\n let mailService: MailService;\n let jwtService: JwtService;\n\n beforeEach(async () => {\n const module = await Test.createTestingModule({\n providers: [\n UserService,\n {\n provide: getRepositoryToken(User),\n useValue: mockRepository(),\n },\n {\n provide: getRepositoryToken(Verification),\n useValue: mockRepository(),\n },\n {\n provide: JwtService,\n useValue: mockJwtService,\n },\n {\n provide: MailService,\n useValue: mockMailService(),\n },\n ],\n }).compile();\n service = module.get<UserService>(UserService);\n mailService = module.get<MailService>(MailService);\n jwtService = module.get<JwtService>(JwtService);\n usersRepository = module.get(getRepositoryToken(User));\n verificationsRepository = module.get(getRepositoryToken(Verification));\n });\n\n it('should be defined', () => {\n expect(service).toBeDefined();\n });\n\n describe('findById', () => {\n it('should fail if user is not found', async () => {\n usersRepository.findOneOrFail.mockRejectedValue(new Error());\n const result = await service.findById(1);\n expect(result).toEqual({\n ok: false,\n error: 'User Not Found',\n });\n });\n\n it('should find an existing user', async () => {\n const findByIdArgs = {\n id: 1,\n };\n usersRepository.findOneOrFail.mockResolvedValue(findByIdArgs);\n const result = await service.findById(1);\n expect(result).toEqual({\n ok: true,\n user: findByIdArgs,\n });\n });\n });\n```\n\n```text\nasync findByIdWithQueryBuilder(id: number): Promise<UserProfileOutput> {\n try {\n const user = await this.users\n .createQueryBuilder('user')\n .where('bundle.id = :id', { id })\n .getOneOrFail();\n\n return {\n ok: true,\n user,\n };\n } catch (error) {\n return { ok: false, error: 'User Not Found' };\n }\n }\n```\n\n```text\nconst mockRepository = () => ({\n findOne: jest.fn(),\n findOneOrFail: jest.fn(),\n save: jest.fn(),\n create: jest.fn(),\n delete: jest.fn(),\n createQueryBuilder: jest.fn(() => ({\n delete: () => jest.fn().mockReturnThis(),\n innerJoinAndSelect: () => jest.fn().mockReturnThis(),\n innerJoin: () => jest.fn().mockReturnThis(),\n leftJoinAndSelect: () => jest.fn().mockReturnThis(),\n leftJoin: () => jest.fn().mockReturnThis(),\n from: () => jest.fn().mockReturnThis(),\n where: () => jest.fn().mockReturnThis(),\n orWhere: () => jest.fn().mockReturnThis(),\n andWhere: () => jest.fn().mockReturnThis(),\n execute: () => jest.fn().mockReturnThis(),\n orderBy: () => jest.fn().mockReturnThis(),\n take: () => jest.fn().mockReturnThis(),\n skip: () => jest.fn().mockReturnThis(),\n getOne: () => jest.fn(),\n getMany: () => jest.fn(),\n getManyAndCount: () => jest.fn(),\n })),\n});\n```\n\n```js\nimport { QueryBuilder } from 'typeorm';\n\ndescribe('Name of the group', () => {\n it('should do something', () => {\n const queryBuilder: any = {\n into: jest.fn().mockReturnThis(),\n values: jest.fn().mockReturnThis(),\n onConflict: jest.fn().mockReturnThis(),\n setParameter: jest.fn().mockReturnThis(),\n execute: jest.fn().mockRejectedValueOnce(new Error('db Error')),\n // execute: jest.fn().mockResolvedValueOnce({ res: 'mockRes' }),\n };\n jest\n .spyOn(QueryBuilder.prototype, 'insert')\n .mockReturnValueOnce(queryBuilder);\n });\n});\n```\n\n```js\nexport async function doQuery(input: any){\n const queryRunner = await Entity.createQueryRunner();\n await queryRunner.manager\n .createQueryBuilder()\n .insert()\n .into(Entity)\n .values(input)\n .onConflict(\n `(\"id\") DO UPDATE SET \"date\" = :date`\n )\n .setParameter('date', date)\n .execute();\n}\n```\n\n```text\nQueryBuilder\n```\n\n========================================\n\nComments:\n- Related: stackoverflow.com/questions/66885517/…","metadata":{"transformedAt":"2026-08-18T18:33:44.719Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":380,"estimatedTokens":2330}}473{"id":"stack-67031078","source":"stackoverflow","questionId":67031078,"title":"Migrate JSON Data to Database Using TypeORM","tags":["node.js","json","migration","typeorm"],"text":"Title: Migrate JSON Data to Database Using TypeORM\nTags: node.js, json, migration, typeorm\nSource: Stack Overflow\n\nQuestion:\nI want to migrate my JSON data to PostgreSQL database using TypeORM. I have many relationship between tables and I have 2 JSON file having 13,000 records and 70,000 records. I want to migrate all of this data to DB. This JSON files are from old database tables and i want to migrate this data to new database tables. `RouteName` and `SerialNo` uniquely maps one to many loanee to collections.\n\n### Loanee Entity\n\n```\nimport { User } from \"./User\";\nimport {\n BaseEntity,\n Column,\n Entity,\n ManyToOne,\n OneToMany,\n PrimaryGeneratedColumn,\n} from \"typeorm\";\nimport { Loan } from \"./Loan\";\nimport { Village } from \"./Village\";\nimport { Penalty } from \"./Penalty\";\nimport { Transcation } from \"./Transcation\";\n\n@Entity()\nexport class Loanee extends BaseEntity {\n @PrimaryGeneratedColumn(\"uuid\")\n id: string;\n\n @ManyToOne(() => User, (user) => user.loanees)\n user: User;\n\n @OneToMany(() => Loan, (loan) => loan.loanee)\n loans: Loan[];\n\n @ManyToOne(() => Village, (village) => village.loanees)\n village: Village;\n\n @OneToMany(() => Penalty, (penalty) => penalty.loanee)\n penalties: Penalty[];\n\n @OneToMany(() => Transcation, (transcation) => transcation.fromLoanee)\n from: Transcation[];\n\n @OneToMany(() => Transcation, (transcation) => transcation.toLoanee)\n to: Transcation[];\n\n @Column()\n fullName: string;\n\n @Column({ nullable: true })\n profileImage: string;\n\n @Column()\n address: string;\n\n @Column({ default: \"0\" })\n phoneNumber: string;\n\n @Column()\n guarantorName: string;\n\n @Column()\n guarantorVillage: string;\n\n @Column()\n guarantorAddress: string;\n\n @Column({ default: \"0\" })\n guarantorPhoneNumber: string;\n\n @Column({ nullable: true })\n remark: string;\n\n @Column({ default: 0 })\n penaltyAmount: number;\n\n @Column({ unique: true, nullable: false })\n loaneeNumber: string;\n\n @Column({ type: \"timestamp\" })\n timestamp: Date;\n}\n```\n\n### Collection Entity\n\n```\nimport {\n BaseEntity,\n Column,\n Entity,\n ManyToOne,\n PrimaryGeneratedColumn,\n} from \"typeorm\";\nimport { Loan } from \"./Loan\";\nimport { Route } from \"./Route\";\nimport { User } from \"./User\";\n\n@Entity()\nexport class Collection extends BaseEntity {\n @PrimaryGeneratedColumn(\"uuid\")\n id: string;\n\n @ManyToOne(() => Loan, (loan) => loan.collections)\n loan: Loan;\n\n @ManyToOne(() => User, (user) => user.collections)\n user: User;\n\n @ManyToOne(() => Route, (route) => route.collections)\n route: Route;\n\n @Column()\n amount: number;\n\n @Column()\n dueAmount: number;\n\n @Column({ nullable: true })\n remark: string;\n\n @Column({ type: \"timestamp\" })\n timestamp: Date;\n}\n```\n\n### Loanee JSON FILE\n\n```\n[\n {\n \"SerialNo\": 178,\n \"LineName\": \"FOUR LINE\",\n \"RouteName\": \"FRIDAY WEEKLY 3 NOLIASAHI\",\n \"LoneeName\": \"POTTI BHAGABAN\",\n \"LoneeAddress\": \"S/O POTTI GORAMMA\",\n \"LoneeVillage\": \"BALI NOLIASAHI\",\n \"LoneeOccupation\": \"MUTCHILU\",\n \"GurantorName\": \"-\",\n \"GurantorAddress\": \"-\",\n \"GurantorVillage\": \"-\",\n \"GurantorOccupation\": \"-\",\n \"FromDate\": \"9/30/05 0:00\",\n \"ToDate\": \"12/9/05 0:00\",\n \"PaymentMode\": \"Weekly70\",\n \"LoanAmount\": 1500,\n \"InstallmentAmount\": 150,\n \"AmountPaid\": 0,\n \"BalanceAmount\": 1500,\n \"AverageAmount\": 21.43\n },\n {\n \"SerialNo\": 3119,\n \"LineName\": \"ONE LINE\",\n \"RouteName\": \"1 DAILY\",\n \"LoneeName\": \"KUNI DAS\",\n \"LoneeAddress\": \"W/O BHASKAR DAS\",\n \"LoneeVillage\": \"RATNA PUR--1ST.\",\n \"LoneeOccupation\": \"-\",\n \"GurantorName\": \"-\",\n \"GurantorAddress\": \"-\",\n \"GurantorVillage\": \"-\",\n \"GurantorOccupation\": \"-\",\n \"FromDate\": \"2/27/07 0:00\",\n \"ToDate\": \"5/8/07 0:00\",\n \"PaymentMode\": \"Weekly70\",\n \"LoanAmount\": 1000,\n \"InstallmentAmount\": 100,\n \"AmountPaid\": 0,\n \"BalanceAmount\": 1000,\n \"AverageAmount\": 14.29\n }\n]\n```\n\n### Collection JSON FILE\n\n```\n[\n {\n \"LineName\": \"ONE LINE\",\n \"RouteName\": 1,\n \"SerialNo\": 810,\n \"Collector\": \"ANR\",\n \"Date\": \"7/8/04 0:00\",\n \"Amount\": 20,\n \"Remark\": \"-\"\n },\n {\n \"LineName\": \"TWO LINE\",\n \"RouteName\": 81,\n \"SerialNo\": 256,\n \"Collector\": \"RAMESH\",\n \"Date\": \"8/31/04 0:00\",\n \"Amount\": 200,\n \"Remark\": \"-\"\n }\n]\n```\n\n========================================\n\nCode:\n```text\nimport { User } from \"./User\";\nimport {\n BaseEntity,\n Column,\n Entity,\n ManyToOne,\n OneToMany,\n PrimaryGeneratedColumn,\n} from \"typeorm\";\nimport { Loan } from \"./Loan\";\nimport { Village } from \"./Village\";\nimport { Penalty } from \"./Penalty\";\nimport { Transcation } from \"./Transcation\";\n\n@Entity()\nexport class Loanee extends BaseEntity {\n @PrimaryGeneratedColumn(\"uuid\")\n id: string;\n\n @ManyToOne(() => User, (user) => user.loanees)\n user: User;\n\n @OneToMany(() => Loan, (loan) => loan.loanee)\n loans: Loan[];\n\n @ManyToOne(() => Village, (village) => village.loanees)\n village: Village;\n\n @OneToMany(() => Penalty, (penalty) => penalty.loanee)\n penalties: Penalty[];\n\n @OneToMany(() => Transcation, (transcation) => transcation.fromLoanee)\n from: Transcation[];\n\n @OneToMany(() => Transcation, (transcation) => transcation.toLoanee)\n to: Transcation[];\n\n @Column()\n fullName: string;\n\n @Column({ nullable: true })\n profileImage: string;\n\n @Column()\n address: string;\n\n @Column({ default: \"0\" })\n phoneNumber: string;\n\n @Column()\n guarantorName: string;\n\n @Column()\n guarantorVillage: string;\n\n @Column()\n guarantorAddress: string;\n\n @Column({ default: \"0\" })\n guarantorPhoneNumber: string;\n\n @Column({ nullable: true })\n remark: string;\n\n @Column({ default: 0 })\n penaltyAmount: number;\n\n @Column({ unique: true, nullable: false })\n loaneeNumber: string;\n\n @Column({ type: \"timestamp\" })\n timestamp: Date;\n}\n```\n\n```text\nimport {\n BaseEntity,\n Column,\n Entity,\n ManyToOne,\n PrimaryGeneratedColumn,\n} from \"typeorm\";\nimport { Loan } from \"./Loan\";\nimport { Route } from \"./Route\";\nimport { User } from \"./User\";\n\n@Entity()\nexport class Collection extends BaseEntity {\n @PrimaryGeneratedColumn(\"uuid\")\n id: string;\n\n @ManyToOne(() => Loan, (loan) => loan.collections)\n loan: Loan;\n\n @ManyToOne(() => User, (user) => user.collections)\n user: User;\n\n @ManyToOne(() => Route, (route) => route.collections)\n route: Route;\n\n @Column()\n amount: number;\n\n @Column()\n dueAmount: number;\n\n @Column({ nullable: true })\n remark: string;\n\n @Column({ type: \"timestamp\" })\n timestamp: Date;\n}\n```\n\n```text\n[\n {\n \"SerialNo\": 178,\n \"LineName\": \"FOUR LINE\",\n \"RouteName\": \"FRIDAY WEEKLY 3 NOLIASAHI\",\n \"LoneeName\": \"POTTI BHAGABAN\",\n \"LoneeAddress\": \"S/O POTTI GORAMMA\",\n \"LoneeVillage\": \"BALI NOLIASAHI\",\n \"LoneeOccupation\": \"MUTCHILU\",\n \"GurantorName\": \"-\",\n \"GurantorAddress\": \"-\",\n \"GurantorVillage\": \"-\",\n \"GurantorOccupation\": \"-\",\n \"FromDate\": \"9/30/05 0:00\",\n \"ToDate\": \"12/9/05 0:00\",\n \"PaymentMode\": \"Weekly70\",\n \"LoanAmount\": 1500,\n \"InstallmentAmount\": 150,\n \"AmountPaid\": 0,\n \"BalanceAmount\": 1500,\n \"AverageAmount\": 21.43\n },\n {\n \"SerialNo\": 3119,\n \"LineName\": \"ONE LINE\",\n \"RouteName\": \"1 DAILY\",\n \"LoneeName\": \"KUNI DAS\",\n \"LoneeAddress\": \"W/O BHASKAR DAS\",\n \"LoneeVillage\": \"RATNA PUR--1ST.\",\n \"LoneeOccupation\": \"-\",\n \"GurantorName\": \"-\",\n \"GurantorAddress\": \"-\",\n \"GurantorVillage\": \"-\",\n \"GurantorOccupation\": \"-\",\n \"FromDate\": \"2/27/07 0:00\",\n \"ToDate\": \"5/8/07 0:00\",\n \"PaymentMode\": \"Weekly70\",\n \"LoanAmount\": 1000,\n \"InstallmentAmount\": 100,\n \"AmountPaid\": 0,\n \"BalanceAmount\": 1000,\n \"AverageAmount\": 14.29\n }\n]\n```\n\n```text\n[\n {\n \"LineName\": \"ONE LINE\",\n \"RouteName\": 1,\n \"SerialNo\": 810,\n \"Collector\": \"ANR\",\n \"Date\": \"7/8/04 0:00\",\n \"Amount\": 20,\n \"Remark\": \"-\"\n },\n {\n \"LineName\": \"TWO LINE\",\n \"RouteName\": 81,\n \"SerialNo\": 256,\n \"Collector\": \"RAMESH\",\n \"Date\": \"8/31/04 0:00\",\n \"Amount\": 200,\n \"Remark\": \"-\"\n }\n]\n```\n\n```text\nRouteName\n```\n\n```text\nSerialNo\n```\n\n```text\nimport { hash } from \"bcryptjs\";\nimport { Request, Response } from \"express\";\nimport \"reflect-metadata\";\nimport { createConnection, getConnection, getManager } from \"typeorm\";\nimport * as uuid from \"uuid\";\nimport { Collection } from \"../entity/Collection\";\nimport { Loan } from \"../entity/Loan\";\nimport { Loanee } from \"../entity/Loanee\";\nimport { Plan } from \"../entity/Plan\";\nimport { Role } from \"../entity/Role\";\nimport { Route } from \"../entity/Route\";\nimport { TranscationType } from \"../entity/TranscationType\";\nimport { User } from \"../entity/User\";\nimport { Village } from \"../entity/Village\";\nimport { RoleType } from \"../types/RoleType\";\nimport { TranscationInterface } from \"../types/TranscationInterface\";\nimport collection from \"./new-collection.json\";\nimport loanee from \"./new-loanee.json\";\nimport onlyCollectores from \"./onlyCollectors.json\";\nimport villageData from \"./tblCities.json\";\nimport RouteCityData from \"./tblRouteCities.json\";\nimport routeData from \"./tblRoutes.json\";\n\nexport const migrate = async (req: Request, res: Response) => {\n const from = req.query.from || 0;\n const to = req.query.to || 100000000000000;\n\n res.status(200).json({\n success: true,\n from,\n to,\n });\n\n await addRole();\n await addVillages();\n await addRoute();\n await addTranscationType();\n await addPlan();\n await addAdmin();\n await addCollectors();\n await addRouteVillage();\n await addNewLoaneeCollectionData(from, to);\n await callStoredProcedure();\n};\n\nexport const migrateOnlyLoaneAndCollections = async (\n req: Request,\n res: Response\n) => {\n const from = parseInt(req.query.from) || 0;\n const to = parseInt(req.query.to) || 100000000000000;\n\n res.status(200).json({\n success: true,\n from,\n to,\n });\n\n await addNewLoaneeCollectionData(from, to);\n await callStoredProcedure();\n};\n\nexport const deleteLoaneeRecords = async (req: Request, res: Response) => {\n const from = parseInt(req.query.from) || 0;\n const to = parseInt(req.query.to) || 100000000000000;\n\n res.status(200).json({\n success: true,\n from,\n to,\n });\n\n for (let i = from; i < to; i++) {\n await Loan.delete({ remark: `${i}_OLD_DATA` });\n await Loanee.delete({ remark: `${i}_OLD_DATA` });\n }\n};\n\nconst addRoute = async () => {\n //Dumping Routes Data to Server DB\n for (let i = 0; i < routeData.length; i++) {\n const item = routeData[i];\n\n await Route.create({\n name: item.RouteName,\n timestamp: new Date(),\n }).save();\n }\n};\n\nconst addVillages = async () => {\n // Dumping Villages Data to Server DB\n for (let i = 0; i < villageData.length; i++) {\n const item = villageData[i];\n\n await Village.create({\n name: item.CityName,\n timestamp: new Date(),\n }).save();\n }\n};\n\nconst addRole = async () => {\n await Role.create({\n name: RoleType.admin,\n timestamp: new Date(),\n }).save();\n await Role.create({\n name: RoleType.collector,\n timestamp: new Date(),\n }).save();\n};\n\nconst addAdmin = async () => {\n const AdminRole = await Role.findOne({ where: { name: RoleType.admin } });\n const user = new User();\n user.role = AdminRole!;\n user.userName = \"admin\";\n user.fullName = \"admin\";\n user.password = await hash(\"admin@123\", 12);\n user.balance = 1000000000;\n user.timestamp = new Date();\n await user.save();\n\n const collectorRole = await Role.findOne({\n where: { name: RoleType.collector },\n });\n\n const defaultUser = new User();\n defaultUser.role = collectorRole!;\n defaultUser.userName = \"SYSTEM_GENERATED_COLLECTOR\";\n defaultUser.fullName = \"SYSTEM_GENERATED_COLLECTOR\";\n defaultUser.password = await hash(\"1234567890\", 12);\n defaultUser.balance = 1000000000;\n defaultUser.timestamp = new Date();\n await defaultUser.save();\n\n const defaultRoute = new Route();\n defaultRoute.name = \"SYSTEM_GENERATED_ROUTE\";\n defaultRoute.timestamp = new Date();\n await defaultRoute.save();\n\n const defaultVillage = new Village();\n defaultVillage.name = \"SYSTEM_GENERATED_VILLAGE\";\n defaultVillage.timestamp = new Date();\n await defaultVillage.save();\n};\n\nconst addCollectors = async () => {\n const CollectorRole = await Role.findOne({\n where: { name: RoleType.collector },\n });\n\n if (!CollectorRole) {\n return;\n }\n const password = await hash(\"123456\", 12);\n for (let i = 0; i < onlyCollectores.length; i++) {\n const collector = onlyCollectores[i];\n const newCollector = new User();\n newCollector.role = CollectorRole;\n newCollector.userName = collector.Username.split(\" \").join(\"_\");\n newCollector.fullName = collector.FullName;\n newCollector.password = password;\n newCollector.timestamp = new Date();\n newCollector.last_updated = new Date();\n await newCollector.save();\n }\n};\n\nconst addTranscationType = async () => {\n const t1 = new TranscationType();\n t1.name = TranscationInterface.cash_collection;\n t1.timestamp = new Date();\n await t1.save();\n\n const t2 = new TranscationType();\n t2.name = TranscationInterface.cash_collector;\n t2.timestamp = new Date();\n await t2.save();\n\n const t3 = new TranscationType();\n t3.name = TranscationInterface.cash_loan;\n t3.timestamp = new Date();\n await t3.save();\n\n const t4 = new TranscationType();\n t4.name = TranscationInterface.cash_office;\n t4.timestamp = new Date();\n await t4.save();\n\n const t6 = new TranscationType();\n t6.name = TranscationInterface.penalty_collected;\n t6.timestamp = new Date();\n await t6.save();\n};\n\nconst addPlan = async () => {\n const p1 = new Plan();\n p1.name = \"Daily\";\n p1.duration = 1;\n p1.timestamp = new Date();\n await p1.save();\n\n const p2 = new Plan();\n p2.name = \"Weekly\";\n p2.duration = 7;\n p2.timestamp = new Date();\n await p2.save();\n\n const p3 = new Plan();\n p3.name = \"Monthly\";\n p3.duration = 30;\n p3.timestamp = new Date();\n await p3.save();\n\n const p4 = new Plan();\n p4.name = \"Fortnight\";\n p4.duration = 15;\n p4.timestamp = new Date();\n await p4.save();\n};\n\nconst addRouteVillage = async () => {\n const AllVillage = await Village.find();\n const AllRoute = await Route.find();\n\n for (let i = 0; i < RouteCityData.length; i++) {\n const item = RouteCityData[i];\n\n const village = AllVillage.find((item2) => item2.id === item.CityId);\n const route = AllRoute.find((item2) => item2.id === item.RouteId);\n\n try {\n if (village && route) {\n await getConnection()\n .createQueryBuilder()\n .relation(Route, \"villages\")\n .of(route)\n .add(village);\n }\n } catch (error) {\n console.log(error.message);\n }\n }\n};\n\nconst addNewLoaneeCollectionData = async (from, to) => {\n const allData: any = [];\n const loaneeData = loanee as any[];\n const collectionData = collection as any[];\n\n const defaultUser = await User.findOne({\n where: { userName: \"SYSTEM_GENERATED_COLLECTOR\" },\n });\n const defaultRoute = await Route.findOne({\n where: { name: \"SYSTEM_GENERATED_ROUTE\" },\n });\n\n const defaultVillage = await Village.findOne({\n where: { name: \"SYSTEM_GENERATED_VILLAGE\" },\n });\n\n const WeeklyPlan = await Plan.findOne({\n where: { name: \"Weekly\" },\n });\n const DailyPlan = await Plan.findOne({\n where: { name: \"Daily\" },\n });\n const MonthlyPlan = await Plan.findOne({\n where: { name: \"Monthly\" },\n });\n const FortnightPlan = await Plan.findOne({\n where: { name: \"Fortnight\" },\n });\n\n // const transcationTypeLoan = await TranscationType.findOne({\n // where: { name: TranscationInterface.cash_loan },\n // });\n\n // const transcationTypeCollection = await TranscationType.findOne({\n // where: { name: TranscationInterface.cash_collection },\n // });\n console.log(collectionData.length);\n\n loaneeData.forEach((item: any, index) => {\n if (index >= from && index <= to) {\n const block = {\n ...item,\n dataIndex: index,\n };\n block.collection = [];\n\n collectionData.forEach((item2: any) => {\n if (\n item.SerialNo === item2.SerialNo &&\n item.RouteName === item2.RouteName\n ) {\n block.collection.push(item2);\n }\n });\n\n allData.push(block);\n }\n });\n\n var count = 0;\n allData.forEach((item: any) => {\n count += item.collection.length;\n });\n console.log(allData.length);\n console.log(\"Total Count : \" + count);\n\n const AllVillage = await Village.find();\n const AllCollector = await User.find();\n const AllRoute = await Route.find();\n\n for (let i = 0; i < allData.length; i++) {\n const item = allData[i];\n\n let roundedNum = 0;\n if (item.LoanAmount === 0 || item.InstallmentAmount === 0) {\n roundedNum = 0;\n } else {\n roundedNum = Number(\n (Number(item.LoanAmount) / Number(item.InstallmentAmount)).toFixed()\n );\n }\n const village = AllVillage.find(\n (item2) => item2.name.toLowerCase() === item.LoneeVillage.toLowerCase()\n );\n\n const routeColl = AllRoute.find(\n (route2) => route2.name.toLowerCase() === item.RouteName.toLowerCase()\n );\n\n let plan = null;\n\n if (item.PaymentMode.includes(\"Weekly\")) {\n plan = WeeklyPlan;\n } else if (item.PaymentMode.includes(\"Daily\")) {\n plan = DailyPlan;\n } else if (item.PaymentMode.includes(\"Monthly\")) {\n plan = MonthlyPlan;\n } else if (item.PaymentMode.includes(\"Fortnight\")) {\n plan = FortnightPlan;\n } else {\n plan = WeeklyPlan;\n }\n\n const loanee = new Loanee();\n\n loanee.id = uuid.v4();\n loanee.user = defaultUser!;\n loanee.village = village ? village : defaultVillage!;\n loanee.route = routeColl ? routeColl : defaultRoute!;\n loanee.fullName = `${item.LoneeName}_${item.dataIndex}`;\n loanee.address = item.LoneeAddress;\n loanee.guarantorName = item.GurantorName;\n loanee.guarantorVillage = item.GurantorVillage;\n loanee.guarantorAddress = item.GurantorAddress;\n loanee.loaneeNumber = `${item.SerialNo}`;\n loanee.remark = `${item.dataIndex}_OLD_DATA`;\n loanee.timestamp = new Date(item.FromDate);\n\n await loanee.save();\n\n const loan = new Loan();\n loan.id = uuid.v4();\n loan.loanee = loanee;\n loan.user = defaultUser!;\n loan.plan = plan!;\n loan.village = village ? village : defaultVillage!;\n loan.route = routeColl ? routeColl : defaultRoute!;\n loan.loanNumber = `${item.SerialNo}`;\n loan.createdAt = new Date(item.FromDate);\n loan.startAt = new Date(item.FromDate);\n loan.endAt = new Date(item.ToDate);\n loan.amount = item.LoanAmount.toFixed();\n loan.dueAmount = item.BalanceAmount.toFixed();\n loan.recoveryMoney = item.LoanAmount.toFixed();\n loan.installment = item.InstallmentAmount.toFixed();\n loan.numberOfInstallments = roundedNum;\n loan.remark = `${item.dataIndex}_OLD_DATA`;\n loan.timestamp = new Date(item.FromDate);\n\n await loan.save();\n\n const collArr = [];\n for (let j = 0; j < item.collection.length; j++) {\n const item2 = item.collection[j];\n\n const userCollector = AllCollector.find(\n (user1) =>\n user1.userName.toLowerCase() === item2.Collector.toLowerCase()\n );\n\n collArr.push({\n id: uuid.v4(),\n loan: loan,\n user: userCollector ? userCollector : defaultUser!,\n route: routeColl ? routeColl : defaultRoute!,\n amount: item2.Amount.toFixed(),\n dueAmount: 0,\n remark: `${item.dataIndex}_OLD_DATA`,\n timestamp: new Date(item2.Date),\n });\n }\n\n await getConnection()\n .createQueryBuilder()\n .insert()\n .into(Collection)\n .values(collArr)\n .execute();\n }\n};\n\nconst callStoredProcedure = async () => {\n await getManager().query(`\n UPDATE loan l\n\n INNER JOIN (\n SELECT loanId, SUM(amount) as total\n FROM collection\n GROUP BY loanId\n ) c ON l.id = c.loanId\n\n SET l.dueAmount = (l.recoveryMoney - c.total); \n `);\n\n await getManager().query(`\n UPDATE loan SET isActive = false WHERE dueAmount <= 0;\n `);\n\n await getManager().query(`\n UPDATE route r\n\n INNER JOIN (\n SELECT MAX(loaneeNumber) as maxNumber, routeId\n FROM loanee\n GROUP BY routeId\n ) l ON l.routeId = r.id\n \n SET r.loaneeCount = l.maxNumber;\n `);\n\n await getManager().query(`\n UPDATE route r\n\n INNER JOIN (\n SELECT MAX(loanNumber) as maxNumber, routeId\n FROM loan\n GROUP BY routeId\n ) l ON l.routeId = r.id\n\n SET r.loanCount = l.maxNumber;\n `);\n};\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.719Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":859,"estimatedTokens":5050}}474{"id":"stack-57211909","source":"stackoverflow","questionId":57211909,"title":"Transactions with NestJS and TypeORM - decorators and unit tesing","tags":["transactions","nestjs","typeorm"],"text":"Title: Transactions with NestJS and TypeORM - decorators and unit tesing\nTags: transactions, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nMy Question is around transaction management using nestjs and Typeorm, my db is postgres.\n\nShould I use decorators like @Transaction and @TransactionManager while doing transaction management. I heard that they are going to be removed in new releases.\nhttps://github.com/typeorm/typeorm/issues/3251\n\nAs a best practise how do we handle a transaction that is inserting or updating multiple tables. I see the following question\nnestjs / TypeOrm database transaction\nIs this the right away, can somebody give me a full example. Should I inject connection to my service class and get EntityManager from it and pass it around?\n\nWhat would be the right way for unit testing such an insert on two tables.\n\nI am right now using Transaction decorators from TypeOrm.\nAll my create code is in a single class, I want to be able to move the code for creation of every entity to be moved to the entity's own service class and expect the transaction rollback still works.\n\n```\n@Transaction({ isolation: \"SERIALIZABLE\" })\n async createProfile(createProfileDTO: CreateProfileDTO, @TransactionManager() manager?: EntityManager){\n...\nconst profileRepository = manager.getRepository(Profile);\nlet savedProfile = await profileRepository.save(profile);\n\nidentifier.profile = savedProfile;\n const identifierRepository = manager.getRepository(Identifier);\n let savedIdentifier = identifierRepository.save(identifier);\n\n}\n```\n\nAlternatively, if I use\n\n```\nawait this.connection.transaction(async transactionalEntityManager => {\n profile = await this.createUserProfile(createProfileDTO, transactionalEntityManager);\n identifiers = await this.identifierService.createIdentifier(profile, createProfileDTO\n , transactionalEntityManager);\n});\n```\n\nWhat is the best way to unit test the above code?\n\n========================================\n\nCode:\n```text\n@Transaction({ isolation: \"SERIALIZABLE\" })\n async createProfile(createProfileDTO: CreateProfileDTO, @TransactionManager() manager?: EntityManager){\n...\nconst profileRepository = manager.getRepository(Profile);\nlet savedProfile = await profileRepository.save<Profile>(profile);\n\nidentifier.profile = savedProfile;\n const identifierRepository = manager.getRepository(Identifier);\n let savedIdentifier = identifierRepository.save(identifier);\n\n}\n```\n\n```text\nawait this.connection.transaction(async transactionalEntityManager => {\n profile = await this.createUserProfile(createProfileDTO, transactionalEntityManager);\n identifiers = await this.identifierService.createIdentifier(profile, createProfileDTO\n , transactionalEntityManager);\n});\n```\n\n```text\n@InjectConnection()\nprivate readonly connection: Connection)\n```\n\n```text\nawait this.connection.transaction(async transactionalEntityManager => {\n try {\n urDTOCreated = await this.myService1.createSomething(urDTO, transactionalEntityManager);\n typeDTOCreated = await this.myService2.createSomethingElse(obj1, obj2, transactionalEntityManager);\n }\n catch (ex) {\n Logger.log(ex);\n throw new InternalServerErrorException(\"Error saving data to database\");\n }\n```\n\n========================================\n\nComments:\n- Having to pass the transactionalEntityManager to every function used is kind of a pain. I'm going to research alternative solutions but has anyone else resolved this before I keep digging in.\n- @Ray did you find a better option?\n- @Ray did you find a better option bro???","metadata":{"transformedAt":"2026-08-18T18:33:44.719Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":93,"estimatedTokens":921}}475{"id":"stack-72743126","source":"stackoverflow","questionId":72743126,"title":"How to get ZodError in json","tags":["javascript","typescript","validation","typeorm","zod"],"text":"Title: How to get ZodError in json\nTags: javascript, typescript, validation, typeorm, zod\nSource: Stack Overflow\n\nQuestion:\nI'm trying to get zod validation errors in json when i test it in insomnia, but am getting it only in terminal and in insomnia it's telling me Error: Couldn't connect to server\ni saw some examples and everywhere it's worked... don't understand why it's not working...\n\nmy register method\n\n```\nexport const register = async (req: Request, res: Response) => {\n const payloadSchema = z\n .object({\n firstname: z.string({\n required_error: \"Firstname is required\",\n invalid_type_error: \"Title must be a string\",\n }),\n lastname: z.string({\n required_error: \"Lastname is required\",\n invalid_type_error: \"Title must be a string\",\n }),\n email: z\n .string({ required_error: \"Email is required\" })\n .email({ message: \"Invalid email address\" }),\n password: z.string(),\n confirm: z.string(),\n })\n .refine((data) => data.password === data.confirm, {\n message: \"Passwords don't match\",\n path: [\"confirm\"], \n });\n\n const parsedData = await payloadSchema.parseAsync(req.body);\n\n try {\n const result = await User.findOne({ where: { email: parsedData.email } });\n\n if (result) {\n return res.status(400).json({\n success: false,\n error: \"User already exists\",\n });\n }\n\n const user = new User();\n user.firstname = parsedData.firstname;\n user.lastname = parsedData.lastname;\n user.email = parsedData.email;\n user.password = parsedData.password;\n await user.save();\n\n const accessToken = jwt.sign(\n { userId: user.id },\n process!.env!.TOKEN_SECRET!\n );\n\n return res.status(200).json({\n success: true,\n createdUser: user,\n accessToken: accessToken,\n });\n } catch (e) {\n if (e instanceof ZodError) {\n return res.status(400).json({\n success: false,\n error: e.flatten(),\n });\n } else if (e instanceof Error) {\n return res.status(400).json({\n message: e.message,\n });\n }\n }\n};\n```\n\nso what's am doing wrong, and how can i fix it? thanks for attention.\n\n========================================\n\nCode:\n```text\nexport const register = async (req: Request, res: Response) => {\n const payloadSchema = z\n .object({\n firstname: z.string({\n required_error: \"Firstname is required\",\n invalid_type_error: \"Title must be a string\",\n }),\n lastname: z.string({\n required_error: \"Lastname is required\",\n invalid_type_error: \"Title must be a string\",\n }),\n email: z\n .string({ required_error: \"Email is required\" })\n .email({ message: \"Invalid email address\" }),\n password: z.string(),\n confirm: z.string(),\n })\n .refine((data) => data.password === data.confirm, {\n message: \"Passwords don't match\",\n path: [\"confirm\"], \n });\n\n const parsedData = await payloadSchema.parseAsync(req.body);\n\n try {\n const result = await User.findOne({ where: { email: parsedData.email } });\n\n if (result) {\n return res.status(400).json({\n success: false,\n error: \"User already exists\",\n });\n }\n\n const user = new User();\n user.firstname = parsedData.firstname;\n user.lastname = parsedData.lastname;\n user.email = parsedData.email;\n user.password = parsedData.password;\n await user.save();\n\n const accessToken = jwt.sign(\n { userId: user.id },\n process!.env!.TOKEN_SECRET!\n );\n\n return res.status(200).json({\n success: true,\n createdUser: user,\n accessToken: accessToken,\n });\n } catch (e) {\n if (e instanceof ZodError) {\n return res.status(400).json({\n success: false,\n error: e.flatten(),\n });\n } else if (e instanceof Error) {\n return res.status(400).json({\n message: e.message,\n });\n }\n }\n};\n```\n\n```text\nconst parsedData = await payloadSchema.parseAsync(req.body);\n```\n\n```text\ntry {\n const parsedData = await payloadSchema.parseAsync(req.body);\n \n const result = await User.findOne({ where: { email: parsedData.email } });\n\n ...\n```\n\n```text\nparseAsync\n```","metadata":{"transformedAt":"2026-08-18T18:33:44.719Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":4,"totalLines":165,"estimatedTokens":992}}476{"id":"stack-61297622","source":"stackoverflow","questionId":61297622,"title":"TypeScript metadata reflection references other classes before they are defined","tags":["typescript","webpack","next.js","typeorm"],"text":"Title: TypeScript metadata reflection references other classes before they are defined\nTags: typescript, webpack, next.js, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have some TypeORM entities in my codebase which have relations to each other, making a circular dependency. Since decorator metadata is used on each entity class, TypeScript inserts code after each class defining metadata on it. Say that the classes are `Business` and `Qualification`. On the relating fields TypeScript will emit code that looks like this:\n\n```\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c = 0; i--) if (d = decorators[i]) r = (c 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nconst decorator = (target, thing) => {\n};\nclass Business {\n}\nclass Qualification {\n}\n__decorate([\n decorator,\n __metadata(\"design:type\", Business)\n], Qualification.prototype, \"business\", void 0);\n```\n\nThis would all be fine, except the `__decorate` part always comes after each class, meaning that one of the classes is going to have to be used before it's defined, which causes an error. Here's a shortened version of the actual code with the actual error:\n\n```\nlet Qualification = (_dec = Object(external_typeorm_[\"Entity\"])(), _dec2 = Object(external_typeorm_[\"PrimaryGeneratedColumn\"])(), _dec3 = Reflect.metadata(\"design:type\", Number), _dec4 = Object(external_typeorm_[\"Column\"])({\n nullable: true\n}), _dec5 = Object(external_class_validator_[\"IsOptional\"])(), _dec6 = Object(external_class_validator_[\"IsUrl\"])(), _dec7 = Reflect.metadata(\"design:type\", String), _dec8 = Object(external_typeorm_[\"ManyToOne\"])(type => Business[\"c\" /* default */], business => business.qualifications, {\n onDelete: 'CASCADE'\n}), _dec9 = Reflect.metadata(\"design:type\", typeof Business[\"c\" /* default */] === \"undefined\" ?\n\n // ^ TypeError: cannot read property \"c\" of undefined\n\n Object : Business[\"c\" /* default */]), _dec10 = Object(external_typeorm_[\"Column\"])({\n type: 'enum',\n enum: VALIDITY_STATES,\n default: 'invalid'\n}), _dec11 = Object(external_class_validator_[\"IsIn\"])(VALIDITY_STATES), _dec12 = Reflect.metadata(\"design:type\", Object), _dec13 = Object(external_typeorm_[\"Column\"])('simple-json'), _dec14 = Object(external_class_validator_[\"ValidateNested\"])(), _dec15 = Object(external_class_validator_[\"IsArray\"])(), _dec16 = Object(external_class_validator_[\"IsIn\"])(category[\"a\" /* CATEGORIES */].filter(c => c.type === 'service').map(c => c.slug), {\n each: true\n}), _dec17 = Reflect.metadata(\"design:type\", Array), _dec(_class = (_class2 = (_temp = class Qualification {\n constructor() {\n _initializerDefineProperty(this, \"id\", _descriptor, this);\n\n _initializerDefineProperty(this, \"imageUrl\", _descriptor2, this);\n\n _initializerDefineProperty(this, \"business\", _descriptor3, this);\n\n _initializerDefineProperty(this, \"validity\", _descriptor4, this);\n\n _initializerDefineProperty(this, \"categories\", _descriptor5, this);\n }\n\n}, _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, \"id\", [_dec2, _dec3], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, \"imageUrl\", [_dec4, _dec5, _dec6, _dec7], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, \"business\", [_dec8, _dec9], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, \"validity\", [_dec10, _dec11, _dec12], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor5 = _applyDecoratedDescriptor(_class2.prototype, \"categories\", [_dec13, _dec14, _dec15, _dec16, _dec17], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n})), _class2)) || _class);\n```\n\nLater in the code, `Business` is defined, but it's too late:\n\n```\nlet Business = (_dec6 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Entity\"])(), _dec7 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])(), _dec8 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsString\"])(), _dec9 = Reflect.metadata(\"design:type\", String), _dec10 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])({\n type: 'enum',\n enum: BUSINESS_TYPES\n}), _dec11 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsIn\"])(BUSINESS_TYPES), _dec12 = Reflect.metadata(\"design:type\", Object), _dec13 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])(), _dec14 = Reflect.metadata(\"design:type\", Boolean), _dec15 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"CreateDateColumn\"])(), _dec16 = Reflect.metadata(\"design:type\", typeof Date === \"undefined\" ? Object : Date), _dec17 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])({\n nullable: true\n}), _dec18 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsOptional\"])(), _dec19 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsUrl\"])(), _dec20 = Reflect.metadata(\"design:type\", String), _dec21 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])({\n nullable: true\n}), _dec22 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsOptional\"])(), _dec23 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsString\"])(), _dec24 = Reflect.metadata(\"design:type\", String), _dec25 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])({\n nullable: true\n}), _dec26 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsOptional\"])(), _dec27 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsString\"])(), _dec28 = Reflect.metadata(\"design:type\", String), _dec29 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])(), _dec30 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsString\"])(), _dec31 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"MaxLength\"])(200), _dec32 = Reflect.metadata(\"design:type\", String), _dec33 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"OneToMany\"])(type => _db_all_entities__WEBPACK_IMPORTED_MODULE_3__[/* Qualification */ \"i\"], qualification => qualification.business, {\n cascade: true\n}), _dec34 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"ValidateNested\"])(), _dec35 = Reflect.metadata(\"design:type\", Array), _dec36 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])('simple-json'), _dec37 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsArray\"])(), _dec38 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"ValidateNested\"])(), _dec39 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsIn\"])(_misc_types_category__WEBPACK_IMPORTED_MODULE_2__[/* CATEGORIES */ \"a\"].filter(c => c.type === 'business').map(c => c.slug), {\n each: true\n}), _dec40 = Reflect.metadata(\"design:type\", Array), _dec41 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])('simple-json'), _dec42 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsArray\"])(), _dec43 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"ValidateNested\"])(), _dec44 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"ArrayMinSize\"])(1), _dec45 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"ArrayMaxSize\"])(5), _dec46 = Reflect.metadata(\"design:type\", Array), _dec47 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])({\n type: 'enum',\n enum: PRICING_PLANS\n}), _dec48 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsIn\"])(PRICING_PLANS), _dec49 = Reflect.metadata(\"design:type\", String), _dec50 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"OneToMany\"])(type => _db_all_entities__WEBPACK_IMPORTED_MODULE_3__[/* BaseOffer */ \"b\"], offer => offer.offerer), _dec51 = Reflect.metadata(\"design:type\", Array), _dec6(_class3 = (_class4 = (_temp2 = class Business extends _db_all_entities__WEBPACK_IMPORTED_MODULE_3__[/* Account */ \"a\"] {\n constructor(...args) {\n super(...args);\n\n _initializerDefineProperty(this, \"name\", _descriptor3, this);\n\n _initializerDefineProperty(this, \"type\", _descriptor4, this);\n\n _initializerDefineProperty(this, \"isApproved\", _descriptor5, this);\n\n _initializerDefineProperty(this, \"since\", _descriptor6, this);\n\n _initializerDefineProperty(this, \"logoUrl\", _descriptor7, this);\n\n _initializerDefineProperty(this, \"fein\", _descriptor8, this);\n\n _initializerDefineProperty(this, \"phoneNumber\", _descriptor9, this);\n\n _initializerDefineProperty(this, \"bio\", _descriptor10, this);\n\n _initializerDefineProperty(this, \"qualifications\", _descriptor11, this);\n\n _initializerDefineProperty(this, \"businessCategories\", _descriptor12, this);\n\n _initializerDefineProperty(this, \"geolocations\", _descriptor13, this);\n\n _initializerDefineProperty(this, \"pricingPlan\", _descriptor14, this);\n\n _initializerDefineProperty(this, \"offers\", _descriptor15, this);\n }\n\n}, _temp2), (_descriptor3 = _applyDecoratedDescriptor(_class4.prototype, \"name\", [_dec7, _dec8, _dec9], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor4 = _applyDecoratedDescriptor(_class4.prototype, \"type\", [_dec10, _dec11, _dec12], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor5 = _applyDecoratedDescriptor(_class4.prototype, \"isApproved\", [_dec13, _dec14], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor6 = _applyDecoratedDescriptor(_class4.prototype, \"since\", [_dec15, _dec16], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor7 = _applyDecoratedDescriptor(_class4.prototype, \"logoUrl\", [_dec17, _dec18, _dec19, _dec20], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor8 = _applyDecoratedDescriptor(_class4.prototype, \"fein\", [_dec21, _dec22, _dec23, _dec24], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor9 = _applyDecoratedDescriptor(_class4.prototype, \"phoneNumber\", [_dec25, _dec26, _dec27, _dec28], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor10 = _applyDecoratedDescriptor(_class4.prototype, \"bio\", [_dec29, _dec30, _dec31, _dec32], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor11 = _applyDecoratedDescriptor(_class4.prototype, \"qualifications\", [_dec33, _dec34, _dec35], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor12 = _applyDecoratedDescriptor(_class4.prototype, \"businessCategories\", [_dec36, _dec37, _dec38, _dec39, _dec40], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor13 = _applyDecoratedDescriptor(_class4.prototype, \"geolocations\", [_dec41, _dec42, _dec43, _dec44, _dec45, _dec46], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor14 = _applyDecoratedDescriptor(_class4.prototype, \"pricingPlan\", [_dec47, _dec48, _dec49], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor15 = _applyDecoratedDescriptor(_class4.prototype, \"offers\", [_dec50, _dec51], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n})), _class4)) || _class3);\n```\n\nStrangely, the code works when compiled for development mode because `Business` is not referred to directly but rather through a module constant. Here's how `Qualification` is defined in development mode:\n\n```\nlet Qualification = (_dec = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Entity\"])(), _dec2 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"PrimaryGeneratedColumn\"])(), _dec3 = Reflect.metadata(\"design:type\", Number), _dec4 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])({\n nullable: true\n}), _dec5 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsOptional\"])(), _dec6 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsUrl\"])(), _dec7 = Reflect.metadata(\"design:type\", String), _dec8 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"ManyToOne\"])(type => _db_all_entities__WEBPACK_IMPORTED_MODULE_2__[\"Business\"], business => business.qualifications, {\n onDelete: 'CASCADE'\n}), _dec9 = Reflect.metadata(\"design:type\", typeof _db_all_entities__WEBPACK_IMPORTED_MODULE_2__[\"Business\"] === \"undefined\" ? Object : _db_all_entities__WEBPACK_IMPORTED_MODULE_2__[\"Business\"]), _dec10 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])({\n type: 'enum',\n enum: VALIDITY_STATES,\n default: 'invalid'\n}), _dec11 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsIn\"])(VALIDITY_STATES), _dec12 = Reflect.metadata(\"design:type\", Object), _dec13 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])('simple-json'), _dec14 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"ValidateNested\"])(), _dec15 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsArray\"])(), _dec16 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsIn\"])(_misc_types_category__WEBPACK_IMPORTED_MODULE_5__[\"CATEGORIES\"].filter(c => c.type === 'service').map(c => c.slug), {\n each: true\n}), _dec17 = Reflect.metadata(\"design:type\", Array), _dec(_class = (_class2 = (_temp = class Qualification {\n constructor() {\n _initializerDefineProperty(this, \"id\", _descriptor, this);\n\n _initializerDefineProperty(this, \"imageUrl\", _descriptor2, this);\n\n _initializerDefineProperty(this, \"business\", _descriptor3, this);\n\n _initializerDefineProperty(this, \"validity\", _descriptor4, this);\n\n _initializerDefineProperty(this, \"categories\", _descriptor5, this);\n }\n\n}, _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, \"id\", [_dec2, _dec3], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, \"imageUrl\", [_dec4, _dec5, _dec6, _dec7], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, \"business\", [_dec8, _dec9], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, \"validity\", [_dec10, _dec11, _dec12], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor5 = _applyDecoratedDescriptor(_class2.prototype, \"categories\", [_dec13, _dec14, _dec15, _dec16, _dec17], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n})), _class2)) || _class);\n```\n\nThe actual code itself imports modules from an `all-entities.ts` file, which exports all the entities in the correct order so that superclasses don't accidentally get loaded after their subclasses, causing errors. That file looks like this (simplified):\n\n```\nexport { default as Qualification } from '../entities/Qualification';\nexport { default as Business } from '../entities/Business';\n```\n\n`./entities/Qualification.ts` and `./entities/Business.ts` are both files that contain a default export of a TypeORM entity, and I don't feel like they're worth including here but I can if anyone wants to look at them. Here's the difference between my production and development webpack configs (generated by Next.js):\n\n```\ndiff --git a/webpack-config-dev.txt b/webpack-config-prod.txt\nindex f8a28c3..8e5fa4d 100644\n--- a/webpack-config-dev.txt\n+++ b/webpack-config-prod.txt\n@@ -1,80 +1,82 @@\n {\n externals: [ [Function] ],\n optimization: {\n checkWasmTypes: false,\n nodeEnv: false,\n splitChunks: false,\n runtimeChunk: undefined,\n minimize: false,\n minimizer: [ [TerserPlugin], [CssMinimizerPlugin] ]\n },\n context: 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society',\n node: { setImmediate: false },\n entry: [AsyncFunction: entry],\n output: {\n path: 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\.next\\\\server',\n filename: [Function: filename],\n libraryTarget: 'commonjs2',\n hotUpdateChunkFilename: 'static/webpack/[id].[hash].hot-update.js',\n hotUpdateMainFilename: 'static/webpack/[hash].hot-update.json',\n- chunkFilename: '[name].js',\n+ chunkFilename: '[name].[contenthash].js',\n strictModuleExceptionHandling: true,\n crossOriginLoading: undefined,\n- futureEmitAssets: false,\n+ futureEmitAssets: true,\n webassemblyModuleFilename: 'static/wasm/[modulehash].wasm'\n },\n performance: false,\n resolve: {\n extensions: [\n '.tsx', '.ts',\n '.js', '.mjs',\n '.jsx', '.json',\n '.wasm'\n ],\n modules: [ 'node_modules' ],\n alias: {\n 'next/head': 'next/dist/next-server/lib/head.js',\n 'next/router': 'next/dist/client/router.js',\n 'next/config': 'next/dist/next-server/lib/runtime-config.js',\n 'next/dynamic': 'next/dist/next-server/lib/dynamic.js',\n next: 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next',\n 'private-next-pages': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\src\\\\pages',\n 'private-dot-next': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\.next'\n },\n mainFields: [ 'main', 'module' ],\n plugins: [ [Object] ]\n },\n resolveLoader: {\n alias: {\n 'emit-file-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\emit-file-loader',\n 'error-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\error-loader',\n 'next-babel-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\next-babel-loader',\n 'next-client-pages-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\next-client-pages-loader',\n 'next-data-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\next-data-loader',\n 'next-serverless-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\next-serverless-loader',\n 'noop-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\noop-loader',\n 'next-plugin-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\next-plugin-loader'\n },\n modules: [ 'node_modules' ],\n plugins: [ [Object] ]\n },\n module: {\n rules: [ [Object], [Object], [Object] ],\n strictExportPresence: true\n },\n plugins: [\n ChunkNamesPlugin {},\n DefinePlugin { definitions: [Object] },\n- UnlinkRemovedPagesPlugin { prevAssets: {} },\n- NoEmitOnErrorsPlugin {},\n- NextJsRequireCacheHotReloader { prevAssets: null },\n+ HashedModuleIdsPlugin { options: [Object] },\n+ IgnorePlugin {\n+ options: [Object],\n+ checkIgnore: [Function: bound checkIgnore]\n+ },\n PagesManifestPlugin { serverless: false },\n NextJsSsrImportPlugin { options: [Object] },\n NextJsSsrImportPlugin {},\n FilterWarningsPlugin { exclude: [Array] }\n ],\n- mode: 'development',\n+ mode: 'production',\n name: 'server',\n target: 'node',\n- devtool: 'cheap-module-source-map'\n+ devtool: false\n }\n```\n\nHere are the classes that are causing the problem:\nBusiness.ts:\n\n```\nimport {\n ArrayMaxSize,\n ArrayMinSize,\n IsArray,\n IsIn,\n IsOptional,\n IsString,\n IsUrl,\n MaxLength,\n ValidateNested,\n IsEmail\n} from 'class-validator';\nimport { Column, CreateDateColumn, Entity, OneToMany } from 'typeorm';\nimport { CATEGORIES } from '../../misc-types/category';\nimport { Geolocation } from '../../misc-types/geolocation';\nimport { Account, BaseOffer, Qualification, ValidateableQualification } from '../db/all-entities';\nimport { omit } from './utils/entity-type-manipulations';\nimport tuple from './utils/string-enum-from-tuple';\n\nconst BUSINESS_TYPES = tuple('individual', 'company');\nconst PRICING_PLANS = tuple('free');\n\n@Entity()\nexport default class Business extends Account {\n /**\n * Public name for the business.\n */\n @Column()\n @IsString()\n name!: string;\n\n @Column({ type: 'enum', enum: BUSINESS_TYPES })\n @IsIn(BUSINESS_TYPES)\n type!: typeof BUSINESS_TYPES[number];\n\n @Column()\n isApproved!: boolean;\n\n /**\n * The date the business created their account (not when it was approved)\n */\n @CreateDateColumn()\n since!: Date;\n\n @Column({ nullable: true })\n @IsOptional()\n @IsUrl()\n logoUrl?: string;\n\n @Column({ nullable: true })\n @IsOptional()\n @IsString()\n fein?: string;\n\n @Column({ nullable: true })\n @IsOptional()\n @IsString()\n phoneNumber?: string;\n\n @Column()\n @IsString()\n @MaxLength(200)\n bio!: string;\n\n @OneToMany(\n type => Qualification,\n qualification => qualification.business,\n { cascade: true }\n )\n @ValidateNested()\n qualifications!: Qualification[];\n\n @Column('simple-json')\n @IsArray()\n @ValidateNested()\n @IsIn(\n CATEGORIES.filter(c => c.type === 'business').map(c => c.slug),\n { each: true }\n )\n businessCategories!: string[];\n\n /**\n * Places this business is available at\n */\n @Column('simple-json')\n @IsArray()\n @ValidateNested()\n @ArrayMinSize(1)\n @ArrayMaxSize(5)\n geolocations!: Geolocation[];\n\n @Column({ type: 'enum', enum: PRICING_PLANS })\n @IsIn(PRICING_PLANS)\n pricingPlan!: 'free';\n\n @OneToMany(\n type => BaseOffer,\n offer => offer.offerer\n )\n offers!: BaseOffer[];\n}\n\n/**\n * A DTO sent to change business properties, most of which align one-to-one (excluding password/passwordHash).\n */\nexport class EditableBusiness extends omit(Business, [\n 'id',\n 'since',\n 'isApproved',\n 'qualifications',\n 'passwordHash',\n 'offers'\n]) {\n @IsString()\n password!: string;\n}\n\nexport class BusinessApplication extends EditableBusiness {\n @ValidateNested()\n @IsOptional()\n initialQualification!: ValidateableQualification;\n}\n```\n\nAnd in Qualification.ts:\n\n```\nimport { IsJSON, IsUrl, ValidateNested, IsOptional, IsBoolean, IsIn, IsArray } from 'class-validator';\nimport { Column, Entity, PrimaryGeneratedColumn, ManyToOne } from 'typeorm';\nimport { Business } from '../db/all-entities';\nimport tuple from './utils/string-enum-from-tuple';\nimport { omit } from './utils/entity-type-manipulations';\nimport { CATEGORIES } from '../../misc-types/category';\n\nconst VALIDITY_STATES = tuple('valid', 'pending-review', 'invalid');\n\n@Entity()\nexport default class Qualification {\n @PrimaryGeneratedColumn()\n id!: number;\n\n @Column({ nullable: true })\n // businesses do not need image proof\n @IsOptional()\n @IsUrl()\n imageUrl?: string;\n\n @ManyToOne(\n type => Business,\n business => business.qualifications,\n { onDelete: 'CASCADE' }\n )\n business!: Business;\n\n @Column({ type: 'enum', enum: VALIDITY_STATES, default: 'invalid' })\n @IsIn(VALIDITY_STATES)\n validity!: typeof VALIDITY_STATES[number];\n\n /**\n * The categories (slugs)\n */\n @Column('simple-json')\n @ValidateNested()\n @IsArray()\n @IsIn(\n CATEGORIES.filter(c => c.type === 'service').map(c => c.slug),\n { each: true }\n )\n categories!: string[];\n}\n\n/**\n * A qualification that can be sent by a business which is not necessarily verified yet.\n */\nexport const ValidateableQualification = omit(Qualification, ['id', 'business', 'validity']);\nexport type ValidateableQualification = typeof ValidateableQualification extends new () => infer U ? U : never;\n```\n\nWhenever either of these classes are imported, they're imported from this file to ensure the proper module loading order:\n\n```\n/* eslint-disable import/first */\n/**\n * This file exists to solve circular dependency problems with Webpack by explicitly specifying the module loading order.\n * @see https://medium.com/visual-development/how-to-fix-nasty-circular-dependency-issues-once-and-for-all-in-javascript-typescript-a04c987cf0de\n */\n\nexport { default as Qualification, ValidateableQualification } from '../entities/Qualification';\n\nexport { default as Account } from '../entities/Account';\nexport { default as Business, EditableBusiness, BusinessApplication } from '../entities/Business';\nexport { default as Customer } from '../entities/Customer';\n\nexport { default as BaseOffer } from '../entities/Offer';\n\nimport ProductOffer, { EditableProductOffer } from '../entities/ProductOffer';\nimport ServiceOffer, { EditableServiceOffer } from '../entities/ServiceOffer';\n\nexport { default as ProductOffer, EditableProductOffer } from '../entities/ProductOffer';\nexport { default as ServiceOffer, EditableServiceOffer } from '../entities/ServiceOffer';\n\nexport type Offer = ProductOffer | ServiceOffer;\nexport type EditableOffer = EditableProductOffer | EditableServiceOffer;\n```\n\nBabel is also used in this project. Here's the .babelrc:\n\n```\n{\n \"presets\": [\n [\n \"next/babel\",\n {\n \"class-properties\": {\n \"loose\": true\n },\n \"styled-jsx\": {\n \"plugins\": [\n \"styled-jsx-plugin-postcss\"\n ]\n }\n }\n ]\n ],\n \"plugins\": [\n \"babel-plugin-transform-typescript-metadata\",\n [\n \"@babel/plugin-proposal-decorators\",\n {\n \"legacy\": true\n }\n ]\n ]\n}\n```\n\nSorry for the huge wads of code. Could anybody help me try to solve this and figure out how to make it work in production like it works in development? Thanks.\n\n========================================\n\nCode:\n```text\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};\nconst decorator = (target, thing) => {\n};\nclass Business {\n}\nclass Qualification {\n}\n__decorate([\n decorator,\n __metadata(\"design:type\", Business)\n], Qualification.prototype, \"business\", void 0);\n```\n\n```js\nlet Qualification = (_dec = Object(external_typeorm_[\"Entity\"])(), _dec2 = Object(external_typeorm_[\"PrimaryGeneratedColumn\"])(), _dec3 = Reflect.metadata(\"design:type\", Number), _dec4 = Object(external_typeorm_[\"Column\"])({\n nullable: true\n}), _dec5 = Object(external_class_validator_[\"IsOptional\"])(), _dec6 = Object(external_class_validator_[\"IsUrl\"])(), _dec7 = Reflect.metadata(\"design:type\", String), _dec8 = Object(external_typeorm_[\"ManyToOne\"])(type => Business[\"c\" /* default */], business => business.qualifications, {\n onDelete: 'CASCADE'\n}), _dec9 = Reflect.metadata(\"design:type\", typeof Business[\"c\" /* default */] === \"undefined\" ?\n\n // ^ TypeError: cannot read property \"c\" of undefined\n\n\n\n Object : Business[\"c\" /* default */]), _dec10 = Object(external_typeorm_[\"Column\"])({\n type: 'enum',\n enum: VALIDITY_STATES,\n default: 'invalid'\n}), _dec11 = Object(external_class_validator_[\"IsIn\"])(VALIDITY_STATES), _dec12 = Reflect.metadata(\"design:type\", Object), _dec13 = Object(external_typeorm_[\"Column\"])('simple-json'), _dec14 = Object(external_class_validator_[\"ValidateNested\"])(), _dec15 = Object(external_class_validator_[\"IsArray\"])(), _dec16 = Object(external_class_validator_[\"IsIn\"])(category[\"a\" /* CATEGORIES */].filter(c => c.type === 'service').map(c => c.slug), {\n each: true\n}), _dec17 = Reflect.metadata(\"design:type\", Array), _dec(_class = (_class2 = (_temp = class Qualification {\n constructor() {\n _initializerDefineProperty(this, \"id\", _descriptor, this);\n\n _initializerDefineProperty(this, \"imageUrl\", _descriptor2, this);\n\n _initializerDefineProperty(this, \"business\", _descriptor3, this);\n\n _initializerDefineProperty(this, \"validity\", _descriptor4, this);\n\n _initializerDefineProperty(this, \"categories\", _descriptor5, this);\n }\n\n}, _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, \"id\", [_dec2, _dec3], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, \"imageUrl\", [_dec4, _dec5, _dec6, _dec7], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, \"business\", [_dec8, _dec9], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, \"validity\", [_dec10, _dec11, _dec12], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor5 = _applyDecoratedDescriptor(_class2.prototype, \"categories\", [_dec13, _dec14, _dec15, _dec16, _dec17], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n})), _class2)) || _class);\n```\n\n```js\nlet Business = (_dec6 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Entity\"])(), _dec7 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])(), _dec8 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsString\"])(), _dec9 = Reflect.metadata(\"design:type\", String), _dec10 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])({\n type: 'enum',\n enum: BUSINESS_TYPES\n}), _dec11 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsIn\"])(BUSINESS_TYPES), _dec12 = Reflect.metadata(\"design:type\", Object), _dec13 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])(), _dec14 = Reflect.metadata(\"design:type\", Boolean), _dec15 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"CreateDateColumn\"])(), _dec16 = Reflect.metadata(\"design:type\", typeof Date === \"undefined\" ? Object : Date), _dec17 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])({\n nullable: true\n}), _dec18 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsOptional\"])(), _dec19 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsUrl\"])(), _dec20 = Reflect.metadata(\"design:type\", String), _dec21 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])({\n nullable: true\n}), _dec22 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsOptional\"])(), _dec23 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsString\"])(), _dec24 = Reflect.metadata(\"design:type\", String), _dec25 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])({\n nullable: true\n}), _dec26 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsOptional\"])(), _dec27 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsString\"])(), _dec28 = Reflect.metadata(\"design:type\", String), _dec29 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])(), _dec30 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsString\"])(), _dec31 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"MaxLength\"])(200), _dec32 = Reflect.metadata(\"design:type\", String), _dec33 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"OneToMany\"])(type => _db_all_entities__WEBPACK_IMPORTED_MODULE_3__[/* Qualification */ \"i\"], qualification => qualification.business, {\n cascade: true\n}), _dec34 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"ValidateNested\"])(), _dec35 = Reflect.metadata(\"design:type\", Array), _dec36 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])('simple-json'), _dec37 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsArray\"])(), _dec38 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"ValidateNested\"])(), _dec39 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsIn\"])(_misc_types_category__WEBPACK_IMPORTED_MODULE_2__[/* CATEGORIES */ \"a\"].filter(c => c.type === 'business').map(c => c.slug), {\n each: true\n}), _dec40 = Reflect.metadata(\"design:type\", Array), _dec41 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])('simple-json'), _dec42 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsArray\"])(), _dec43 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"ValidateNested\"])(), _dec44 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"ArrayMinSize\"])(1), _dec45 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"ArrayMaxSize\"])(5), _dec46 = Reflect.metadata(\"design:type\", Array), _dec47 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])({\n type: 'enum',\n enum: PRICING_PLANS\n}), _dec48 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsIn\"])(PRICING_PLANS), _dec49 = Reflect.metadata(\"design:type\", String), _dec50 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"OneToMany\"])(type => _db_all_entities__WEBPACK_IMPORTED_MODULE_3__[/* BaseOffer */ \"b\"], offer => offer.offerer), _dec51 = Reflect.metadata(\"design:type\", Array), _dec6(_class3 = (_class4 = (_temp2 = class Business extends _db_all_entities__WEBPACK_IMPORTED_MODULE_3__[/* Account */ \"a\"] {\n constructor(...args) {\n super(...args);\n\n _initializerDefineProperty(this, \"name\", _descriptor3, this);\n\n _initializerDefineProperty(this, \"type\", _descriptor4, this);\n\n _initializerDefineProperty(this, \"isApproved\", _descriptor5, this);\n\n _initializerDefineProperty(this, \"since\", _descriptor6, this);\n\n _initializerDefineProperty(this, \"logoUrl\", _descriptor7, this);\n\n _initializerDefineProperty(this, \"fein\", _descriptor8, this);\n\n _initializerDefineProperty(this, \"phoneNumber\", _descriptor9, this);\n\n _initializerDefineProperty(this, \"bio\", _descriptor10, this);\n\n _initializerDefineProperty(this, \"qualifications\", _descriptor11, this);\n\n _initializerDefineProperty(this, \"businessCategories\", _descriptor12, this);\n\n _initializerDefineProperty(this, \"geolocations\", _descriptor13, this);\n\n _initializerDefineProperty(this, \"pricingPlan\", _descriptor14, this);\n\n _initializerDefineProperty(this, \"offers\", _descriptor15, this);\n }\n\n}, _temp2), (_descriptor3 = _applyDecoratedDescriptor(_class4.prototype, \"name\", [_dec7, _dec8, _dec9], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor4 = _applyDecoratedDescriptor(_class4.prototype, \"type\", [_dec10, _dec11, _dec12], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor5 = _applyDecoratedDescriptor(_class4.prototype, \"isApproved\", [_dec13, _dec14], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor6 = _applyDecoratedDescriptor(_class4.prototype, \"since\", [_dec15, _dec16], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor7 = _applyDecoratedDescriptor(_class4.prototype, \"logoUrl\", [_dec17, _dec18, _dec19, _dec20], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor8 = _applyDecoratedDescriptor(_class4.prototype, \"fein\", [_dec21, _dec22, _dec23, _dec24], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor9 = _applyDecoratedDescriptor(_class4.prototype, \"phoneNumber\", [_dec25, _dec26, _dec27, _dec28], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor10 = _applyDecoratedDescriptor(_class4.prototype, \"bio\", [_dec29, _dec30, _dec31, _dec32], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor11 = _applyDecoratedDescriptor(_class4.prototype, \"qualifications\", [_dec33, _dec34, _dec35], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor12 = _applyDecoratedDescriptor(_class4.prototype, \"businessCategories\", [_dec36, _dec37, _dec38, _dec39, _dec40], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor13 = _applyDecoratedDescriptor(_class4.prototype, \"geolocations\", [_dec41, _dec42, _dec43, _dec44, _dec45, _dec46], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor14 = _applyDecoratedDescriptor(_class4.prototype, \"pricingPlan\", [_dec47, _dec48, _dec49], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor15 = _applyDecoratedDescriptor(_class4.prototype, \"offers\", [_dec50, _dec51], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n})), _class4)) || _class3);\n```\n\n```js\nlet Qualification = (_dec = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Entity\"])(), _dec2 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"PrimaryGeneratedColumn\"])(), _dec3 = Reflect.metadata(\"design:type\", Number), _dec4 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])({\n nullable: true\n}), _dec5 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsOptional\"])(), _dec6 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsUrl\"])(), _dec7 = Reflect.metadata(\"design:type\", String), _dec8 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"ManyToOne\"])(type => _db_all_entities__WEBPACK_IMPORTED_MODULE_2__[\"Business\"], business => business.qualifications, {\n onDelete: 'CASCADE'\n}), _dec9 = Reflect.metadata(\"design:type\", typeof _db_all_entities__WEBPACK_IMPORTED_MODULE_2__[\"Business\"] === \"undefined\" ? Object : _db_all_entities__WEBPACK_IMPORTED_MODULE_2__[\"Business\"]), _dec10 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])({\n type: 'enum',\n enum: VALIDITY_STATES,\n default: 'invalid'\n}), _dec11 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsIn\"])(VALIDITY_STATES), _dec12 = Reflect.metadata(\"design:type\", Object), _dec13 = Object(typeorm__WEBPACK_IMPORTED_MODULE_1__[\"Column\"])('simple-json'), _dec14 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"ValidateNested\"])(), _dec15 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsArray\"])(), _dec16 = Object(class_validator__WEBPACK_IMPORTED_MODULE_0__[\"IsIn\"])(_misc_types_category__WEBPACK_IMPORTED_MODULE_5__[\"CATEGORIES\"].filter(c => c.type === 'service').map(c => c.slug), {\n each: true\n}), _dec17 = Reflect.metadata(\"design:type\", Array), _dec(_class = (_class2 = (_temp = class Qualification {\n constructor() {\n _initializerDefineProperty(this, \"id\", _descriptor, this);\n\n _initializerDefineProperty(this, \"imageUrl\", _descriptor2, this);\n\n _initializerDefineProperty(this, \"business\", _descriptor3, this);\n\n _initializerDefineProperty(this, \"validity\", _descriptor4, this);\n\n _initializerDefineProperty(this, \"categories\", _descriptor5, this);\n }\n\n}, _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, \"id\", [_dec2, _dec3], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, \"imageUrl\", [_dec4, _dec5, _dec6, _dec7], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, \"business\", [_dec8, _dec9], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, \"validity\", [_dec10, _dec11, _dec12], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n}), _descriptor5 = _applyDecoratedDescriptor(_class2.prototype, \"categories\", [_dec13, _dec14, _dec15, _dec16, _dec17], {\n configurable: true,\n enumerable: true,\n writable: true,\n initializer: null\n})), _class2)) || _class);\n```\n\n```js\nexport { default as Qualification } from '../entities/Qualification';\nexport { default as Business } from '../entities/Business';\n```\n\n```text\ndiff --git a/webpack-config-dev.txt b/webpack-config-prod.txt\nindex f8a28c3..8e5fa4d 100644\n--- a/webpack-config-dev.txt\n+++ b/webpack-config-prod.txt\n@@ -1,80 +1,82 @@\n {\n externals: [ [Function] ],\n optimization: {\n checkWasmTypes: false,\n nodeEnv: false,\n splitChunks: false,\n runtimeChunk: undefined,\n minimize: false,\n minimizer: [ [TerserPlugin], [CssMinimizerPlugin] ]\n },\n context: 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society',\n node: { setImmediate: false },\n entry: [AsyncFunction: entry],\n output: {\n path: 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\.next\\\\server',\n filename: [Function: filename],\n libraryTarget: 'commonjs2',\n hotUpdateChunkFilename: 'static/webpack/[id].[hash].hot-update.js',\n hotUpdateMainFilename: 'static/webpack/[hash].hot-update.json',\n- chunkFilename: '[name].js',\n+ chunkFilename: '[name].[contenthash].js',\n strictModuleExceptionHandling: true,\n crossOriginLoading: undefined,\n- futureEmitAssets: false,\n+ futureEmitAssets: true,\n webassemblyModuleFilename: 'static/wasm/[modulehash].wasm'\n },\n performance: false,\n resolve: {\n extensions: [\n '.tsx', '.ts',\n '.js', '.mjs',\n '.jsx', '.json',\n '.wasm'\n ],\n modules: [ 'node_modules' ],\n alias: {\n 'next/head': 'next/dist/next-server/lib/head.js',\n 'next/router': 'next/dist/client/router.js',\n 'next/config': 'next/dist/next-server/lib/runtime-config.js',\n 'next/dynamic': 'next/dist/next-server/lib/dynamic.js',\n next: 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next',\n 'private-next-pages': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\src\\\\pages',\n 'private-dot-next': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\.next'\n },\n mainFields: [ 'main', 'module' ],\n plugins: [ [Object] ]\n },\n resolveLoader: {\n alias: {\n 'emit-file-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\emit-file-loader',\n 'error-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\error-loader',\n 'next-babel-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\next-babel-loader',\n 'next-client-pages-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\next-client-pages-loader',\n 'next-data-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\next-data-loader',\n 'next-serverless-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\next-serverless-loader',\n 'noop-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\noop-loader',\n 'next-plugin-loader': 'C:\\\\Users\\\\Robbie\\\\Code\\\\fit-society\\\\node_modules\\\\next\\\\dist\\\\build\\\\webpack\\\\loaders\\\\next-plugin-loader'\n },\n modules: [ 'node_modules' ],\n plugins: [ [Object] ]\n },\n module: {\n rules: [ [Object], [Object], [Object] ],\n strictExportPresence: true\n },\n plugins: [\n ChunkNamesPlugin {},\n DefinePlugin { definitions: [Object] },\n- UnlinkRemovedPagesPlugin { prevAssets: {} },\n- NoEmitOnErrorsPlugin {},\n- NextJsRequireCacheHotReloader { prevAssets: null },\n+ HashedModuleIdsPlugin { options: [Object] },\n+ IgnorePlugin {\n+ options: [Object],\n+ checkIgnore: [Function: bound checkIgnore]\n+ },\n PagesManifestPlugin { serverless: false },\n NextJsSsrImportPlugin { options: [Object] },\n NextJsSsrImportPlugin {},\n FilterWarningsPlugin { exclude: [Array] }\n ],\n- mode: 'development',\n+ mode: 'production',\n name: 'server',\n target: 'node',\n- devtool: 'cheap-module-source-map'\n+ devtool: false\n }\n```\n\n```js\nimport {\n ArrayMaxSize,\n ArrayMinSize,\n IsArray,\n IsIn,\n IsOptional,\n IsString,\n IsUrl,\n MaxLength,\n ValidateNested,\n IsEmail\n} from 'class-validator';\nimport { Column, CreateDateColumn, Entity, OneToMany } from 'typeorm';\nimport { CATEGORIES } from '../../misc-types/category';\nimport { Geolocation } from '../../misc-types/geolocation';\nimport { Account, BaseOffer, Qualification, ValidateableQualification } from '../db/all-entities';\nimport { omit } from './utils/entity-type-manipulations';\nimport tuple from './utils/string-enum-from-tuple';\n\nconst BUSINESS_TYPES = tuple('individual', 'company');\nconst PRICING_PLANS = tuple('free');\n\n@Entity()\nexport default class Business extends Account {\n /**\n * Public name for the business.\n */\n @Column()\n @IsString()\n name!: string;\n\n @Column({ type: 'enum', enum: BUSINESS_TYPES })\n @IsIn(BUSINESS_TYPES)\n type!: typeof BUSINESS_TYPES[number];\n\n @Column()\n isApproved!: boolean;\n\n /**\n * The date the business created their account (not when it was approved)\n */\n @CreateDateColumn()\n since!: Date;\n\n @Column({ nullable: true })\n @IsOptional()\n @IsUrl()\n logoUrl?: string;\n\n @Column({ nullable: true })\n @IsOptional()\n @IsString()\n fein?: string;\n\n @Column({ nullable: true })\n @IsOptional()\n @IsString()\n phoneNumber?: string;\n\n @Column()\n @IsString()\n @MaxLength(200)\n bio!: string;\n\n @OneToMany(\n type => Qualification,\n qualification => qualification.business,\n { cascade: true }\n )\n @ValidateNested()\n qualifications!: Qualification[];\n\n @Column('simple-json')\n @IsArray()\n @ValidateNested()\n @IsIn(\n CATEGORIES.filter(c => c.type === 'business').map(c => c.slug),\n { each: true }\n )\n businessCategories!: string[];\n\n /**\n * Places this business is available at\n */\n @Column('simple-json')\n @IsArray()\n @ValidateNested()\n @ArrayMinSize(1)\n @ArrayMaxSize(5)\n geolocations!: Geolocation[];\n\n @Column({ type: 'enum', enum: PRICING_PLANS })\n @IsIn(PRICING_PLANS)\n pricingPlan!: 'free';\n\n @OneToMany(\n type => BaseOffer,\n offer => offer.offerer\n )\n offers!: BaseOffer[];\n}\n\n/**\n * A DTO sent to change business properties, most of which align one-to-one (excluding password/passwordHash).\n */\nexport class EditableBusiness extends omit(Business, [\n 'id',\n 'since',\n 'isApproved',\n 'qualifications',\n 'passwordHash',\n 'offers'\n]) {\n @IsString()\n password!: string;\n}\n\nexport class BusinessApplication extends EditableBusiness {\n @ValidateNested()\n @IsOptional()\n initialQualification!: ValidateableQualification;\n}\n```\n\n```js\nimport { IsJSON, IsUrl, ValidateNested, IsOptional, IsBoolean, IsIn, IsArray } from 'class-validator';\nimport { Column, Entity, PrimaryGeneratedColumn, ManyToOne } from 'typeorm';\nimport { Business } from '../db/all-entities';\nimport tuple from './utils/string-enum-from-tuple';\nimport { omit } from './utils/entity-type-manipulations';\nimport { CATEGORIES } from '../../misc-types/category';\n\nconst VALIDITY_STATES = tuple('valid', 'pending-review', 'invalid');\n\n@Entity()\nexport default class Qualification {\n @PrimaryGeneratedColumn()\n id!: number;\n\n @Column({ nullable: true })\n // businesses do not need image proof\n @IsOptional()\n @IsUrl()\n imageUrl?: string;\n\n @ManyToOne(\n type => Business,\n business => business.qualifications,\n { onDelete: 'CASCADE' }\n )\n business!: Business;\n\n @Column({ type: 'enum', enum: VALIDITY_STATES, default: 'invalid' })\n @IsIn(VALIDITY_STATES)\n validity!: typeof VALIDITY_STATES[number];\n\n /**\n * The categories (slugs)\n */\n @Column('simple-json')\n @ValidateNested()\n @IsArray()\n @IsIn(\n CATEGORIES.filter(c => c.type === 'service').map(c => c.slug),\n { each: true }\n )\n categories!: string[];\n}\n\n/**\n * A qualification that can be sent by a business which is not necessarily verified yet.\n */\nexport const ValidateableQualification = omit(Qualification, ['id', 'business', 'validity']);\nexport type ValidateableQualification = typeof ValidateableQualification extends new () => infer U ? U : never;\n```\n\n```js\n/* eslint-disable import/first */\n/**\n * This file exists to solve circular dependency problems with Webpack by explicitly specifying the module loading order.\n * @see https://medium.com/visual-development/how-to-fix-nasty-circular-dependency-issues-once-and-for-all-in-javascript-typescript-a04c987cf0de\n */\n\nexport { default as Qualification, ValidateableQualification } from '../entities/Qualification';\n\nexport { default as Account } from '../entities/Account';\nexport { default as Business, EditableBusiness, BusinessApplication } from '../entities/Business';\nexport { default as Customer } from '../entities/Customer';\n\nexport { default as BaseOffer } from '../entities/Offer';\n\nimport ProductOffer, { EditableProductOffer } from '../entities/ProductOffer';\nimport ServiceOffer, { EditableServiceOffer } from '../entities/ServiceOffer';\n\nexport { default as ProductOffer, EditableProductOffer } from '../entities/ProductOffer';\nexport { default as ServiceOffer, EditableServiceOffer } from '../entities/ServiceOffer';\n\nexport type Offer = ProductOffer | ServiceOffer;\nexport type EditableOffer = EditableProductOffer | EditableServiceOffer;\n```\n\n```text\n{\n \"presets\": [\n [\n \"next/babel\",\n {\n \"class-properties\": {\n \"loose\": true\n },\n \"styled-jsx\": {\n \"plugins\": [\n \"styled-jsx-plugin-postcss\"\n ]\n }\n }\n ]\n ],\n \"plugins\": [\n \"babel-plugin-transform-typescript-metadata\",\n [\n \"@babel/plugin-proposal-decorators\",\n {\n \"legacy\": true\n }\n ]\n ]\n}\n```\n\n```text\nBusiness\n```\n\n```text\nQualification\n```\n\n```text\n__decorate\n```\n\n```text\nBusiness\n```\n\n```text\nBusiness\n```\n\n```text\nQualification\n```\n\n```text\nall-entities.ts\n```\n\n```text\n./entities/Qualification.ts\n```\n\n```text\n./entities/Business.ts\n```\n\n```text\nexport const ValidateableQualification = omit(Qualification, ['id', 'business', 'validity']);\n```\n\n```text\nexport const RelationalEntities = [\n Qualification,\n Business,\n // ...\n]\n```\n\n```text\n@OneToMany(type => Qualification)\nqualification!: Qualification;\n\n// instead of (will not work)\n@OneToMany(Qualification)\nqualification!: Qualification;\n```\n\n```text\nQualification\n```\n\n```text\nValidateableQualification\n```\n\n```text\nQualification\n```\n\n```text\nclass-validator\n```\n\n```text\nRelationalEntities.ts\n```\n\n```text\nentities: RelationalEntities\n```\n\n```text\ntype => Type\n```\n\n```text\nType\n```\n\n```text\ntype => Qualification\n```\n\n```text\nQualification\n```\n\n========================================\n\nComments:\n- I'm pretty sure the fact that it works in the first place isn't TS, but webpack. An issue with the same problem has been labeled a design limitation by the TS team - github.com/microsoft/TypeScript/issues/27519\n- @Gerrit0 I know it's webpack's fault, but how do I get it to do what it's doing in dev mode in production mode?\n- Hi leonardo--I know you're knowledgeable on this subject for sure! Thanks for the suggestion, but I'm already doing that in my code. I've edited it to provide the offending classes for more information.\n- Oh sorry, I didn’t get it. I’ll check your updated post and try to see if I can tell you something more.\n- @RobertMoore ok I’m looking at the code and the babel config and I noticed only now that you are using my babel plugin to transform metadata 😂. The babel-loader with typescript metadata is a bit unreliable, and I never used it with Next.js but I’ll see if there is something we can do about it.\n- It will be very hard to omit ValidateableQualification and to not use the classes as values because I have a request body validator middleware that uses class-validator and a provided class (as a value) to check if the request is valid. These classes are not just used in TypeORM. Currently I'm trying to make sure I just don't import such entity-classes from next.js pages as values in the first place, I'll let you know how that goes.\n- So you can see all the code, I've invited you as a collaborator on the repository. Here is the page that is currently importing classes as values if you the imports. github.com/RobbieGM/fit-society/blob/master/src/pages/login/‌​…\n- Let us continue this discussion in chat.","metadata":{"transformedAt":"2026-08-18T18:33:44.719Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":32,"totalLines":1297,"estimatedTokens":12791}}477{"id":"stack-58523301","source":"stackoverflow","questionId":58523301,"title":"designing three dimensional relationships with ORM (TypeORM)","tags":["javascript","typescript","orm","nestjs","typeorm"],"text":"Title: designing three dimensional relationships with ORM (TypeORM)\nTags: javascript, typescript, orm, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI tried to create a database schema with users, groups, documents and permissions.\n\n- users can join multiple groups\n\n- groups can have multiple users\n\n- users can have permissions for documents\n\n- groups can have permissions for documents\n\n- permissions can be anything, not for documents only\n\nI tried to create a small graphic for that\n\nhttps://i.sstatic.net/5BjXh.png\n\nI started designing the entities\n\n**User**\n\n```\n@Entity('User')\nexport class UserEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @ManyToMany((type: any) => GroupEntity, (group: GroupEntity) => group.users)\n @JoinTable()\n groups: GroupEntity[];\n\n @ManyToMany((type: any) => DocumentEntity, (document: DocumentEntity) => document.users)\n @JoinTable()\n documents: DocumentEntity[];\n}\n```\n\n**Group**\n\n```\n@Entity('Group')\nexport class GroupEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @ManyToMany((type: any) => UserEntity, (user: UserEntity) => user.groups)\n users: UserEntity[];\n\n @ManyToMany((type: any) => DocumentEntity, (document: DocumentEntity) => document.groups)\n @JoinTable()\n documents: DocumentEntity[];\n}\n```\n\n**Document**\n\n```\n@Entity('Document')\nexport class DocumentEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @ManyToMany((type: any) => UserEntity, (user: UserEntity) => user.documents)\n users: UserEntity[];\n\n @ManyToMany((type: any) => GroupEntity, (group: GroupEntity) => group.documents)\n groups: GroupEntity[];\n}\n```\n\nWhen it comes to the persmissions for documents you will see that the relation exists between 3 tables, users/groups, documents and permissions.\n\nI use TypeORM for REST APIs (NestJs) and I'm not sure if a permission is an Entity. Due to the fact I'm designing REST endpoints this permission entity would be a shared entity along multiple endpoints.\n\nHow do I have to extend my entities for these permissions?\n\n... and maybe you might come up with a better database design :)\n\n========================================\n\nCode:\n```text\n@Entity('User')\nexport class UserEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @ManyToMany((type: any) => GroupEntity, (group: GroupEntity) => group.users)\n @JoinTable()\n groups: GroupEntity[];\n\n @ManyToMany((type: any) => DocumentEntity, (document: DocumentEntity) => document.users)\n @JoinTable()\n documents: DocumentEntity[];\n}\n```\n\n```text\n@Entity('Group')\nexport class GroupEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @ManyToMany((type: any) => UserEntity, (user: UserEntity) => user.groups)\n users: UserEntity[];\n\n @ManyToMany((type: any) => DocumentEntity, (document: DocumentEntity) => document.groups)\n @JoinTable()\n documents: DocumentEntity[];\n}\n```\n\n```text\n@Entity('Document')\nexport class DocumentEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @ManyToMany((type: any) => UserEntity, (user: UserEntity) => user.documents)\n users: UserEntity[];\n\n @ManyToMany((type: any) => GroupEntity, (group: GroupEntity) => group.documents)\n groups: GroupEntity[];\n}\n```\n\n```text\n@Entity('User')\nexport class UserEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @ManyToMany((type: any) => GroupEntity, (group: GroupEntity) => group.users)\n @JoinTable()\n groups: GroupEntity[];\n\n @OneToMany((type: any) => CrossUserDocumentPermissionEntity, (documentPermission: CrossUserDocumentPermissionEntity) => documentPermission.user)\n documentPermissions: CrossUserDocumentPermissionEntity[];\n}\n```\n\n```text\n@Entity('Group')\nexport class GroupEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @ManyToMany((type: any) => UserEntity, (user: UserEntity) => user.groups)\n users: UserEntity[];\n\n @OneToMany((type: any) => CrossGroupDocumentPermissionEntity, (documentPermission: CrossGroupDocumentPermissionEntity) => documentPermission.group)\n documentPermissions: CrossGroupDocumentPermissionEntity[];\n}\n```\n\n```text\n@Entity('Permission')\nexport class PermissionEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @OneToMany((type: any) => CrossUserDocumentPermissionEntity, (userDocument: CrossUserDocumentPermissionEntity) => userDocument.permission)\n usersDocuments: CrossUserDocumentPermissionEntity[];\n\n @OneToMany((type: any) => CrossGroupDocumentPermissionEntity, (groupDocument: CrossUserDocumentPermissionEntity) => groupDocument.permission)\n GroupDocuments: CrossGroupDocumentPermissionEntity[];\n}\n```\n\n```text\n@Entity('Document')\nexport class DocumentEntity {\n @PrimaryGeneratedColumn('uuid')\n id: string;\n\n @OneToMany((type: any) => CrossUserDocumentPermissionEntity, (userPermission: CrossUserDocumentPermissionEntity) => userPermission.document)\n usersPermissions: CrossUserDocumentPermissionEntity[];\n\n @OneToMany((type: any) => CrossGroupDocumentPermissionEntity, (groupPermission: CrossUserDocumentPermissionEntity) => groupPermission.document)\n GroupPermissions: CrossGroupDocumentPermissionEntity[];\n}\n```\n\n```text\n@Entity('Cross_User_Document_Permission')\nexport class CrossUserDocumentPermissionEntity {\n @PrimaryColumn()\n userId: string;\n\n @PrimaryColumn()\n permissionId: string;\n\n @PrimaryColumn()\n documentId: string;\n\n @ManyToOne((type: any) => UserEntity, (user: UserEntity) => user.documentPermission)\n user: UserEntity;\n\n @ManyToOne((type: any) => DocumentEntity, (document: DocumentEntity) => document.userPermission)\n document: DocumentEntity;\n\n @ManyToOne((type: any) => PermissionEntity, (permission: PermissionEntity) => permission.userDocument)\n permission: PermissionEntity;\n}\n```\n\n========================================\n\nComments:\n- @ Ralph thanks. So you would say Permission shouldn't be an entity?\n- No no I was refering to the three dimensional relation of the right instead of using the ManyToMany decorator create it manually with oneToMany ManyToOne you can have both three dimensional relations but @ManyToMany forces you to have only one table with two relations, if you need I can give you an example for the relation on the right\n- And about the permission if a user always have a group maybe you don't need the Cross_User_Document_Permission I beleive you need the Permission table because you can then diferenciate the permission unless you planning to use ACL in each document\n- a small example would be awesome :) it's possible that a user has no group membership","metadata":{"transformedAt":"2026-08-18T18:33:44.720Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":217,"estimatedTokens":1611}}478{"id":"stack-73581077","source":"stackoverflow","questionId":73581077,"title":"How to implement an interface in an Entity using typeorm","tags":["javascript","node.js","typescript","typeorm","node.js-typeorm"],"text":"Title: How to implement an interface in an Entity using typeorm\nTags: javascript, node.js, typescript, typeorm, node.js-typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm using an entity \"User\" but I need to implement the currentMatch the user is playing so I did something like this\n\n```\n@Column({\nnullable: true,\n})\npublic currentMatch: Match;\n```\n\nWhere Match is an interface with all the data I need from the match.\n\nERROR [ExceptionHandler] Data type \"Match\" in \"UserEntity.currentMatch\" is not supported by \"postgres\" database.\n\nIs there a way to implement my interface to the entity ?\n\n========================================\n\nCode:\n```text\n@Column({\nnullable: true,\n})\npublic currentMatch: Match;\n```\n\n```text\n@Column({\nnullable: true,\ntype: 'json'\n})\npublic currentMatch: Match;\n```\n\n```text\ntype: 'json'\n```\n\n========================================\n\nComments:\n- Thanks, now it does compile but it triggers this error: `ERROR [WsExceptionsHandler] Cannot read properties of null (reading 'player1')` player1 being a variable of the Match interface\n- Maybe the interface needs to change to represent what's in the database or vice versa `currentMatch: Match | null`\n- It should be the case but I'll try to look that way, thanks for your help !","metadata":{"transformedAt":"2026-08-18T18:33:44.720Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":48,"estimatedTokens":312}}479{"id":"stack-58088461","source":"stackoverflow","questionId":58088461,"title":"NestJS + TypeORM - Error connecting to both mysql and mongodb","tags":["javascript","node.js","mongodb","nestjs","typeorm"],"text":"Title: NestJS + TypeORM - Error connecting to both mysql and mongodb\nTags: javascript, node.js, mongodb, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI am just learning about NestJS and I have been trying to get an application to connect to both mysql and mongodb for some time and I just can't get it to work. The error I am getting is as follows:\n\n \n Nest can't resolve dependencies of the AppService (UserMRepository, ?). Please make sure that the argument at index [1] is available in the AppModule context.\n\n \n\nThis is a simple NestJS generated app that simply connects to two databases and will create a record in each database when getHello() is called. \n\napp.module.ts\n\n```\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { User } from './entity/User.entity';\nimport { UserM } from './entity/User.mongo';\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n \"name\": \"default\",\n \"type\": \"mongodb\",\n \"host\": \"localhost\",\n \"port\": 27017,\n \"database\": \"typeorm\",\n \"useNewUrlParser\": true,\n \"useUnifiedTopology\": true,\n \"entities\": [\n \"src/**/**.mongo.ts\",\n \"dist/**/**.mongo.js\"\n ],\n }), \n TypeOrmModule.forRoot({\n \"name\": \"mysql\",\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"typeorm\",\n \"password\": \"typeorm\",\n \"database\": \"typeorm\",\n \"entities\": [\n \"src/**/**.entity.ts\",\n \"dist/**/**.entity.js\"\n ],\n }),\n TypeOrmModule.forFeature([UserM]),\n TypeOrmModule.forFeature([User], 'mysql'),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\napp.service.ts\n\n```\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository, MongoRepository, getRepository, DeleteResult } from 'typeorm';\nimport { User} from \"./entity/User.entity\";\nimport { UserM } from './entity/User.mongo';\n\n@Injectable()\nexport class AppService {\n constructor(\n @InjectRepository(UserM)\n @InjectRepository(User)\n private readonly userMRepository: Repository,\n private readonly userRepository: Repository,\n ) {}\n\n async getHello(): Promise {\n var userM = new UserM();\n userM.firstName = \"Timber\";\n userM.lastName = \"Saw\";\n userM.age = 25;\n var newUser1 = await this.userMRepository.save(userM);\n\n var user = new User();\n user.firstName = \"Timber\";\n user.lastName = \"Saw\";\n user.age = 25;\n var newUser2 = await this.userRepository.save(user);\n\n return;\n }\n}\n```\n\nI can confirm that will successfully work with each database individually but when I try both together it keeps failing. I have read all the posts on this and tried various ways of setting this up so not sure what I am doing wrong. Is someone able to see what I am doing wrong?\n\nPaul\n\n========================================\n\nCode:\n```text\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { User } from './entity/User.entity';\nimport { UserM } from './entity/User.mongo';\n\n\n@Module({\n imports: [\n TypeOrmModule.forRoot({\n \"name\": \"default\",\n \"type\": \"mongodb\",\n \"host\": \"localhost\",\n \"port\": 27017,\n \"database\": \"typeorm\",\n \"useNewUrlParser\": true,\n \"useUnifiedTopology\": true,\n \"entities\": [\n \"src/**/**.mongo.ts\",\n \"dist/**/**.mongo.js\"\n ],\n }), \n TypeOrmModule.forRoot({\n \"name\": \"mysql\",\n \"type\": \"mysql\",\n \"host\": \"localhost\",\n \"port\": 3306,\n \"username\": \"typeorm\",\n \"password\": \"typeorm\",\n \"database\": \"typeorm\",\n \"entities\": [\n \"src/**/**.entity.ts\",\n \"dist/**/**.entity.js\"\n ],\n }),\n TypeOrmModule.forFeature([UserM]),\n TypeOrmModule.forFeature([User], 'mysql'),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n```\n\n```text\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository, MongoRepository, getRepository, DeleteResult } from 'typeorm';\nimport { User} from \"./entity/User.entity\";\nimport { UserM } from './entity/User.mongo';\n\n@Injectable()\nexport class AppService {\n constructor(\n @InjectRepository(UserM)\n @InjectRepository(User)\n private readonly userMRepository: Repository<UserM>,\n private readonly userRepository: Repository<User>,\n ) {}\n\n async getHello(): Promise<string> {\n var userM = new UserM();\n userM.firstName = \"Timber\";\n userM.lastName = \"Saw\";\n userM.age = 25;\n var newUser1 = await this.userMRepository.save(userM);\n\n var user = new User();\n user.firstName = \"Timber\";\n user.lastName = \"Saw\";\n user.age = 25;\n var newUser2 = await this.userRepository.save(user);\n\n return;\n }\n}\n```\n\n```text\nconstructor(\n @InjectRepository(UserM)\n private readonly userMRepository: Repository<UserM>,\n @InjectRepository(User, 'mysql')\n private readonly userRepository: Repository<User>,\n ) {}\n```\n\n========================================\n\nComments:\n- Thanks Tano, I tried that but it didn't work. I am getting the same error.\n- First of all, you should remove one of the entities path, since it doesnt make sense to use them twice. I assume that the user.entity is annotated with @Entity and the the typeorm database exists in mysql. Please add \"synchronize\": true to mysql connection to see if it can connect to it. the typeorm cant create the database in mysql only in mongo. If you can see more errors, with me\n- Tano, the Entities are slightly different in that the \"UserM\" uses ObjectID type for mongodb whereas \"User\" has an int type. I have been able to confirm that the connection to each database works successfully as I have commented the respective code for each database in turn and the uncommented database works successfully. It seems like the issue is more that NestJS itself is having an issue with both connections in parallel.\n- you can add the connection to the injectrepository annotation. Try it please!","metadata":{"transformedAt":"2026-08-18T18:33:44.720Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":3,"totalLines":196,"estimatedTokens":1480}}480{"id":"stack-47014450","source":"stackoverflow","questionId":47014450,"title":"How can I manage entities implementing a common interface?","tags":["typeorm"],"text":"Title: How can I manage entities implementing a common interface?\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI know that I can `implement` an interface when defining an `Entity`, but I want to be able to treat all implementations of this interface as if they had a shared table, with a common `Repository`. To better illustrate my problem, here a **two examples**:\n\n### GitHub repository owners\n\nOn GitHub both users and organizations can own repositories. Let's imagine there is a `User` and an `Organization` entity. They both implement the `RepositoryOwner` interface that specifies stuff like an array of `Repository`'s as a relation.\n\nNow take a look at GitHub's \"Trending developers\" page. It treats `User`'s and `Organization`'s equally as if there was a common `Repository` that could be used to fetch the data.\n\n### Resource sharing site\n\nA site where users can upload different types of resources like images, videos and documents. All of these types have their own `Entity` with different properties, but all of them implement the `Resource` interface. On a user's profile page there's a list of all the resources uploaded by this user. A `Repository` would be very helpful again, the type of a resource is determined using `typeof` and displayed using an icon.\n\n========================================\n\nCode:\n```text\nimplement\n```\n\n```text\nEntity\n```\n\n```text\nRepository\n```\n\n```text\nUser\n```\n\n```text\nOrganization\n```\n\n```text\nRepositoryOwner\n```\n\n```text\nRepository\n```\n\n```text\nUser\n```\n\n```text\nOrganization\n```\n\n```text\nRepository<RepositoryOwner>\n```\n\n```text\nEntity\n```\n\n```text\nResource\n```\n\n```text\nRepository<Resource>\n```\n\n```text\ntypeof\n```\n\n```text\nIRepositoryOwner\n```\n\n```text\nRepositoryOwner\n```\n\n```text\nRepositoryOwner\n```\n\n```text\nOrganization\n```\n\n```text\nUser\n```\n\n```text\nRepositoryOwners\n```\n\n```text\nrepositoryOwner instanceof User\n```\n\n```text\nrepositoryOwner\n```\n\n```text\nUser\n```\n\n========================================\n\nComments:\n- Can you simplify your question a bit? What do you want to achieve? I don't seem to ...\n- @RajshriMohanKS What part wasn't clear enough? I'd love to improve the question but don't know how.\n- I'm assuming that you intend to a common table from which you want to derive two more tables? In that case why can you not define an interface `IRepositoryOwner` and `implement` it in a base entity `RepositoryOwner`. And then `extend` `RepositoryOwner` to `Organization` and `User` entities? Is this what you are looking for?\n- Does this allow me to retrieve an array of `RepositoryOwner`'s, check the type using `repositoryOwner instanceof User` and cast `repositoryOwner` to a `User` when needed?\n- You should be able to retrieve an array of `RepositoryOwner`s but `repositoryOwner instanceof User` would be false. And casting `repositoryOwner` to `User` would not be possible. You'd be missing the derived class properties.","metadata":{"transformedAt":"2026-08-18T18:33:44.720Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":23,"totalLines":120,"estimatedTokens":725}}481{"id":"stack-63055143","source":"stackoverflow","questionId":63055143,"title":"Typeorm: Return only one property from loaded relation","tags":["typescript","mapping","api-design","typeorm"],"text":"Title: Typeorm: Return only one property from loaded relation\nTags: typescript, mapping, api-design, typeorm\nSource: Stack Overflow\n\nQuestion:\nUsecase: We have files in an S3 bucket with the respective information in our database.\nI would like to provide only an url for the frontend. Is this even possible?\n\nAt the moment it loads the whole object:\n\n```\n\"descriptionFile\": {\n \"id\": 99,\n \"createdAt\": \"2020-07-23T11:58:59.510Z\",\n \"updatedAt\": \"2020-07-23T11:58:59.510Z\",\n \"s3Identifier\": \"asdfasdf-2we3123r99\"\n},\n```\n\nGoal: To only have an url in the response:\n\n```\n\"descriptionFileUrl\": \"https://myapi.com/api/media/asdfasdf-2we3123r99\"\n```\n\nThese are my entities:\n\n```\n// category.entity.ts\n@OneToOne(type => S3File)\n@JoinColumn({ name: 'description_file_id' })\npublic descriptionFile: S3File;\n\n// s3-file.entity.ts\n@Column({ name: 's3_identifier', nullable: false })\npublic s3Identifier: string;\n\npublic get fullUrl() {\n return 'https://' + this.s3Identifier;\n}\n```\n\nService function that load the data:\n\n```\nthis.categoryRepository.find({\n relations: [..., 'descriptionFile'],\n});\n```\n\n========================================\n\nCode:\n```text\n\"descriptionFile\": {\n \"id\": 99,\n \"createdAt\": \"2020-07-23T11:58:59.510Z\",\n \"updatedAt\": \"2020-07-23T11:58:59.510Z\",\n \"s3Identifier\": \"asdfasdf-2we3123r99\"\n},\n```\n\n```text\n\"descriptionFileUrl\": \"https://myapi.com/api/media/asdfasdf-2we3123r99\"\n```\n\n```text\n// category.entity.ts\n@OneToOne(type => S3File)\n@JoinColumn({ name: 'description_file_id' })\npublic descriptionFile: S3File;\n\n// s3-file.entity.ts\n@Column({ name: 's3_identifier', nullable: false })\npublic s3Identifier: string;\n\npublic get fullUrl() {\n return 'https://' + this.s3Identifier;\n}\n```\n\n```text\nthis.categoryRepository.find({\n relations: [..., 'descriptionFile'],\n});\n```\n\n```text\n// constructor of service class\nconstructor(...) {\n this.s3Client = new S3Client({\n credentials: {\n accessKeyId: this.configService.s3AccessKey,\n secretAccessKey: this.configService.s3SharedSecret,\n },\n forcePathStyle: true,\n endpoint: this.configService.s3Host,\n });\n}\n\npublic getPresignedUrl(bucket: string, fileName: string): Promise<string> {\n const signedUrlExpireSeconds = 60 * 60; // 1h\n\n const command = new GetObjectCommand({\n Bucket: bucket,\n Key: fileName,\n });\n return getSignedUrl(this.s3Client, command, { expiresIn: signedUrlExpireSeconds });\n }\n```\n\n```text\n@aws-sdk/client-s3\n```\n\n```text\ngetPresignedUrl\n```\n\n========================================\n\nComments:\n- Look TypeORM select alias of column name or Typeorm - left join and select only relation entity, could be helpful","metadata":{"transformedAt":"2026-08-18T18:33:44.720Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":7,"totalLines":123,"estimatedTokens":671}}482{"id":"stack-71019065","source":"stackoverflow","questionId":71019065,"title":"typeorm inner join and where problem - BaseEntity model","tags":["typescript","typeorm","rawsql"],"text":"Title: typeorm inner join and where problem - BaseEntity model\nTags: typescript, typeorm, rawsql\nSource: Stack Overflow\n\nQuestion:\nI use typeorm (^0.2.41) and define two model which extends from my custom BaseModel:\n\nBaseModel:\n\n```\nimport { BaseEntity } from 'typeorm';\n\nexport class BaseModel extends BaseEntity {\n}\n```\n\nCategory:\n\n```\n@Entity('Category', { schema: 'public' })\nexport class Category extends BaseModel {\n @PrimaryGeneratedColumn({ type: 'integer', name: 'id' })\n id: number;\n\n @OneToMany(() => AbilityCategory, (abilityCategory) => abilityCategory.category, { onDelete: 'CASCADE' })\n abilityCategories: AbilityCategory[];\n}\n```\n\nAbilityCategory:\n\n```\n@Entity('_ability_category', { schema: 'public' })\nexport class AbilityCategory extends BaseModel {\n @PrimaryGeneratedColumn({ type: 'integer', name: 'id' })\n id: number;\n\n @ManyToOne(() => Category, (category) => category.abilityCategories)\n @JoinColumn([{ name: 'categoryId', referencedColumnName: 'id' }])\n category: Category;\n}\n```\n\n(I've removed unnecessary fields, before mention here)\n\nand I write this query:\n\n```\nawait Category.find({\n where: {\n type: 'JobCategory',\n 'abilityCategories.id': 13\n },\n join: {\n alias: 'category',\n innerJoinAndSelect: { abilityCategories: 'category.abilityCategories' }\n },\n take: 5\n}\n);\n```\n\nbut in raw sql query, it passes null to abilityCategories.id:\n\n```\nSELECT DISTINCT \"distinctAlias\".\"category_id\" as \"ids_category_id\"\nFROM (SELECT \"category\".\"id\" AS \"category_id\"\n FROM \"public\".\"Category\" \"category\"\n INNER JOIN \"public\".\"_ability_category\" \"abilityCategories\"\n ON \"abilityCategories\".\"categoryId\" = \"category\".\"id\"\n WHERE (\"category\".\"type\" = $1 AND \"abilityCategories\".\"id\" = $2)) \"distinctAlias\"\nORDER BY \"category_id\" ASC\nLIMIT 5 -- PARAMETERS: [\"JobCategory\",null]\n```\n\nis there anyone to help me find out the reason of null value for second parameter?\n\n========================================\n\nCode:\n```text\nimport { BaseEntity } from 'typeorm';\n\nexport class BaseModel extends BaseEntity {\n}\n```\n\n```text\n@Entity('Category', { schema: 'public' })\nexport class Category extends BaseModel {\n @PrimaryGeneratedColumn({ type: 'integer', name: 'id' })\n id: number;\n\n @OneToMany(() => AbilityCategory, (abilityCategory) => abilityCategory.category, { onDelete: 'CASCADE' })\n abilityCategories: AbilityCategory[];\n}\n```\n\n```text\n@Entity('_ability_category', { schema: 'public' })\nexport class AbilityCategory extends BaseModel {\n @PrimaryGeneratedColumn({ type: 'integer', name: 'id' })\n id: number;\n\n @ManyToOne(() => Category, (category) => category.abilityCategories)\n @JoinColumn([{ name: 'categoryId', referencedColumnName: 'id' }])\n category: Category;\n}\n```\n\n```text\nawait Category.find({\n where: {\n type: 'JobCategory',\n 'abilityCategories.id': 13\n },\n join: {\n alias: 'category',\n innerJoinAndSelect: { abilityCategories: 'category.abilityCategories' }\n },\n take: 5\n}\n);\n```\n\n```text\nSELECT DISTINCT \"distinctAlias\".\"category_id\" as \"ids_category_id\"\nFROM (SELECT \"category\".\"id\" AS \"category_id\"\n FROM \"public\".\"Category\" \"category\"\n INNER JOIN \"public\".\"_ability_category\" \"abilityCategories\"\n ON \"abilityCategories\".\"categoryId\" = \"category\".\"id\"\n WHERE (\"category\".\"type\" = $1 AND \"abilityCategories\".\"id\" = $2)) \"distinctAlias\"\nORDER BY \"category_id\" ASC\nLIMIT 5 -- PARAMETERS: [\"JobCategory\",null]\n```\n\n========================================\n\nComments:\n- Ops! I've forgotten to mention this field when I wrote this question. I've been edit the question.\n- The link is an incomplete answer, since the resource may be deleted. Please complete the answer.","metadata":{"transformedAt":"2026-08-18T18:33:44.720Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":5,"totalLines":141,"estimatedTokens":911}}483{"id":"stack-65317483","source":"stackoverflow","questionId":65317483,"title":"How to expose foreign key column in the entity in TypeORM","tags":["typeorm"],"text":"Title: How to expose foreign key column in the entity in TypeORM\nTags: typeorm\nSource: Stack Overflow\n\nQuestion:\nI have failed to expose the foreign key column in the entity which I feel weird to not be able to.\n\nIf I am not eager loading the relation, at least I should be able to to see the `imageId` to have some clue of the existence of the relation. so when I do a `userRepository.findOne({email: emailaddress})`, even I know that I can not `eager load` the image this way. But at least I could see the `imageId`.\n\n```\n@Column('datetime', { nullable: true, name: 'last_login' })\nlastLogin: string;\n\n@OneToOne(() => UserSetting)\n@JoinColumn({ name: 'setting_id' })\nsetting: UserSetting;\n\n@OneToOne(() => UserImage, { onDelete: 'SET NULL' })\n@JoinColumn({ name: 'image_id' })\nimage: UserImage;\n\nimageUrl: { preview: string, thumbnail: string };\n\n@OneToMany(() => Contact, contact => contact.user)\ncontacts: Contact[];\n\n@OneToMany(() => Notification, notification => notification.user)\nnotifications: Notification[];\n```\n\nAs you can see, there is no `imageId` defined. I tried to put it like this. The database just cannot be synced up and it wiped out all my image data too.\n\n```\n@Column({name: 'image_id' })\nimageId: string;\n\n@OneToOne(() => UserImage, { onDelete: 'SET NULL' })\n@JoinColumn({ name: 'image_id' })\nimage: UserImage;\n```\n\nAm I missing something simple here?\n\n========================================\n\nCode:\n```text\n@Column('datetime', { nullable: true, name: 'last_login' })\nlastLogin: string;\n\n@OneToOne(() => UserSetting)\n@JoinColumn({ name: 'setting_id' })\nsetting: UserSetting;\n\n@OneToOne(() => UserImage, { onDelete: 'SET NULL' })\n@JoinColumn({ name: 'image_id' })\nimage: UserImage;\n\nimageUrl: { preview: string, thumbnail: string };\n\n@OneToMany(() => Contact, contact => contact.user)\ncontacts: Contact[];\n\n@OneToMany(() => Notification, notification => notification.user)\nnotifications: Notification[];\n```\n\n```text\n@Column({name: 'image_id' })\nimageId: string;\n\n@OneToOne(() => UserImage, { onDelete: 'SET NULL' })\n@JoinColumn({ name: 'image_id' })\nimage: UserImage;\n```\n\n```text\nimageId\n```\n\n```text\nuserRepository.findOne({email: emailaddress})\n```\n\n```text\neager load\n```\n\n```text\nimageId\n```\n\n```text\nimageId\n```\n\n```text\n@Column({ nullable: true })\nimageId: string;\n\n@OneToOne(() => UserImage, userImage=> userImage.user, { onDelete: 'SET NULL' })\n@JoinColumn({ name: 'image_id' })\nimage: UserImage;\n```\n\n```text\n@OneToOne(() => User, user=> user.image)\nuser: User;\n```\n\n```text\nUser Entity\n```\n\n```text\nUserImage Entity\n```\n\n========================================\n\nComments:\n- Tried that. It breaks the database. imageId should add {name: 'image_id'} as well right?\n- You are right. I missed the nullable: true part. But after adding it, image id data are gone.\n- Maybe you should set the default value as well.\n- For the record, this is when creating the entity. Not for modifying it. If you are still running on the auto-migrate mode, adding the foreign key column will wipe out the whole foreign key column data.","metadata":{"transformedAt":"2026-08-18T18:33:44.720Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":11,"totalLines":125,"estimatedTokens":763}}484{"id":"stack-77889852","source":"stackoverflow","questionId":77889852,"title":"How to correctly seed the entities with on-to-many/many-to-one relations with Node.js + TypeORM + Postgres?","tags":["node.js","postgresql","typeorm"],"text":"Title: How to correctly seed the entities with on-to-many/many-to-one relations with Node.js + TypeORM + Postgres?\nTags: node.js, postgresql, typeorm\nSource: Stack Overflow\n\nQuestion:\nAlthough the TypeORM official documentation gives the answer to this question,\nlooks like there are some pitfalls. In my case, there are not errors, but looks like the binding has not been executed correctly.\n\nWell, I can't do exactly as in the TypeORM documentation in the code for production, so I have collected the data for diagnostic.\n\nIn my case, the `BlogPost` entity depends on `BlogPostCategory`:\n\n```\nimport { Entity, Column, PrimaryGeneratedColumn, ManyToOne as ManyToOne, Relation } from \"typeorm\";\nimport { isUndefined } from \"@yamato-daiwa/es-extensions\";\n\n@Entity()\nexport default class BlogPost {\n\n @PrimaryGeneratedColumn(\"uuid\")\n public readonly ID!: BlogPost.ID;\n\n @Column({ type: \"varchar\", nullable: false })\n public readonly heading!: string;\n\n @Column({ type: \"text\", nullable: false })\n public readonly HTML!: string;\n\n /* [ Theory ] About `Relation` https://stackoverflow.com/a/71983552/4818123 */\n @ManyToOne(\n (): typeof BlogPostCategory => BlogPostCategory,\n (blogPostCategory: BlogPostCategory): ReadonlyArray => blogPostCategory.blogPosts\n )\n public readonly category!: Relation;\n\n @Column({ type: \"varchar\", nullable: false })\n public readonly metaDescription!: string;\n\n @Column({ type: \"timestamp with time zone\", nullable: false })\n public readonly publishingDateTime__ISO8601!: string;\n\n public constructor(\n properties?: Readonly>\n ) {\n\n if (isUndefined(properties)) {\n return;\n }\n\n this.heading = properties.heading;\n this.HTML = properties.HTML;\n this.category = properties.category;\n this.metaDescription = properties.metaDescription;\n this.publishingDateTime__ISO8601 = properties.publishingDateTime__ISO8601;\n\n }\n\n}\n```\n\n```\n@Entity()\n@Unique([ \"text\" ])\nexport default class BlogPostCategory {\n\n @PrimaryGeneratedColumn(\"uuid\")\n public readonly ID!: BlogPostCategory.ID;\n\n @Column({ type: \"varchar\", nullable: false })\n public text!: string;\n\n @OneToMany(\n (): typeof BlogPost => BlogPost,\n (blogPost: BlogPost): BlogPostCategory => blogPost.category\n )\n public blogPosts!: Array;\n\n public constructor(properties?: Readonly>) {\n\n if (isUndefined(properties)) {\n return;\n }\n\n this.text = properties.text;\n\n }\n\n}\n```\n\nAlthough I don't know the seeding library compatible with newest version of TypeORM,\nin fact, the seeder is the simple script which could be run by `node` or `ts-node`, as in my case.\nFrom the viewpoint of logic, because the `BlogPost` depends on `BlogPostCategory`, it is better to create the instances of `BlogPostCategory` first.\n\n```\nimport { getArrayElementSatisfiesThePredicateIfSuchElementIsExactlyOne } from \"@yamato-daiwa/es-extensions\";\nimport { DataSource } from \"typeorm\";\n\nconst dataSource: DataSource = new DataSource(/* ... */);\n\nawait dataSource.initialize();\n\n// ...\n\nconst blogPostCategories: ReadonlyArray = await dataSource.manager.save(\n Object.\n values(initialBlogPostsCategories).\n map(\n (blogPostCategory): BlogPostCategory => new BlogPostCategory({ text: blogPostCategory.text })\n )\n );\n \nconsole.log(\"=== CHECKPOINT 1 =========================================================================\")\nconsole.log(blogPostCategories);\n\nconst blogPosts: Array = await dataSource.manager.save(\n initialBlogPosts.map(\n\n (blogPost: Readonly>): BlogPost =>\n\n new BlogPost({\n ...blogPost,\n category: getArrayElementSatisfiesThePredicateIfSuchElementIsExactlyOne(\n blogPostCategories,\n (blogPostCategory: BlogPostCategory): boolean =>\n blogPostCategory.text === blogPost.category.text,\n { mustThrowErrorIfElementNotFoundOrMatchesAreMultiple: true }\n )\n })\n\n )\n );\n\nconsole.log(\"=== CHECKPOINT 2 =========================================================================\")\nconsole.log(blogPosts)\n```\n\nThe example of output at `CHECKPOINT 1`:\n\n```\n[ \n BlogPostCategory { \n ID: '1c23cf90-f112-442f-9c12-240d6749d26d',\n text: 'Category 1', \n blogPosts: undefined \n }, \n BlogPostCategory { \n ID: 'f433eeb3-22e2-4218-81ed-d3ff21fe4936',\n text: 'Category 2', \n blogPosts: undefined \n }\n]\n```\n\n`blogPosts` are still undefined because they has not been created yet.\nI suppose, it is fine for now.\n\nThe example of output at `CHECKPOINT 2`:\n\n```\n[\n BlogPost {\n ID: 'e0403e10-4659-4363-88e7-8e7529823b31',\n heading: 'Post 1',\n HTML: \"\n\n### Post 1\n\n\",\n category: BlogPostCategory {\n ID: 'ae525873-91dc-4b84-92cc-ea31dcd326cb',\n text: 'Category 1',\n blogPosts: undefined\n },\n metaDescription: 'Post 1',\n publishingDateTime__ISO8601: '2024-01-25T07:23:59.840Z'\n },\n BlogPost {\n ID: '5f7dd7de-82c6-4119-8653-288d7e20a79f',\n heading: 'Post 2',\n HTML: \"\n\n### Post 2\n\n\",\n category: BlogPostCategory {\n ID: '1c23cf90-f112-442f-9c12-240d6749d26d',\n text: 'Category 2',\n blogPosts: undefined\n },\n metaDescription: 'Post 2',\n publishingDateTime__ISO8601: '2023-12-31T15:00:00.000Z'\n }\n]\n```\n\nWe have the recursion: `BlogPost` has `BlogPostCateogry` inside, and `BlogPostCateogry` has `BlogPost`s. I am not sure about it is fine, but when I try to retrieve the blog posts from the database, they have empty category. I suppose, the problems begins here.\n\nThe database content:\n\nhttps://i.sstatic.net/ciJnX.png\n\nhttps://i.sstatic.net/Wbh9F.png\n\nI suppose the usage of constructors in the entities is not the cause, because according to TypeORM documentation, the usage of constructors is fine if the constructor parameters are optional.\n\n========================================\n\nCode:\n```text\nimport { Entity, Column, PrimaryGeneratedColumn, ManyToOne as ManyToOne, Relation } from \"typeorm\";\nimport { isUndefined } from \"@yamato-daiwa/es-extensions\";\n\n\n@Entity()\nexport default class BlogPost {\n\n @PrimaryGeneratedColumn(\"uuid\")\n public readonly ID!: BlogPost.ID;\n\n @Column({ type: \"varchar\", nullable: false })\n public readonly heading!: string;\n\n @Column({ type: \"text\", nullable: false })\n public readonly HTML!: string;\n\n /* [ Theory ] About `Relation` https://stackoverflow.com/a/71983552/4818123 */\n @ManyToOne(\n (): typeof BlogPostCategory => BlogPostCategory,\n (blogPostCategory: BlogPostCategory): ReadonlyArray<BlogPost> => blogPostCategory.blogPosts\n )\n public readonly category!: Relation<BlogPostCategory>;\n\n @Column({ type: \"varchar\", nullable: false })\n public readonly metaDescription!: string;\n\n @Column({ type: \"timestamp with time zone\", nullable: false })\n public readonly publishingDateTime__ISO8601!: string;\n\n public constructor(\n properties?: Readonly<Omit<BlogPost, \"ID\">>\n ) {\n\n if (isUndefined(properties)) {\n return;\n }\n\n\n this.heading = properties.heading;\n this.HTML = properties.HTML;\n this.category = properties.category;\n this.metaDescription = properties.metaDescription;\n this.publishingDateTime__ISO8601 = properties.publishingDateTime__ISO8601;\n\n }\n\n}\n```\n\n```text\n@Entity()\n@Unique([ \"text\" ])\nexport default class BlogPostCategory {\n\n @PrimaryGeneratedColumn(\"uuid\")\n public readonly ID!: BlogPostCategory.ID;\n\n @Column({ type: \"varchar\", nullable: false })\n public text!: string;\n\n @OneToMany(\n (): typeof BlogPost => BlogPost,\n (blogPost: BlogPost): BlogPostCategory => blogPost.category\n )\n public blogPosts!: Array<BlogPost>;\n\n\n public constructor(properties?: Readonly<Omit<BlogPostCategory, \"ID\">>) {\n\n if (isUndefined(properties)) {\n return;\n }\n\n\n this.text = properties.text;\n\n }\n\n}\n```\n\n```text\nimport { getArrayElementSatisfiesThePredicateIfSuchElementIsExactlyOne } from \"@yamato-daiwa/es-extensions\";\nimport { DataSource } from \"typeorm\";\n\nconst dataSource: DataSource = new DataSource(/* ... */);\n\nawait dataSource.initialize();\n\n// ...\n\nconst blogPostCategories: ReadonlyArray<BlogPostCategory> = await dataSource.manager.save(\n Object.\n values(initialBlogPostsCategories).\n map(\n (blogPostCategory): BlogPostCategory => new BlogPostCategory({ text: blogPostCategory.text })\n )\n );\n \nconsole.log(\"=== CHECKPOINT 1 =========================================================================\")\nconsole.log(blogPostCategories);\n\nconst blogPosts: Array<BlogPost> = await dataSource.manager.save(\n initialBlogPosts.map(\n\n (blogPost: Readonly<Omit<BlogPost, \"ID\">>): BlogPost =>\n\n new BlogPost({\n ...blogPost,\n category: getArrayElementSatisfiesThePredicateIfSuchElementIsExactlyOne(\n blogPostCategories,\n (blogPostCategory: BlogPostCategory): boolean =>\n blogPostCategory.text === blogPost.category.text,\n { mustThrowErrorIfElementNotFoundOrMatchesAreMultiple: true }\n )\n })\n\n )\n );\n\nconsole.log(\"=== CHECKPOINT 2 =========================================================================\")\nconsole.log(blogPosts)\n```\n\n```text\n[ \n BlogPostCategory { \n ID: '1c23cf90-f112-442f-9c12-240d6749d26d',\n text: 'Category 1', \n blogPosts: undefined \n }, \n BlogPostCategory { \n ID: 'f433eeb3-22e2-4218-81ed-d3ff21fe4936',\n text: 'Category 2', \n blogPosts: undefined \n }\n]\n```\n\n```text\n[\n BlogPost {\n ID: 'e0403e10-4659-4363-88e7-8e7529823b31',\n heading: 'Post 1',\n HTML: \"<h1>Post 1</h1>\",\n category: BlogPostCategory {\n ID: 'ae525873-91dc-4b84-92cc-ea31dcd326cb',\n text: 'Category 1',\n blogPosts: undefined\n },\n metaDescription: 'Post 1',\n publishingDateTime__ISO8601: '2024-01-25T07:23:59.840Z'\n },\n BlogPost {\n ID: '5f7dd7de-82c6-4119-8653-288d7e20a79f',\n heading: 'Post 2',\n HTML: \"<h2>Post 2</h2>\",\n category: BlogPostCategory {\n ID: '1c23cf90-f112-442f-9c12-240d6749d26d',\n text: 'Category 2',\n blogPosts: undefined\n },\n metaDescription: 'Post 2',\n publishingDateTime__ISO8601: '2023-12-31T15:00:00.000Z'\n }\n]\n```\n\n```text\nBlogPost\n```\n\n```text\nBlogPostCategory\n```\n\n```text\nnode\n```\n\n```text\nts-node\n```\n\n```text\nBlogPost\n```\n\n```text\nBlogPostCategory\n```\n\n```text\nBlogPostCategory\n```\n\n```text\nCHECKPOINT 1\n```\n\n```text\nblogPosts\n```\n\n```text\nCHECKPOINT 2\n```\n\n```text\nBlogPost\n```\n\n```text\nBlogPostCateogry\n```\n\n```text\nBlogPostCateogry\n```\n\n```text\nBlogPost\n```\n\n```text\nconst blogCategoriesWithBlogs = await dataSource.manager.find(BlogPostCategory, {\nrelations: {\n blogPosts: true,\n}});\n```\n\n========================================\n\nComments:\n- How are you retrieving the blog posts from the database? Maybe the problem is there. With TypeORM you have to explicitly specify which relations you want to load, unless you specify the relations as eagerly loaded Also it looks like you are missing the @Entity decorator on BlogPostCategory entity...\n- @pert5432 Thank you for the comment. \"How are you retrieving the blog posts from the database?\" - by `repository.find();`. \"With TypeORM you have to explicitly specify which relations you want to load\" - in TypeORM configuration, I have explicitly specified `entities: [ BlogPost, BlogPostCategory ]`. \"Also it looks like you are missing the @Entity decorator on BlogPostCategory entity\" - Oh, sorry. It is the mistake during the boiling down of the production code. The real one has the `Entity` annotation.","metadata":{"transformedAt":"2026-08-18T18:33:44.720Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":20,"totalLines":446,"estimatedTokens":2854}}485{"id":"stack-71946569","source":"stackoverflow","questionId":71946569,"title":"How can I populate an object type's optional nested relations using string unions?","tags":["typescript","typeorm","typescript-generics"],"text":"Title: How can I populate an object type's optional nested relations using string unions?\nTags: typescript, typeorm, typescript-generics\nSource: Stack Overflow\n\nQuestion:\nI am attempting to create a `Populate` type that takes 2 generics: object type with optional relations (keys that reference other object types), and a union of Path strings that can deeply populate (or rather, set as non-optional) the relations. For example: having 3 entities that all optionally reference each other:\n\n```\ntype Tag = { name: string, countries?: Country[], companies?: Company[] }\ntype Company = { name: string, country?: Country, tags?: Tag[] };\ntype Country = { name: string, companies?: Company[], tags?: Tag[] };\n\ntype Populate = { // ... need help here ... // }\ntype CompanyWithCountry = Populate\ntype CompanyWithCountryAndTags = Populate\ntype SuperPopulatedCompany = Populate\n\n/** result for SuperPopulatedCompany = {\n name: string; \n country: null | Populate, //note for non-array items `null would be possible`\n tags: Populate[], //for array relations at least an empty array is always returned\n} \n*/\n```\n\nThe purpose of this is to enable me to type resulting object of using TypeORM's `relations` key in some of my queries, which can populate relational objects that reference eachother. Unfortunately, TypeORM's return type is always a base entity type, and any relations always remain optional regardless of which relations you passed into the query. I'm wanting to cast the return type to make relations not optional if they were queried. For example:\n\n```\nconst company = companyRepository.find({ \n id: 1,\n relations: ['country', 'country.companies', 'country.tags', 'tags', 'tags.companies'],\n}) as Populate\n\n/*\ntypeof company = {\n name: string;\n country: null | {\n name: string;\n companies: Company[], //non-optional\n tags: Tags[], //non-optional\n }\n tags: { \n name: string; \n companies: Company[], // non-optional\n countries?: Country[], //optional (because not in relations query)\n }[]\n}\n\nAllowing me to access: \n company.country, \n company.country?.companies, \n company.country?.tags, \n company.tags, \n company.tags[n]?.companies\n*/\n```\n\n========================================\n\nCode:\n```text\ntype Tag = { name: string, countries?: Country[], companies?: Company[] }\ntype Company = { name: string, country?: Country, tags?: Tag[] };\ntype Country = { name: string, companies?: Company[], tags?: Tag[] };\n\ntype Populate = { // ... need help here ... // }\ntype CompanyWithCountry = Populate<Company, 'country'>\ntype CompanyWithCountryAndTags = Populate<Company, 'country' | 'tags' | 'country.tags'>\ntype SuperPopulatedCompany = Populate<Company, 'country' | 'country.tags', 'country.tags.companies' | 'tags' | 'tags.companies' | 'tags.countries'>\n\n/** result for SuperPopulatedCompany = {\n name: string; \n country: null | Populate<Country, 'tags' | 'tags.companies'>, //note for non-array items `null would be possible`\n tags: Populate<Tag, 'companies' | 'countries'>[], //for array relations at least an empty array is always returned\n} \n*/\n```\n\n```text\nconst company = companyRepository.find({ \n id: 1,\n relations: ['country', 'country.companies', 'country.tags', 'tags', 'tags.companies'],\n}) as Populate<Company, 'country' | 'country.companies' | 'country.tags' | 'tags' | 'tags.companies' >\n\n/*\ntypeof company = {\n name: string;\n country: null | {\n name: string;\n companies: Company[], //non-optional\n tags: Tags[], //non-optional\n }\n tags: { \n name: string; \n companies: Company[], // non-optional\n countries?: Country[], //optional (because not in relations query)\n }[]\n}\n\nAllowing me to access: \n company.country, \n company.country?.companies, \n company.country?.tags, \n company.tags, \n company.tags[n]?.companies\n*/\n```\n\n```text\nPopulate\n```\n\n```text\nrelations\n```\n\n```text\ntype SplitPath<S, R extends unknown[] = []> = S extends `${infer P}.${infer Rest}` ? SplitPath<Rest, [...R, P]> : [...R, S];\n\ntype JoinPath<P, S extends string = \"\"> = P extends [infer First, ...infer Rest] ? JoinPath<Rest, `${S}${S extends \"\" ? \"\" : \".\"}${First & string}`> : S;\n```\n\n```text\n// Type to expand results so we can see if it works (mostly for debugging)\n// WARNING: BREAKS ON TUPLES\ntype Expand<T> = T extends ReadonlyArray<unknown> ? Expand<T[number]>[] : T extends object ? { [K in keyof T]: Expand<T[K]> } : T;\n```\n\n```text\ndeclare function find<Relations extends ReadonlyArray<string> = never>(criteria: {\n id?: number;\n relations?: Relations;\n // ...\n}): Expand<Populate<Company, Relations>>;\n```\n\n```text\ntype Populate<T, Keys extends ReadonlyArray<string>> = Omit<T, SplitPath<Keys[number]>[0]> & {\n [K in SplitPath<Keys[number]>[0]]-?:\n NonNullable<T[K & keyof T]> extends ReadonlyArray<unknown>\n ? Populate<NonNullable<T[K & keyof T]>[number], OmitFirstLevel<Keys, K>>[]\n : NonNullable<Populate<NonNullable<T[K & keyof T]>, OmitFirstLevel<Keys, K>>>\n};\n```\n\n```text\nOmit<T, SplitPath<Keys[number]>[0]>\n```\n\n```text\n{\n [K in SplitPath<Keys[number]>[0]]-?:\n NonNullable<T[K & keyof T]> extends ReadonlyArray<unknown>\n ? Populate<NonNullable<T[K & keyof T]>[number], OmitFirstLevel<Keys, K>>[]\n : NonNullable<Populate<NonNullable<T[K & keyof T]>, OmitFirstLevel<Keys, K>>>\n}\n```\n\n```text\n{\n [K in \"country\"]-?:\n NonNullable<T[K & keyof T]> extends ReadonlyArray<unknown>\n ? Populate<NonNullable<T[K & keyof T]>[number], OmitFirstLevel<Keys, K>>[]\n : NonNullable<Populate<NonNullable<T[K & keyof T]>, OmitFirstLevel<Keys, K>>>\n}\n```\n\n```text\n{\n country: NonNullable<T[\"country\" & keyof T]> extends ReadonlyArray<unknown>\n ? Populate<NonNullable<T[\"country\" & keyof T]>[number], OmitFirstLevel<Keys, \"country\">>[]\n : NonNullable<Populate<NonNullable<T[\"country\" & keyof T]>, OmitFirstLevel<Keys, \"country\">>>\n}\n```\n\n```text\n{\n country: NonNullable<T[\"country\"]> extends ReadonlyArray<unknown>\n ? Populate<NonNullable<T[\"country\"]>[number], OmitFirstLevel<Keys, \"country\">>[]\n : NonNullable<Populate<NonNullable<T[\"country\"]>, OmitFirstLevel<Keys, \"country\">>>\n}\n```\n\n```text\n{\n country: T[\"country\"] extends ReadonlyArray<unknown>\n ? Populate<T[\"country\"][number], OmitFirstLevel<Keys, \"country\">>[]\n : Populate<T[\"country\"], OmitFirstLevel<Keys, \"country\">>>\n}\n```\n\n```text\ntype OmitFirstLevel<\n Keys,\n Target extends string,\n R extends ReadonlyArray<unknown> = [],\n> = Keys extends readonly [infer First, ...infer Rest]\n ? SplitPath<First> extends readonly [infer T, ...infer Path]\n ? T extends Target\n ? Path extends []\n ? OmitFirstLevel<Rest, Target, R>\n : OmitFirstLevel<Rest, Target, [...R, JoinPath<Path>]>\n : OmitFirstLevel<Rest, Target, R>\n : OmitFirstLevel<Rest, Target, R>\n : R\n;\n```\n\n```text\n{\n country: T[\"country\"] extends ReadonlyArray<unknown>\n ? Populate<T[\"country\"][number], [\"tags\"]>>[]\n : Populate<T[\"country\"], [\"tags\"]>>\n}\n```\n\n```text\n{\n country: Populate<T[\"country\"], [\"tags\"]>\n}\n```\n\n```text\nSplitPath<\"country.tags.companies\">\n```\n\n```text\n[\"country\", \"tags\", \"companies\"]\n```\n\n```text\nJoinPath<[\"country\", \"tags\", \"companies\"]>\n```\n\n```text\n\"country.tags.companies\"\n```\n\n```text\nPopulate\n```\n\n```text\nPopulate<Company, [...]>\n```\n\n```text\nPopulate<...>\n```\n\n```text\nfind\n```\n\n```text\nPopulate\n```\n\n```text\nrelations\n```\n\n```text\nnever\n```\n\n```text\nRelations\n```\n\n```text\nPopulate\n```\n\n```text\nCompany\n```\n\n```text\nPopulate\n```\n\n```text\nT\n```\n\n```text\nPopulate<Company, [\"country\", \"country.tags\"]>\n```\n\n```text\nPopulate\n```\n\n```text\nOmit\n```\n\n```text\nOmit<Company, SplitPath<[\"country\", \"country.tags\"][number]>[0]>\n```\n\n```text\nOmit<Company, SplitPath<\"country\" | \"country.tags\">[0]>\n```\n\n```text\nOmit<Company, ([\"country\"] | [\"country\", \"tags\"])[0]>\n```\n\n```text\nOmit<Company, \"country\">\n```\n\n```text\n-?\n```\n\n```text\n\"country\" & keyof T\n```\n\n```text\n& keyof T\n```\n\n```text\nK\n```\n\n```text\nT\n```\n\n```text\n& keyof T\n```\n\n```text\nK\n```\n\n```text\nT\n```\n\n```text\nNonNullable\n```\n\n```text\nT[\"country\"]\n```\n\n```text\nNonNullable\n```\n\n```text\nExclude<T[\"country\"], undefined>\n```\n\n```text\nNonNullable\n```\n\n```text\nNonNullable\n```\n\n```text\nT[\"country\"]\n```\n\n```text\nT[\"country\"]\n```\n\n```text\nOmitFirstLevel\n```\n\n```text\nOmitFirstLevel<[\"country\", \"country.tags\"], \"country\">\n```\n\n```text\n[\"tags\"]\n```\n\n```text\nOmitFirstLevel<[\"country\", \"country.tags\", \"country.tags.companies\"], \"country\">\n```\n\n```text\n[\"tags\", \"tags.companies\"]\n```\n\n```text\nOmitFirstLevel<[\"country\", \"country.tags\", \"tags\", \"tags.companies\"], \"country\">\n```\n\n```text\n[\"tags\"]\n```\n\n```text\nT[\"country\"]\n```\n\n```text\nT[\"country\"]\n```\n\n```text\ntags\n```\n\n```text\nJoinPath\n```\n\n```text\nSplitPath\n```\n\n```text\nOmitFirstLevel\n```\n\n========================================\n\nComments:\n- To clear up why some keys may be null vs empty array: In a lot of relational ORMs if the JOINable row on a one-to-one relation is not found, the result will be null. If no JOINable rows are found on a one-to-many relation, the result is an empty array.\n- After an hour of fiddling I made this monstrosity. There might be a few little kinks I have to roll out but if it works for you, I'll find the time to write a complete answer.\n- @Gisheri could you please provide more explanation of what you are trying to achieve? At least minimum reproducible example with two properties\n- this is great! Thanks for looking over this problem. I'm just trying it out. The only difference I notice in the output is that nested populated children still have optional in their relations rather than `null`. I'm looking through it trying to see if I can figure out where that can be changed.\n- @Gisheri I don't know what that specifically means but this is a version that uses and removes `null` instead of optional properties and `undefined`.","metadata":{"transformedAt":"2026-08-18T18:33:44.720Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":69,"totalLines":438,"estimatedTokens":2480}}486{"id":"stack-69098205","source":"stackoverflow","questionId":69098205,"title":"TypeORM: One-To-One relation doesn't create foreign key for subtable","tags":["typescript","typeorm"],"text":"Title: TypeORM: One-To-One relation doesn't create foreign key for subtable\nTags: typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nI have two entities\n\nUsers:\n\n```\n@Entity()\nexport class Users {\n @PrimaryGeneratedColumn()\n user_id: number;\n\n @OneToOne(_ => UserContacts, contact => contact.user_id)\n @JoinColumn({ name: 'contact_id' })\n contacts: UserContacts\n}\n```\n\n```\n@Entity()\nexport class UserContacts {\n @PrimaryGeneratedColumn()\n contact_id: number;\n\n @OneToOne(_ => Users, users => users.contacts)\n user_id: Users;\n}\n```\n\nBut in PostgreSQL after saving I have:\n\nuser_contacts table:\n\n```\ncontact_id | user_id\n------------+---------\n 6 |\n```\n\nusers table:\n\n```\nuser_id | contact_id\n---------+------------\n 7 | 6\n```\n\nI suppose in user_contacts table in user_id column should be 7\n\nI just learn TypeORM so I don't create any architecture\n\nI have two functions for creating contacts and users\n\nMy save flow:\n\n```\nexport function createUser(contacts?: UserContacts): Users {\n const user = new Users();\n user.firstName = faker.name.firstName();\n user.lastName = faker.name.lastName();\n user.age = faker.datatype.number({ min: 1, max: 99 });\n\n if (contacts) { user.contacts = contacts }\n\n return user\n}\n\nexport function createContacts(): UserContacts {\n const contact = new UserContacts()\n contact.email = faker.internet.email();\n contact.phone = faker.phone.phoneNumber('##########');\n contact.address = faker.address.city();\n\n return contact;\n}\n\nasync function bootstrap() {\n try {\n const connection = await createConnection();\n const userRepository = connection.getRepository(Users);\n const contactRepository = connection.getRepository(UserContacts);\n\n const contacts = createContacts();\n const user = createUser(contacts);\n\n contactRepository.save(contacts);\n userRepository.save(user);\n\n console.info('Done!');\n\n } catch (e) {\n console.error(e.message);\n }\n}\n\nbootstrap();\n```\n\nWhat did I do wrong?\n\n========================================\n\nCode:\n```js\n@Entity()\nexport class Users {\n @PrimaryGeneratedColumn()\n user_id: number;\n\n @OneToOne(_ => UserContacts, contact => contact.user_id)\n @JoinColumn({ name: 'contact_id' })\n contacts: UserContacts\n}\n```\n\n```js\n@Entity()\nexport class UserContacts {\n @PrimaryGeneratedColumn()\n contact_id: number;\n\n @OneToOne(_ => Users, users => users.contacts)\n user_id: Users;\n}\n```\n\n```text\ncontact_id | user_id\n------------+---------\n 6 |\n```\n\n```text\nuser_id | contact_id\n---------+------------\n 7 | 6\n```\n\n```js\nexport function createUser(contacts?: UserContacts): Users {\n const user = new Users();\n user.firstName = faker.name.firstName();\n user.lastName = faker.name.lastName();\n user.age = faker.datatype.number({ min: 1, max: 99 });\n\n if (contacts) { user.contacts = contacts }\n\n return user\n}\n\nexport function createContacts(): UserContacts {\n const contact = new UserContacts()\n contact.email = faker.internet.email();\n contact.phone = faker.phone.phoneNumber('##########');\n contact.address = faker.address.city();\n\n return contact;\n}\n\nasync function bootstrap() {\n try {\n const connection = await createConnection();\n const userRepository = connection.getRepository(Users);\n const contactRepository = connection.getRepository(UserContacts);\n\n const contacts = createContacts();\n const user = createUser(contacts);\n\n contactRepository.save(contacts);\n userRepository.save(user);\n\n console.info('Done!');\n\n } catch (e) {\n console.error(e.message);\n }\n}\n\nbootstrap();\n```\n\n```js\n@Entity()\nexport class UserContacts {\n @PrimaryGeneratedColumn()\n contact_id: number;\n\n // This property is metadata. It's not column for DB\n @OneToOne(_ => Users, users => users.contacts)\n user: Users;\n}\n```\n\n========================================\n\nComments:\n- Can you post your code used for saving ? In your controller and service\n- I updated the post. I think I need three save calls because in one save I created contacts without user_id in the second I created a user with contact_id and in third, I should update contacts for updating user_id column. I already tried this variant but it doesn't work\n- Ok, in fact, regarding to doc (typeorm.io/#/one-to-one-relations) you can retreive users from your contacts table without explicit id on both side. You can get user by using contactRepository.find({relations: [\"users\"]). If you really want to duplicate the id information (that I would not recommand) you'll have to do it manually by updating this user_id column.\n- Ahhaha and if I want to find a user via another ORM/Native SQL query what do I need to do?))\n- You can do what typeORM do for you, something like : Select * From Users + Join UserContact table on users.contact_id = usercontact.id","metadata":{"transformedAt":"2026-08-18T18:33:44.720Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":6,"totalLines":204,"estimatedTokens":1181}}487{"id":"stack-40754004","source":"stackoverflow","questionId":40754004,"title":"How do i prevent decorators from importing node modules in TypeScript?","tags":["angular","typescript","webpack","typeorm"],"text":"Title: How do i prevent decorators from importing node modules in TypeScript?\nTags: angular, typescript, webpack, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to use the typeorm library in typescript to create a DTO/DAO pattern between a TypeScript 2 Express server and Angular 2. \n\nI'm calling these objects DTOs for brevity, but they are just a bunch of fields, and annotations. \n\n```\nimport {autoserialize} from \"cerialize\";\nimport {DTOReport} from \"./reports.dto\";\n\nimport { PrimaryGeneratedColumn} from \"typeorm/decorator/columns/PrimaryGeneratedColumn\"\nimport { CreateDateColumn } from \"typeorm/decorator/columns/CreateDateColumn\";\nimport { Column } from \"typeorm/decorator/columns/Column\";\nimport { JoinColumn } from \"typeorm/decorator/relations/JoinColumn\";\nimport { OneToOne } from \"typeorm/decorator/relations/OneToOne\";\nimport { ManyToOne } from \"typeorm/decorator/relations/ManyToOne\";\nimport { OneToMany } from \"typeorm/decorator/relations/OneToMany\";\nimport { Table } from \"typeorm/decorator/tables/Table\";\nimport { ColumnTypes } from \"typeorm/metadata/types/ColumnTypes\";\n\n@Table()\nexport class DTOSourceFile {\n @PrimaryGeneratedColumn()\n @autoserialize\n id: number;\n\n @Column()\n @autoserialize\n locationURL: string;\n\n @CreateDateColumn()\n @autoserialize\n createdAt: Date;\n\n @OneToMany(type => DTOReport, report => report.source, {nullable: true})\n @autoserialize report: DTOReport;\n @autoserialize reportId: number;\n\n @Column(ColumnTypes.TEXT)\n @autoserialize\n originalname: string;\n\n @Column(ColumnTypes.JSON)\n @autoserialize\n mutler: string;\n}\n```\n\nI'm carefully importing only the decorators. However, at compile time i see a request go back to the root index.ts file. \n\n```\n\"use strict\";\nconst ColumnTypes_1 = require(\"../../metadata/types/ColumnTypes\");\nconst ColumnTypeUndefinedError_1 = require(\"../error/ColumnTypeUndefinedError\");\nconst index_1 = require(\"../../index\"); // The resulting error from Angular 2's webpack compiler clearly shows the issue as it then tries to load node dependencies. \n\n```\nWARNING in ./~/typeorm/driver/sqlserver/SqlServerDriver.js\nModule not found: Error: Can't resolve 'mssql' in '/Users/jmurphy/projects/ubq/web/node_modules/typeorm/driver/sqlserver'\n @ ./~/typeorm/driver/sqlserver/SqlServerDriver.js 256:25-41\n @ ./~/typeorm/connection/ConnectionManager.js\n @ ./~/typeorm/index.js\n @ ./~/typeorm/decorator/columns/PrimaryGeneratedColumn.js\n @ ./src/app/dtos/lens.dto.ts\n @ ./src/app/lens/lens.component.ts\n @ ./src/app/app.module.ts\n @ ./src/app/index.ts\n @ ./src/main.ts\n @ multi main\nChild html-webpack-plugin for \"index.html\":\n Asset Size Chunks Chunk Names\n index.html 2.88 kB 0\nwebpack: bundle is now VALID.\n```\n\n**Is there a way to allow TypeORM decorators to exist in a browser project without trying to load node dependencies?** \n\n*Links:* \n\nTypeORM Source:\nhttps://github.com/typeorm/typeorm/blob/master/src/decorator/columns/PrimaryColumn.ts\n\n========================================\n\nCode:\n```text\nimport {autoserialize} from \"cerialize\";\nimport {DTOReport} from \"./reports.dto\";\n\nimport { PrimaryGeneratedColumn} from \"typeorm/decorator/columns/PrimaryGeneratedColumn\"\nimport { CreateDateColumn } from \"typeorm/decorator/columns/CreateDateColumn\";\nimport { Column } from \"typeorm/decorator/columns/Column\";\nimport { JoinColumn } from \"typeorm/decorator/relations/JoinColumn\";\nimport { OneToOne } from \"typeorm/decorator/relations/OneToOne\";\nimport { ManyToOne } from \"typeorm/decorator/relations/ManyToOne\";\nimport { OneToMany } from \"typeorm/decorator/relations/OneToMany\";\nimport { Table } from \"typeorm/decorator/tables/Table\";\nimport { ColumnTypes } from \"typeorm/metadata/types/ColumnTypes\";\n\n@Table()\nexport class DTOSourceFile {\n @PrimaryGeneratedColumn()\n @autoserialize\n id: number;\n\n @Column()\n @autoserialize\n locationURL: string;\n\n @CreateDateColumn()\n @autoserialize\n createdAt: Date;\n\n @OneToMany(type => DTOReport, report => report.source, {nullable: true})\n @autoserialize report: DTOReport;\n @autoserialize reportId: number;\n\n @Column(ColumnTypes.TEXT)\n @autoserialize\n originalname: string;\n\n @Column(ColumnTypes.JSON)\n @autoserialize\n mutler: string;\n}\n```\n\n```text\n\"use strict\";\nconst ColumnTypes_1 = require(\"../../metadata/types/ColumnTypes\");\nconst ColumnTypeUndefinedError_1 = require(\"../error/ColumnTypeUndefinedError\");\nconst index_1 = require(\"../../index\"); // < --- THIS\nconst PrimaryColumnCannotBeNullableError_1 = require(\"../error/PrimaryColumnCannotBeNullableError\");\n/**\n * Column decorator is used to mark a specific class property as a table column.\n * Only properties decorated with this decorator will be persisted to the database when entity be saved.\n * Primary columns also creates a PRIMARY KEY for this column in a db.\n */\nfunction PrimaryColumn(typeOrOptions, options) {\n let type;\n if (typeof typeOrOptions === \"string\") {\n type = typeOrOptions;\n }\n else {\n options = typeOrOptions;\n }\n return function (object, propertyName) {\n const reflectedType = ColumnTypes_1.ColumnTypes.typeToString(Reflect.getMetadata(\"design:type\", object, propertyName));\n // if type is not given implicitly then try to guess it\n if (!type)\n type = ColumnTypes_1.ColumnTypes.determineTypeFromFunction(Reflect.getMetadata(\"design:type\", object, propertyName));\n // if column options are not given then create a new empty options\n if (!options)\n options = {};\n // check if there is no type in column options then set type from first function argument, or guessed one\n if (!options.type)\n options = Object.assign({ type: type }, options);\n // if we still don't have a type then we need to give error to user that type is required\n if (!options.type)\n throw new ColumnTypeUndefinedError_1.ColumnTypeUndefinedError(object, propertyName);\n // check if column is not nullable, because we cannot allow a primary key to be nullable\n if (options.nullable)\n throw new PrimaryColumnCannotBeNullableError_1.PrimaryColumnCannotBeNullableError(object, propertyName);\n // implicitly set a primary to column options\n options = Object.assign({ primary: true }, options);\n // create and register a new column metadata\n const args = {\n target: object.constructor,\n propertyName: propertyName,\n propertyType: reflectedType,\n mode: \"regular\",\n options: options\n };\n index_1.getMetadataArgsStorage().columns.add(args); // < --- THIS\n };\n}\nexports.PrimaryColumn = PrimaryColumn;\n\n//# sourceMappingURL=PrimaryColumn.js.map\n```\n\n```text\nWARNING in ./~/typeorm/driver/sqlserver/SqlServerDriver.js\nModule not found: Error: Can't resolve 'mssql' in '/Users/jmurphy/projects/ubq/web/node_modules/typeorm/driver/sqlserver'\n @ ./~/typeorm/driver/sqlserver/SqlServerDriver.js 256:25-41\n @ ./~/typeorm/connection/ConnectionManager.js\n @ ./~/typeorm/index.js\n @ ./~/typeorm/decorator/columns/PrimaryGeneratedColumn.js\n @ ./src/app/dtos/lens.dto.ts\n @ ./src/app/lens/lens.component.ts\n @ ./src/app/app.module.ts\n @ ./src/app/index.ts\n @ ./src/main.ts\n @ multi main\nChild html-webpack-plugin for \"index.html\":\n Asset Size Chunks Chunk Names\n index.html 2.88 kB 0\nwebpack: bundle is now VALID.\n```\n\n```text\nimport * as fs from \"fs\";\nimport {Connection} from \"./Connection\";\nimport {ConnectionNotFoundError} from \"./error/ConnectionNotFoundError\";\nimport {MysqlDriver} from \"../driver/mysql/MysqlDriver\";\nimport {ConnectionOptions} from \"./ConnectionOptions\";\nimport {DriverOptions} from \"../driver/DriverOptions\";\nimport {Driver} from \"../driver/Driver\";\nimport {MissingDriverError} from \"./error/MissingDriverError\";\nimport {PostgresDriver} from \"../driver/postgres/PostgresDriver\";\nimport {AlreadyHasActiveConnectionError} from \"./error/AlreadyHasActiveConnectionError\";\nimport {Logger} from \"../logger/Logger\";\nimport {SqliteDriver} from \"../driver/sqlite/SqliteDriver\";\nimport {OracleDriver} from \"../driver/oracle/OracleDriver\";\nimport {SqlServerDriver} from \"../driver/sqlserver/SqlServerDriver\";\nimport {OrmUtils} from \"../util/OrmUtils\";\nimport {CannotDetermineConnectionOptionsError} from \"./error/CannotDetermineConnectionOptionsError\";\n\n/**\n * ConnectionManager is used to store and manage all these different connections.\n * It also provides useful factory methods to simplify connection creation.\n */\nexport class ConnectionManager {\n// ...\n```\n\n```text\ngetMetadataArgsStorage\n```\n\n```text\n/index.ts\n```\n\n```text\n/index.ts\n```\n\n```text\ngetMetadataArgsStorage\n```\n\n```text\ndefaultContainer\n```\n\n```text\nMetadataArgsStorage\n```\n\n```text\ngetMetadataArgsStorage\n```\n\n```text\nindex.ts\n```\n\n```text\nConnectionManager\n```\n\n========================================\n\nComments:\n- Can you include the source code of PrimaryColumn.ts please?\n- @OweRReLoaDeD - i've appended the link\n- Maybe I'm not understanding this correctly but there is an import in the TS github.com/typeorm/typeorm/blob/master/src/decorator/columns‌​/… that's why there is an import in the JS ?\n- @OweRReLoaDeD - gotcha. Looks like the author unintentionally coupled the decorators to the core module. Any advice?\n- i created a fork here doing exactly what you just outlined: github.com/rightisleft/typeorm/commit/…\n- If it works and you explain your use case to the original authors in a PR they will very likely accept it. Good luck ;)","metadata":{"transformedAt":"2026-08-18T18:33:44.720Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":13,"totalLines":274,"estimatedTokens":2378}}488{"id":"stack-67985267","source":"stackoverflow","questionId":67985267,"title":"NestJS / TypeORM join two tables from two different database","tags":["join","nestjs","typeorm"],"text":"Title: NestJS / TypeORM join two tables from two different database\nTags: join, nestjs, typeorm\nSource: Stack Overflow\n\nQuestion:\nI'm trying to make a query in **nestjs** using **typeorm** to **join two table from two different databases.**\nSearching online, I can't find any guide about it and probably I noticed that typeorm can't do that, is there a way to do it with or without typeorm?\n\n========================================\n\nTop Answer:\nOne way to do this is to write a raw query.\n\nIt doesn't have the advantages of being able to provide the entity structure around it, so you'll have to validate and add entities via `.create()`.\n\n```\nconst yourValidationAndTypeEnforcement = (input: any) => {\n if (!('field1' in input && typeof input.field1 === 'string')) {\n throw new Error('Expected field1 of type string');\n }\n // handle any other validation. \n // the below is really simplified. you'll probably have to do a little bit more on the entity side and break down which fields belong to which pa\n return manager.create(YourEntity, input);\n}\n// Raw query does the join the way you would in any SQL client.\nconst result = await manager.query(`SELECT * FROM db1.sourcetable as ST1 LEFT JOIN db2.sourcetable as ST2 ON ST1.some_id = ST2.some_matching_id`);\n// Then take the raw result and loop over it to create more developer friendly entities or POJOs.\nconst tidiedAndTyped = result.map(yourValidationAndTypeEnforcement);\n```\n\nI realise that isn't much to go on, but hopefully demonstrates a way to get past an issue like this.\n\n========================================\n\nCode:\n```text\nconst yourValidationAndTypeEnforcement = (input: any) => {\n if (!('field1' in input && typeof input.field1 === 'string')) {\n throw new Error('Expected field1 of type string');\n }\n // handle any other validation. \n // the below is really simplified. you'll probably have to do a little bit more on the entity side and break down which fields belong to which pa\n return manager.create(YourEntity, input);\n}\n// Raw query does the join the way you would in any SQL client.\nconst result = await manager.query(`SELECT * FROM db1.sourcetable as ST1 LEFT JOIN db2.sourcetable as ST2 ON ST1.some_id = ST2.some_matching_id`);\n// Then take the raw result and loop over it to create more developer friendly entities or POJOs.\nconst tidiedAndTyped = result.map(yourValidationAndTypeEnforcement);\n```\n\n```text\n.create()\n```\n\n========================================\n\nComments:\n- did you get any solution?\n- short answer no, but you can join the tables using two connections as explained in the answer","metadata":{"transformedAt":"2026-08-18T18:33:44.720Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":2,"totalLines":59,"estimatedTokens":647}}489{"id":"stack-63929408","source":"stackoverflow","questionId":63929408,"title":"How to implement Resolver-Inheritance with Type-GraphQL, TypeORM, and dependency injection","tags":["dependency-injection","factory","typeorm","typegraphql"],"text":"Title: How to implement Resolver-Inheritance with Type-GraphQL, TypeORM, and dependency injection\nTags: dependency-injection, factory, typeorm, typegraphql\nSource: Stack Overflow\n\nQuestion:\nI am trying to extend upon the Type-GraphQL provided example of resolvers-inheritance except replace the static data with a TypeORM repository.\n\nHere is how the PersonResolver extends the ResourceResolver and how it passes the `persons` array as the second argument of the ResourceResolver constructor.\n\n```\nconst persons: Person[] = [\n {\n id: 1,\n name: \"Person 1\",\n age: 23,\n role: PersonRole.Normal,\n },\n {\n id: 2,\n name: \"Person 2\",\n age: 48,\n role: PersonRole.Admin,\n },\n];\n\n@Resolver()\nexport class PersonResolver extends ResourceResolver(Person, persons) {\n ...\n}\n```\n\nInside the ResourceResolver\n\n```\nexport function ResourceResolver(\n ResourceCls: ClassType,\n resources: TResource[],\n) {\n const resourceName = ResourceCls.name.toLocaleLowerCase();\n\n // `isAbstract` decorator option is mandatory to prevent multiple registering in schema\n @Resolver(_of => ResourceCls, { isAbstract: true })\n @Service()\n abstract class ResourceResolverClass {\n protected resourceService: ResourceService;\n\n constructor(factory: ResourceServiceFactory) {\n this.resourceService = factory.create(resources);\n }\n...\n}\n```\n\nAnd in the ResourceServiceFactory\n\n```\n@Service()\nexport class ResourceServiceFactory {\n create(resources?: TResource[]) {\n return new ResourceService(resources);\n }\n}\n\nexport class ResourceService {\n constructor(protected resources: TResource[] = []) {}\n\n getOne(id: number): TResource | undefined {\n return this.resources.find(res => res.id === id);\n}\n```\n\nI would like to know the best way to implement the ResourceResolver but instead of static data I would like to pass a repository from TypeORM.\n\nHere is the original example - https://github.com/MichalLytek/type-graphql/tree/master/examples/resolvers-inheritance.\n\nAny help or advice is greatly appreciated.\n\n========================================\n\nCode:\n```text\nconst persons: Person[] = [\n {\n id: 1,\n name: \"Person 1\",\n age: 23,\n role: PersonRole.Normal,\n },\n {\n id: 2,\n name: \"Person 2\",\n age: 48,\n role: PersonRole.Admin,\n },\n];\n\n@Resolver()\nexport class PersonResolver extends ResourceResolver(Person, persons) {\n ...\n}\n```\n\n```text\nexport function ResourceResolver<TResource extends Resource>(\n ResourceCls: ClassType<TResource>,\n resources: TResource[],\n) {\n const resourceName = ResourceCls.name.toLocaleLowerCase();\n\n // `isAbstract` decorator option is mandatory to prevent multiple registering in schema\n @Resolver(_of => ResourceCls, { isAbstract: true })\n @Service()\n abstract class ResourceResolverClass {\n protected resourceService: ResourceService<TResource>;\n\n constructor(factory: ResourceServiceFactory) {\n this.resourceService = factory.create(resources);\n }\n...\n}\n```\n\n```text\n@Service()\nexport class ResourceServiceFactory {\n create<TResource extends Resource>(resources?: TResource[]) {\n return new ResourceService(resources);\n }\n}\n\nexport class ResourceService<TResource extends Resource> {\n constructor(protected resources: TResource[] = []) {}\n\n getOne(id: number): TResource | undefined {\n return this.resources.find(res => res.id === id);\n}\n```\n\n```text\npersons\n```\n\n```text\nfunction createBaseResolver<T extends BaseEntity>(suffix: string, objectTypeCls: T) {\n @Resolver({ isAbstract: true })\n abstract class BaseResolver { \n @Query(type => [objectTypeCls], { name: `getAll${suffix}` })\n async getA(@Arg(\"id\", type => Int) id: number): Promise<T> {\n let beCastedObj = (<typeof BaseEntity> objectTypeCls.constructor); // https://github.com/Microsoft/TypeScript/issues/5677\n return beCastedObj.findOne({ where: { id:id } }) as Promise<T>;\n }\n }\n \n return BaseResolver;\n }\n```\n\n```text\nconst PersonBaseResolver = createBaseResolver(\"person\", Person);\n\n@Resolver(of => Person)\nexport class PersonResolver extends PersonBaseResolver {\n // ...\n}\n```\n\n```text\nabstract class BaseUserCreatedEntityResolver {\n\n async get(args: any, ctx: any): Promise<T> {\n this.checkForLogin(ctx);\n let beCastedObj = (<typeof UserCreatedEntity>objectTypeCls.constructor);\n args = Object.assign(args, { userCreator: ctx.req.session.userId })\n let a = beCastedObj.findOne({ where: args }) as any;\n return a;\n }\n\n async getAll(args: any, ctx: any): Promise<T> {\n this.checkForLogin(ctx);\n let beCastedObj = (<typeof UserCreatedEntity>objectTypeCls.constructor);\n args = Object.assign(args, { userCreator: ctx.req.session.userId });\n beCastedObj.create(args);\n return beCastedObj.find({ where: args }) as any;\n }\n\n async add(args:any, ctx: any): Promise<T> {\n this.checkForLogin(ctx);\n let beCastedObj = (<typeof UserCreatedEntity>objectTypeCls.constructor);\n args = Object.assign(args, { userCreator: ctx.req.session.userId });\n let entity = await beCastedObj.create(args)[0];\n await entity.save();\n return entity as any;\n }\n\n async delete(args:any, ctx: any): Promise<T> {\n this.checkForLogin(ctx);\n let entity = await this.get(args,ctx);\n await entity.remove();\n return new Promise(()=>true);\n }\n\n async update(args:any, ctx: any): Promise<T> {\n this.checkForLogin(ctx);\n let entity = await this.get(args,ctx);\n delete args['userCreator'];// this should've been filtered out in child param definition, but adding it here just in case\n\n Object.assign(entity,args);\n await entity.save();\n return entity;\n }\n\n checkForLogin(ctx:any){\n if(!ctx.req.session.userId) throw new Error(\"User not logged in\");\n }\n\n }\n```\n\n```text\n@ArgsType()\nclass GetAllArgs {\n @Field()\n date:Date;\n}\n\n//...\n\n@Query(() => Entity)\nasync getAllEntitiesName(@Args() args :GetAllArgs, @Ctx() ctx: any) {\n return super.get(args,ctx);\n}\n```\n\n========================================\n\nComments:\n- Thank you for taking the time to answer my question. If you are experienced with TypeGraphQL and TypeORM do you think this patter is worth implementing? Thanks again for your help.\n- My pleasure :). The answer was too long to your question so i edited my answer above.\n- Wow this is a really cool paradigm! I understand the concept (thanks to your explanation) but still doubt myself with the implementation. In your opinion do you think that I should pursue this paradigm or simply repeat myself in my resolvers - considering I have less than 10 entities in my application.\n- I'm basically just using a parent class. It helps cut out a lot of code from the children (stay DRY). And if any child needs a custom resolver, just don't use the `super` call. You can do it! Remove the confusing TypeGraphQL parent resolver stuff and just make it a normal JS class. Then copy+paste my code (removing the session/login stuff if you don't need it) and put it in the parent. I went ahead and copied in all my parent functions, hopefully that helps.\n- Another thing you can do is just start writing the child classes without a parent, and then when you get frustrated with the copy+paste switch to using a parent. If you never get frustrated then you may not need to switch! Reduces \"Premature optimization\" [of code]","metadata":{"transformedAt":"2026-08-18T18:33:44.720Z","totalAnswersIncluded":0,"totalCodeBlocksIncluded":8,"totalLines":241,"estimatedTokens":1831}}490{"id":"stack-63456676","source":"stackoverflow","questionId":63456676,"title":"Memory problems in TypeORM, or me just filling it up","tags":["node.js","typescript","typeorm"],"text":"Title: Memory problems in TypeORM, or me just filling it up\nTags: node.js, typescript, typeorm\nSource: Stack Overflow\n\nQuestion:\nHave written an database init script in typescript using typeorm. And I seem to have cause a memory problem, but I can't figure out a way around it.\n\nCurrently the script imports three files\nProfiles (55 records)\nUser (5306 records)\nLogins (1006909 records)\n\nRewrote the calls so in all cases, the script will create a JSON with all the updates, then use `createQueryBuilder` to execute the update as per below:\n\n```\ngetConnection()\n .createQueryBuilder()\n .insert()\n .into(EULogin)\n .values(loginChunk)\n .execute()\n .catch(error => console.log(error))\n```\n\nWorks a charm for the first ones, but when it comes to the last one (the 1,000,000 entires), it will not play ball. And I get a memory problem\n\nLOGIN: Committed 196000/1006909 (Chunk Size:500) to database in 155 MS\nLOGIN: Committed 196500/1006909 (Chunk Size:500) to database in 823 MS\n\n[60698:0x110008000] 34328 ms: Scavenge 1389.1 (1423.6) -> 1388.6\n(1423.6) MB, 12.1 / 0.0 ms (average mu = 0.104, current mu = 0.099)\nallocation failure [60698:0x110008000] 34339 ms: Scavenge 1389.3\n(1423.6) -> 1388.9 (1423.6) MB, 10.4 / 0.0 ms (average mu = 0.104,\ncurrent mu = 0.099) allocation failure [60698:0x110008000] 34361\nms: Scavenge 1389.4 (1423.6) -> 1389.1 (1424.1) MB, 12.5 / 0.0 ms\n(average mu = 0.104, current mu = 0.099) allocation failure\n\n==== JS stack trace =========================================\n\n```\n0: ExitFrame [pc: 0x20ed7445be3d]\n1: StubFrame [pc: 0x20ed7440d608]\n2: StubFrame [pc: 0x20ed7502c4cc] Security context: 0x0fbfb411e6e9 \n3: /* anonymous */(aka /* anonymous */) [0xfbf79c62a41] [/Users/bengtbjorkberg/Development/EUGrapherNode/node_modules/typeorm/query-builder/InsertQueryBuilder.js:348]\n```\n\n[bytecode=0xfbf93b851a1 offset=26](this=0x0fbfab4826f1\n,valueSet=0x0fbf8846ebc1 FATAL ERROR: Ineffective mark-compacts near heap limit Allocation\nfailed - JavaScript heap out of memory 1: 0x10003cf99 node::Abort()\n[/usr/local/bin/node] 2: 0x10003d1a3 node::OnFatalError(char const*,\nchar const*) [/usr/local/bin/node] 3: 0x1001b7835\nv8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char\nconst*, bool) [/usr/local/bin/node] 4: 0x100585682\nv8::internal::Heap::FatalProcessOutOfMemory(char const*)\n[/usr/local/bin/node] 5: 0x100588155\nv8::internal::Heap::CheckIneffectiveMarkCompact(unsigned long, double)\n[/usr/local/bin/node] 6: 0x100583fff\nv8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector,\nv8::GCCallbackFlags) [/usr/local/bin/node] 7: 0x1005821d4\nv8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace,\nv8::internal::GarbageCollectionReason, v8::GCCallbackFlags)\n[/usr/local/bin/node] 8: 0x10058ea6c\nv8::internal::Heap::AllocateRawWithLigthRetry(int,\nv8::internal::AllocationSpace, v8::internal::AllocationAlignment)\n[/usr/local/bin/node] 9: 0x10058eaef\nv8::internal::Heap::AllocateRawWithRetryOrFail(int,\nv8::internal::AllocationSpace, v8::internal::AllocationAlignment)\n[/usr/local/bin/node] 10: 0x10055e434\nv8::internal::Factory::NewFillerObject(int, bool,\nv8::internal::AllocationSpace) [/usr/local/bin/node] 11: 0x1007e6714\nv8::internal::Runtime_AllocateInNewSpace(int, v8::internal::Object**,\nv8::internal::Isolate*) [/usr/local/bin/node] 12: 0x20ed7445be3d\n\nProcess finished with exit code 134 (interrupted by signal 6: SIGABRT)\n\nI have tried to open the database in synchronous mode (not async)\nI have tried to split the last update in as small as 50 records at a time\nI even tried to open and close the database for each chunk, but that died because I could not get it to do so synchronously.\n\nOpening the database with:\n\n```\ncreateConnection().then(connection => {\n```\n\nAnd below is the \"Chunkloader\"\n\n```\n.on('end', () => {\n let compTime: number = new Date().getTime()\n console.log(\"LOGIN: Entities read: \" + loginReadCounter + \" in \" + new Date(compTime - loginStartTime).getMilliseconds() + \" MS\")\n let currentChunk :number = 0;\n let chunkSize : number = 500;\n let loginChunk = [];\n let loginStartChunkTime : number = compTime;\n loginEntries.forEach(entry => {\n loginChunk.push(entry);\n currentChunk ++;\n loginCommitCounter++;\n if (currentChunk === chunkSize !! ){\n getConnection()\n .createQueryBuilder()\n .insert()\n .into(EULogin)\n .values(loginChunk)\n .execute()\n .catch(error => console.log(error))\n\n let compTime: number = new Date().getTime()\n console.log(\"LOGIN: Committed \" + loginCommitCounter + \"/\" + loginReadCounter + \" (Chunk Size:\" + loginChunk.length + \") to database in \" + new Date(compTime - loginStartChunkTime).getMilliseconds() + \" MS\");\n currentChunk = 0;\n loginStartChunkTime = compTime;\n loginChunk = [];\n\n }\n });\n```\n\nAny ideas?\n\n========================== EDIT FOLLOWING GOOD INPUT ====================\n\nTo try to sort my own head out, I moved it to a separate function, I got `await` to work, but how do I stop the process from continuing after the call. Because await works inside createConnection, but it does not work on createConnection, so the function will return straight away\n\n```\nfunction syncDataWrite(dbEntitiy, dataSet){\n console.log(\"DBLOADER Started for: \" + dataSet.length);\n createConnection().then(async connection => {\n console.log(\"DBLOADER Connected!\");\n const completion = await createQueryBuilder()\n .insert()\n .into(dbEntitiy)\n .values(dataSet)\n .execute()\n .catch(error => console.log(error))\n console.log(\"DBLOADER SQL uploaded\")\n })\n // console.log(dbEntity);\n\n}\n```\n\n========================================\n\nTop Answer:\nI took a lot of problem to fix this performance issue,\nat the end of the day I got it working using repository, instead of queryBuilder.\n\nBefore:\n\n```\nActiveRentalEntity.createQueryBuilder('ar')\n .insert()\n .values(data)\n .execute()\n```\n\nAfter (using repository). It's not because of the chunk thing, I tried chunking it manually using query builder and got same problem, seems like repository is better optmized:\n\n```\ngetRepository(ActiveRentalEntity).save(data, { chunk: 1000 });\n```\n\n========================================\n\nCode:\n```text\ngetConnection()\n .createQueryBuilder()\n .insert()\n .into(EULogin)\n .values(loginChunk)\n .execute()\n .catch(error => console.log(error))\n```\n\n```text\n0: ExitFrame [pc: 0x20ed7445be3d]\n1: StubFrame [pc: 0x20ed7440d608]\n2: StubFrame [pc: 0x20ed7502c4cc] Security context: 0x0fbfb411e6e9 <JSObject>\n3: /* anonymous */(aka /* anonymous */) [0xfbf79c62a41] [/Users/bengtbjorkberg/Development/EUGrapherNode/node_modules/typeorm/query-builder/InsertQueryBuilder.js:348]\n```\n\n```text\ncreateConnection().then(connection => {\n```\n\n```text\n.on('end', () => {\n let compTime: number = new Date().getTime()\n console.log(\"LOGIN: Entities read: \" + loginReadCounter + \" in \" + new Date(compTime - loginStartTime).getMilliseconds() + \" MS\")\n let currentChunk :number = 0;\n let chunkSize : number = 500;\n let loginChunk = [];\n let loginStartChunkTime : number = compTime;\n loginEntries.forEach(entry => {\n loginChunk.push(entry);\n currentChunk ++;\n loginCommitCounter++;\n if (currentChunk === chunkSize !! ){\n getConnection()\n .createQueryBuilder()\n .insert()\n .into(EULogin)\n .values(loginChunk)\n .execute()\n .catch(error => console.log(error))\n\n let compTime: number = new Date().getTime()\n console.log(\"LOGIN: Committed \" + loginCommitCounter + \"/\" + loginReadCounter + \" (Chunk Size:\" + loginChunk.length + \") to database in \" + new Date(compTime - loginStartChunkTime).getMilliseconds() + \" MS\");\n currentChunk = 0;\n loginStartChunkTime = compTime;\n loginChunk = [];\n\n }\n });\n```\n\n```text\nfunction syncDataWrite(dbEntitiy, dataSet){\n console.log(\"DBLOADER Started for: \" + dataSet.length);\n createConnection().then(async connection => {\n console.log(\"DBLOADER Connected!\");\n const completion = await createQueryBuilder()\n .insert()\n .into(dbEntitiy)\n .values(dataSet)\n .execute()\n .catch(error => console.log(error))\n console.log(\"DBLOADER SQL uploaded\")\n })\n // console.log(dbEntity);\n\n}\n```\n\n```text\ncreateQueryBuilder\n```\n\n```text\nawait\n```\n\n```text\nconst connection = getConnection();\nfor (const entry of loginEntries) {\n // [snip] \n await createQueryBuilder()\n .insert()\n .into(EULogin)\n .values(loginChunk)\n .execute()\n // [snip]\n}\n```\n\n```js\nasync function syncDataWrite(dbEntitiy, dataSet){\n\n console.log(\"DBLOADER Started for: \" + dataSet.length);\n const connection = await createConnection();\n console.log(\"DBLOADER Connected!\");\n const completion = await createQueryBuilder()\n .insert()\n .into(dbEntitiy)\n .values(dataSet)\n .execute();\n\n}\n```\n\n```text\nfor\n```\n\n```text\n.execute()\n```\n\n```text\nsyncDataWrite\n```\n\n```text\nsyncDataWrite\n```\n\n```text\nawait\n```\n\n```text\nActiveRentalEntity.createQueryBuilder('ar')\n .insert()\n .values(data)\n .execute()\n```\n\n```text\ngetRepository(ActiveRentalEntity).save(data, { chunk: 1000 });\n```\n\n========================================\n\nComments:\n- Been trying this, but can't get it to work. As soon as I run it I get an `Error:(170, 37) TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules.`. Not certain if it is because I am doing it from the fs stream or something. But it looks like it is running it synchronously\n- Added a function in the end, and you are right, but I can't get await working even in that (I think) simple example\n- @vrghost if `syncDataWrite` only handles a single chunk, then you still have the exact same problem. You need to use `await syncDataWrite()`. You can also do `const connection = await getConnection()`","metadata":{"transformedAt":"2026-08-18T18:33:44.721Z","totalAnswersIncluded":1,"totalCodeBlocksIncluded":16,"totalLines":309,"estimatedTokens":2673}}491 