2
votes

I'm currently playing around with NestJS and am using MongoDB with TypeORM, and I couldn't find something similar to the .populate() method in Mongoose, is there a way to do it with TypeORM or should I stick to Mongoose?

For example, here is a route I created with Express + Mongoose, and I want to recreate it with NestJS + TypeORM:

route.get('/:slug', async (req, res) => {
    const collection = await Collection.findOne({slug: req.params.slug}).populate('products');

    res.json(collection);
});
1

1 Answers

1
votes

In TypeORM there is something called relations which you can use to populate the docs from other(related) collections.

Here is an example from TypeORM docs :

createConnection(/*...*/).then(async connection => {
 
    /*...*/
    let photoRepository = connection.getRepository(Photo);
    let photos = await photoRepository.find({ relations: ["metadata"] });
 
}).catch(error => console.log(error));

You can read more about it here on TypeORM docs.

According to how you design collection/schema in TypeORM, your query might look like this, i havent tried the query but you can make it work like this:

Collection.find({slug: req.params.slug}, {relations : ['products']});

Note, there are also functions like .innerJoinAndSelect and .leftJoinAndSelect which you can use with QueryBuilder(.createQueryBuilder) and populate documents from other collection just like mongoose .populate()

I suggest that you read the TypeORM, there are many examples given as well, it will help you build the kind of query you need.