I am currently implementing a demo application to get to know the NestJS framework with mongoDB.
I am currently facing the following error message, which I cannot fix:
failed for value "1" at path "_id" for model "Player" + 40997ms CastError: Cast to ObjectId failed for value "1" at path "_id" for model "Player"
My controller looks like this:
@Controller('/players')
export class PlayersController {
constructor(private playersService: PlayersService) { }
@Get('/:id')
async getPlayer(@Res() res, @Param('id') id: number) {
const player = await this.playersService.getPlayer(id);
if (!player) throw new NotFoundException('Player does not exist!');
return res.status(HttpStatus.OK).json(player);
}
}
My service looks like this:
@Injectable()
export class PlayersService {
constructor(@InjectModel('Player') private readonly playerModel: Model<Player>) { }
async getPlayer(playerId: number): Promise<Player | undefined> {
const player = await this.playerModel.findById(playerId);
return player;
}
}
My DTO looks like this:
export class CreatePlayerDto {
readonly id: number;
readonly name: string;
readonly score: number;
readonly created_at: Date;
readonly is_deleted: boolean;
}
My model looks like this:
export class Player extends Document {
readonly id: number;
readonly name: string;
readonly score: number;
@Exclude() readonly createdAt: Date;
@Exclude() readonly isDeleted: boolean;
}
My mongoose schema looks like this:
export const PlayerSchema = new mongoose.Schema({
id: Number,
name: String,
score: Number,
createdAt: { type: Date, default: Date.now },
isDeleted: Boolean
});
Example mongoDB entry after typing db.players.find()
{ "_id" : ObjectId("5e5fccac9d16bf2d325cd57a"), "id" : 1, "name" : "Player One", "score" : 0, "createdAt" : "2020-04-03", "isDeleted" : false }
What am I doing wrong here or how can I fix this Error?