Felipe Sikansi
Felipe Sikansi

Reputation: 73

TypeORM FindById doesn't work with MongoDB

I'm trying to use TypeORM with MongoDB and express but I'm having problems with the basic stuff.

I just created a controller with basic CRUD operations for an entity. The methods save, findAll and find by Filter works ok, but I can't make the methods that require an mongo id work.

router.get("/", async(req: Request, res: Response) => {
    const investmentRepository = getMongoRepository(Investment);

    const investments = await investmentRepository.find();
    res.send(investments);
});

router.get("/:id", async(req: Request, res: Response) => {
    const investmentRepository = getMongoRepository(Investment);
    const investment = await 
    investmentRepository.findOneById(req.params.id);
    if (!investment) {
        res.status(404);
        res.end();
    }
    res.send(investment);
});

The second method is always returning 404. For example, this is an entity returned on get all "investment/"

{
    "id": "59dfd8cadcbd9d1720457008",
    "name": "Teste LCI",
    "startDate": 1466305200,
    "numberOfDays": 365,
    "type": "LCI_LCA"
}

If I try to send a request for this specific object calling

investment/59dfd8cadcbd9d1720457008

the response is always 404.

The same behavior happen with the delete method, raising an exception

Cannot find entity to remove by a given id

I also tried to convert the string to ObjectID using:

new ObjectID(req.params.id);

but it fails with the error ObjectID is not a constructor.

Upvotes: 7

Views: 8050

Answers (2)

Demaman
Demaman

Reputation: 21

If you are importing from typeorm that might occur, you need to use:

import { ObjectId } from 'mongodb'

Here is an example :

import { Injectable, NotFoundException } from '@nestjs/common';
import { TaskStatus } from './task-status.enum';
import { CreateTaskDto} from './dto/create-task.dto';
import { GetTasksFilterDto } from './dto/get-tasks-filter.dto';
import { TaskRepository } from './dto/task.respository';
import { InjectRepository } from '@nestjs/typeorm';
import { Task } from './entities/task.entity';
import { ObjectId} from 'mongodb';

@Injectable()
export class TasksService {
  constructor(
    @InjectRepository(Task)
    private tasksRepository: TaskRepository
  )
  {}

  async getTaskById(id: ObjectId): Promise<Task> {
    console.log(`Finding task with id '${id}'`);
    const found = await this.tasksRepository.findOne({
      where: { _id: new ObjectId(id) }
    });

    console.log(found);
    if (!found) {
      throw new NotFoundException(`The task with '${id}' does not exist`);
    }
    return found;
  }

Upvotes: 2

J Livengood
J Livengood

Reputation: 2738

If you're receiving the error ObjectId is not a constructor it is because you forgot to require it in your file. All you need is:

const ObjectId = require('mongodb').ObjectId;

Upvotes: 9

Related Questions