Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 811
Felipe Sikansi Avatar asked Oct 13 '17 00:10

Felipe Sikansi


1 Answers

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;
like image 118
J Livengood Avatar answered Nov 15 '22 06:11

J Livengood