강의

멘토링

커뮤니티

Cộng đồng Hỏi & Đáp của Inflearn

Hình ảnh hồ sơ của minj96
minj96

câu hỏi đã được viết

NestJS phụ trợ vững chắc, từ cơ bản đến nâng cao

API giao tiếp giữa mèo với mèo (nhận xét, lượt thích) - hoàn thành dịch vụ

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

Viết

·

1.6K

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 깃허브 주소 남깁니다!
mongodbnodejsexpressNestJSssr

Câu trả lời 2

0

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

0

amamov님의 프로필 이미지
amamov
Người chia sẻ kiến thức

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

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

Hình ảnh hồ sơ của minj96
minj96

câu hỏi đã được viết

Đặt câu hỏi