inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

탄탄한 백엔드 NestJS, 기초부터 심화까지

고양이끼리 소통 API (댓글, 좋아요) - 서비스 완성

Cast to ObjectId failed for value라는 에러 발생합니다!

1654

김민재

작성한 질문수 5

1

수강생분들의 질문을 기다립니다!
- 에러에 해당하는 질문은 "에러가 발생한 상황에 대한 충분한 설명", "에러 메세지", "에러가 난 코드 스크린샷"을 함께 첨부해주세요.
- 언어에 해당하는 질문은 구글링 및 서치 후에 구체적으로 질문해주시면 좋습니다.
- 간단한 진로 및 방향성에 대한 질문은 메일로 보내주세요.
- 패키지 버전 관리은 실무 환경과 트랜드에 맞추어 강의를 업데이트 하고 있습니다. 강의를 그대로 따라갔는데 에러가 발생한다면 패키지 버전을 강의에서 사용하는 버전과 동일하게 맞춰주세요!
- 강의 노트, QA 목록, 공지 사항을 먼저 확인해주세요.
- 논리적이고 구체적인 질문은 학습 효과를 올립니다 :)
 
comments.service
 
import { CatsRepository } from 'src/cats/cats.repository';
import { Comments } from './../comments.schema';
import { CommentsCreateDto } from './../dto/comments.create.dto';
import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

@Injectable()
export class CommentsService {
constructor(
@InjectModel(Comments.name)
private readonly commentsModel: Model<Comments>,
private readonly catsRepository: CatsRepository,
) {}
async getAllComments() {
try {
const comments = await this.commentsModel.find();
return comments;
} catch (error) {
throw new BadRequestException(error.message);
}
}

async createComment(id: string, commentData: CommentsCreateDto) {
try {
const targetCat = await this.catsRepository.findCatByIdWithOutPsw(id);

const { contents, author } = commentData;
const validatedAuthor = await this.catsRepository.findCatByIdWithOutPsw(
author,
);
const newComment = new this.commentsModel({
author: validatedAuthor._id,
contents,
info: targetCat._id,
});
return await newComment.save();
} catch (error) {
throw new BadRequestException(error.message);
}
}
async plusLike(id: string) {
try {
const comment = await this.commentsModel.findById(id);
comment.likeCount += 1;
return await comment.save();
} catch (error) {}
}
}
 
{
"success": false,
"timestamp": "2022-02-22T10:53:22.484Z",
"statusCode": 400,
"message": "Cast to ObjectId failed for value \"66213fe65d99f4623dae55787\" (type string) at path \"_id\" for model \"Cat\"",
"error": "Bad Request"
}
 
jwt.strategy에서는 payload에 있는 sub.id 역시 스트링으로 잘 넘어갔는데 왜 쿼리 id는 오류가나는지 궁금합니다
 
https://github.com/minjamie/NestJS-A-to-Z 깃허브 주소 남깁니다!

mongodb nodejs express NestJS ssr

답변 2

0

김택수

질문자님 혹시 이 문제 해결하셨나요? 저는 해결이 안되네요..

0

윤상석

안녕하세요! 단순히 타입핑 문제입니다.

몽구스 메소드에 id를 넘길때 `id as ObjectId ` 방식으로 타입 케스팅하여 넘겨주시면 됩니다. 만일 깐깐하게 타입 체킹을 하고 싶으시면 string 대신에 ObjectId 타입으로 타이핑하시길 권장드립니다!

프로젝트 환경 세팅할 때 최신 노드 버젼을 사용하시는 분들은 참고하셔도 좋을 것 같아요~

2

77

1

DTO에 대한 질문

1

86

2

백엔드 MVC에서 View의 역할은 무엇인가요?

1

91

2

추가 업데이트 관련 건

0

89

2

nest js 버전문제

0

79

2

mongdb 스키마 공식 문서와 형태가 다른 이유 궁금합니다.

0

103

1

라인 끝에 에러 표시(eslint) 때문에 구글 찾아 보니.

0

72

1

전체 고양이 조회 라우터 중 error.message 오류

0

66

1

캡슐화 추가 설명 중 단일책임원칙 관련 질문

0

103

0

42강 고양이끼리 소통 댓글 구현 중 Schema hasn't been registered for model 'comments' 에러 해결

0

80

1

채팅 이슈

0

132

1

모듈이 더 이상 지원하지 않는답니다

0

205

1

오류가 있습니다

0

105

1

import 에서 오류가 납니다

0

126

1

이런 오류가 나옵니다

0

99

1

에러가 발생합니다

0

108

1

프론트 에러 뜨는데 수정 안해주시나요

0

154

1

emit() broadcast.emit() 질문있습니다

0

100

1

서버연결이 안됩니다.

1

402

1

[PM2][ERROR] Command not found

0

516

1

S3에 업로드까지는 성공했는데 사진이 나오지 않습니다.

0

242

1

error_code : Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.ts(2339)

0

598

1

jwt를 따로 연습하고 있는데 env를 못읽는 것 같습니다.

0

316

2

Ec2로 안하시는 이유가 있을까요?

0

341

1