저장을 습관화
에러 기록 - MongoServerError: E11000 duplicate key error 본문
1. 증상
mongoose를 이용하여 MongDB에 POST할 경우 발생
app.js의 실행을 강제적으로 종료시킴
에러 로그는 아래와 같음
C:(생략)\node_modules\mongodb\lib\operations\insert.js:50
return callback(new error_1.MongoServerError(res.writeErrors[0]));
^
MongoServerError: E11000 duplicate key error collection: Gaein_Gwaje.comments index: commentId_1 dup key: { commentId: null }
at C:(생략)\node_modules\mongodb\lib\operations\insert.js:50:33
at C:(생략)\node_modules\mongodb\lib\cmap\connection_pool.js:331:21
at C:(생략)\node_modules\mongodb\lib\sdam\server.js:207:17
at handleOperationResult (C:(생략)\node_modules\mongodb\lib\sdam\server.js:335:20)
at Connection.onMessage (C:(생략)\node_modules\mongodb\lib\cmap\connection.js:206:9)
at MessageStream.<anonymous> (C:(생략)\node_modules\mongodb\lib\cmap\connection.js:61:60)
at MessageStream.emit (node:events:513:28)
at processIncomingData (C:(생략)\node_modules\mongodb\lib\cmap\message_stream.js:124:16)
at MessageStream._write (C:(생략)\node_modules\mongodb\lib\cmap\message_stream.js:33:9)
at writeOrBuffer (node:internal/streams/writable:392:12) {
index: 0,
code: 11000,
keyPattern: { commentId: 1 },
keyValue: { commentId: null },
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.16.0
2. 원인
이 문제는 스키마 설정 파일에서 수정한 내용을 MongoDB에서 인지하지 못한 것이 원인
나의 경우 스키마의 항목들 중 unique: true 옵션을 넣어줬다가 제거하였음
그 뒤 새로운 항목을 추가하려하면 MongoDB는 여전히 해당 항목이 유일한 값을 가져야한다고 판단하여
에러를 발생시키고, mongoose와의 연결을 끊어버림
3. 해결 방법 - mongodb 재연결
문제가 발생하는 테이블, 즉 수정된 스키마를 사용하여 접근하는 DB 테이블을 DROP, 삭제하고 재연결한다.
하지만 이 경우 DB 테이블에 등록하였던 내용도 전부 사라지므로
개발 중인 경우에만 하도록 하고 실제 서비스인 경우에는 절대 하지 말도록 하자
'공부 > node.js' 카테고리의 다른 글
.toHexString() (0) | 2023.06.19 |
---|---|
node.js mongoose 시간 적는 법 (0) | 2023.06.19 |
과제 기록 - Node.js, express, MongoDB, mongoose, AWS EC2 (0) | 2023.06.18 |
mongoose의 __V 필드 (0) | 2023.06.15 |
에러 기록 - MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 (0) | 2023.06.15 |