깊은바다거북
개발 공부 기록
깊은바다거북
전체 방문자
오늘
어제
  • 분류 전체보기 (219)
    • JAVA (9)
    • JavaScript (15)
    • 스파르타코딩클럽 (11)
      • [내일배움단] 웹개발 종합반 개발일지 (5)
      • [내일배움캠프] 프로젝트와 트러블 슈팅 (6)
    • SQL | NoSQL (4)
    • CS 등등 (0)
    • TIL | WIL (173)
    • 기타 에러 해결 (3)
    • 내 살 길 궁리 (4)

인기 글

최근 글

최근 댓글

태그

  • DFS(깊이우선탐색)
  • tree
  • 팀 프로젝트
  • Til
  • TIT (Today I Troubleshot)
  • 혼자 공부하는 자바스크립트
  • POST / GET 요청
  • 자료 구조
  • Trie
  • 트러블 슈팅 Troubleshooting
  • 01. 미니 프로젝트
  • Leetcode
  • 자잘한 에러 해결
  • Binary Tree(이진 트리)
  • 점화식(Recurrence Relation)
  • Preorder Traversal(전위 순회)
  • 최소 힙(Min Heap)
  • 자바스크립트 기초 문법
  • 프로그래머스
  • 코딩테스트 연습문제
  • Backtracking(백트래킹)
  • BST(이진 탐색 트리)
  • BFS(너비우선탐색)
  • TypeScript
  • leetcode-cli
  • Linked List
  • 최대 힙(Max Heap)
  • 재귀 함수
  • Inorder Traversal(중위 순회)
  • 시간 복잡도
hELLO · Designed By 정상우.
깊은바다거북

개발 공부 기록

3/6 월 (N2T가 말썽이다) TIL, TIT
TIL | WIL

3/6 월 (N2T가 말썽이다) TIL, TIT

2023. 3. 7. 11:32

(최종 프로젝트 진행중)

에러가 많았다.

노션에 정리한 노트를 티스토리로 옮겨주는 프로그램인 N2T도 갑자기 안된다.

오늘 한 일:

  • TypeError: Class extends value undefined is not a constructor or null 튜터님 찾아가 해결하기 (순환 참조 문제라는데 해결법마다 내 케이스는 아니다. 정말 모르겠다.)
  • GitHub Actions 대략 세팅 건으로 회의 후 튜터님 찾아가기.

에러 정리와 재현을 다 못하고 우선 마무리한다.


※ 이하는 스스로 공부하며 적어둔 노트이며 불확실한 내용이 있을 수 있습니다. 학습용으로 적합하지 않음을 유념해주세요. ※

에러 TypeError: Class extends value undefined is not a constructor or null ✔️

발생 상황: Nest.js와 TypeORM 세팅을 끝마치고 최종 실행 도중 이렇게 에러가 떴다. 이상한 것은 Entity 관계 설정만 해줬을 때는 문제가 없었다는 것이었다. nullable이니 뭐니 속성값을 주던 때부터 각 모듈마다 TypeOrmModule을 연결해주던 시점 사이에 문제가 발생한 것 같다.

에러 메세지 전문:

[오전 2:58:46] File change detected. Starting incremental compilation...

[오전 2:58:47] Found 0 errors. Watching for file changes.


C:\Users\USER\Desktop\Sparta\05_project_무인냥품\src\user-like\user-like.entity.ts:12
export class UserLike extends LikeBase {
                              ^
TypeError: Class extends value undefined is not a constructor or null
    at Object.<anonymous> (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\src\user-like\user-like.entity.ts:12:31)
    at Module._compile (node:internal/modules/cjs/loader:1159:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Function.Module._load (node:internal/modules/cjs/loader:878:12)
    at Module.require (node:internal/modules/cjs/loader:1061:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\src\user\user.entity.ts:16:1)
    at Module._compile (node:internal/modules/cjs/loader:1159:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1213:10)

시도: 찾아보니 참조 순환 문제라고 하는데, 전부 내 케이스가 아니다… 그리고 나름 이해한 해결법들에 따르면 나는 문제가 발생할 이유가 없는데 싶다. 하나 의심가는 것은 (문제의) user-like.entity.ts에서 User를 공통적으로 두 번 참조하고 있다는 점이다.

여기 보던 중: https://stackoverflow.com/questions/43176006/typeerror-class-extends-value-undefined-is-not-a-function-or-null

DB를 확인해보니, requests 테이블은 없고 cat 테이블이 cats 외에 또 생긴 상태이다. 이건 뭐지..?

이런 참조 순환 문제는 원인을 잡아내기가 어렵다고 한다.

원인:

해결: 문제가 되는 LikeBase 클래스를 다른 파일로 분리하고 export 시켜주었더니 해결되었다.

에러 QueryFailedError: Cannot add or update a child row: a foreign key constraint fails ✔️

발생 상황: 처음 빈 DB 테이블들을 만들고, 내 파트인 ‘품앗이(requests 테이블)’ POST http://localhost:3000/requests API를 호출했는데 위와 같은 에러가 뜸.

에러 메세지 전문:

C:\Users\USER\Desktop\Sparta\05_project_무인냥품\src\driver\mysql\MysqlQueryRunner.ts:222
                                new QueryFailedError(query, parameters, err),
                                ^
QueryFailedError: ER_NO_REFERENCED_ROW_2: Cannot add or update a child row: a foreign key constraint fails (`mooin_cat`.`requests`, CONSTRAINT `FK_9e5e2eb56e3837b43e5a547be23` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`))
    at Query.<anonymous> (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\src\driver\mysql\MysqlQueryRunner.ts:222:33)
    at Query.<anonymous> (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\mysql\lib\Connection.js:526:10)
    at Query._callback (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\mysql\lib\Connection.js:488:16)
    at Query.Sequence.end (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
    at Query.ErrorPacket (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\mysql\lib\protocol\sequences\Query.js:92:8)
    at Protocol._parsePacket (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\mysql\lib\protocol\Protocol.js:291:23)
    at Parser._parsePacket (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\mysql\lib\protocol\Parser.js:433:10)
    at Parser.write (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\mysql\lib\protocol\Parser.js:43:10)
    at Protocol.write (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\mysql\lib\protocol\Protocol.js:38:16)
    at Socket.<anonymous> (C:\Users\USER\Desktop\Sparta\05_project_무인냥품\node_modules\mysql\lib\Connection.js:88:28)

시도: users 테이블에 데이터를 하나 넣어봤다. ⇒ 여전히 동일한 에러.

시도2. 임의로 user_id=2라는 식으로 데이터를 함께 넣어줘봤다. ⇒ 안됨.

시도3. 현재 users 테이블엔 데이터가 하나뿐이라 user_id=2가 없는 상태니, user_id=1을 임의로 넣어줘봄 ⇒ 됐다!

원인: requests 테이블의 user_id가 users 테이블을 참조하고 있는데, users가 가지고 있지 않은 user_id 값을 참조하여 requests에 행을 만들려고 해 발생한 에러이다.

해결: ‘부모’ 테이블을 참조하고 있는 ‘자식’ 테이블에 데이터를 넣을 땐, 부모에게 있는 PK 값에 ‘존재하는’ 외래키값을 넣어주어야 한다.

[TypeORM] 기본 find() 메소드로 Join해올 때 컬럼 선별하기 + nested join하기

// src/request/request.entity.ts
@Entity({ name: 'requests' })
export class Request {
	...
	@ManyToOne(() => User, (user: User) => user.requests, { cascade: true })
	@JoinColumn({ name: 'user_id' })
	user: User;
}

// src/request/request.service.ts
const request = await this.requestRepository.find({
  relations: {
    user: true,
  },
  select: {
    user: {
      nickname: true,
    },
    request_id: true,
    reserved_time: true,
    detail: true,
  },
});

포인트: 관계키로 형성된 가상 컬럼 Request.user 를 사용하는데,

  1. relations에도 넣어주고,
  1. select 부분에도 배열로 컬럼명을 나열하는 게 아니라 객체로 만들어 넣어주는 것이 핵심이다.

조회 결과:

[
  {
    "request_id": 4,
    "detail": "낯을 많이 가려요",
    "reserved_time": "0000-00-00",
    "user": {
      "nickname": "Nick"
    }
  },
  {
    "request_id": 5,
    "detail": "사람 보면 잘 숨어요",
    "reserved_time": "0000-00-00",
    "user": {
      "nickname": "Nick"
    }
  },
	...
]

결과 쿼리문:

=> 
sub selection user
adding following selects:  [ 'Request__Request_user.nickname' ]
query: 
SELECT `Request`.`request_id` AS `Request_request_id`, `Request`.`detail` AS `Request_detail`, `Request`.`reserved_time` AS `Request_reserved_time`, `Request__Request_user`.`nickname` AS `Request__Request_user_nickname`, `Request__Request_user`.`user_id` AS `Request__Request_user_user_id` 
FROM `requests` `Request` 
LEFT JOIN `users` `Request__Request_user` 
		ON `Request__Request_user`.`user_id`=`Request`.`user_id` 
		AND (`Request__Request_user`.`deleted_at` IS NULL) 
WHERE `Request`.`deleted_at` IS NULL

LEFT JOIN에 AND로 조건 걸어주는 게 신기하네…

같은 방식으로 한 ‘요청’에 딸린 유저에게 딸린 고양이들의 정보도 조인하여 원하는 컬럼을 선별하여 가져올 수 있다. Nested 객체 표기를 사용하면 된다:

const request = await this.requestRepository.find({
  relations: {
    user: {
      cats: true,
    },
  },
  select: {
    user: {
      nickname: true,
      cats: {
        gender: true,
      },
    },
    request_id: true,
    reserved_time: true,
    detail: true,
  },
});

=> 조회 결과:
[
  {
    "request_id": 4,
    "detail": "낯을 많이 가려요",
    "reserved_time": "0000-00-00",
    "user": {
      "nickname": "Nick",
      "cats": []
    }
  },
  {
    "request_id": 5,
    "detail": "사람 보면 잘 숨어요",
    "reserved_time": "0000-00-00",
    "user": {
      "nickname": "Nick",
      "cats": []
    }
  },
]

(참고: https://stackoverflow.com/questions/59645009/how-to-return-only-some-columns-of-a-relations-with-typeorm)

Git stash 명령어 모음

저장: git stash 혹은 git stash save

목록 조회: git stash list

목록에서 불러오기: git stash apply = git stash apply 0

목록에서 삭제: git stash drop = git stash drop 0

목록에서 불러오고 삭제: git stash pop = git stash apply 0 + git stash drop 0

저장 되돌리기(?) git stash show -p 0 | git apply -R

깃 글로벌 (단축) 명령어 등록하기..!

$ git config --global alias.stash-unapply '!git stash show -p | git apply -R'
$ git stash apply
$ #... work work work
// alias로 등록한 stash 되돌리기 명령어
$ git stash-unapply

(참고: https://gmlwjd9405.github.io/2018/05/18/git-stash.html)

에러 error: failed to push some refs to 'https://github.com…’ (진행중)

에러 TypeORMError: Entity metadata for User#requests was not found.

TypeOrmModule.forFeature function에 해당 모듈(여기서는 User)을 entities 항목에 넣는 걸 깜빡하면 발생(?)

(https://stackoverflow.com/questions/56693067/entity-metadata-for-roleusers-was-not-found)


Uploaded by N2T

    'TIL | WIL' 카테고리의 다른 글
    • 3/8 수 (팀 커밋 방식을 조율하다) TIL, TIT
    • 3/7 화 (GitHub Actions와 Nest.js 네이밍 컨벤션, 그리고 프로젝트 모듈명 바꾸기 노가다) TIL, TIT
    • 3월 5일 (프로젝트 구조를 짜다) TIL
    • 3/4 토 (TypeORM 소스 파일과 공식 문서를 함께 후루룩) TIL, TIT
    깊은바다거북
    깊은바다거북

    티스토리툴바