我目前正在使用NestJS,并在TypeORM中使用MongoDB,但我在Mongoose中找不到类似于.populate()方法的东西,有没有办法使用TypeORM,或者我应该坚持使用Mongoose?
例如,这是我用Express + Mongoose创建的路由,我想用NestJS +TypeORM重新创建它:
route.get('/:slug', async (req, res) => {
const collection = await Collection.findOne({slug: req.params.slug}).populate('products');
res.json(collection);
});发布于 2020-10-11 01:40:44
在TypeORM中,有一个名为relations的东西,您可以使用它来填充来自其他(相关)集合的文档。
下面是TypeORM文档中的一个示例:
createConnection(/*...*/).then(async connection => {
/*...*/
let photoRepository = connection.getRepository(Photo);
let photos = await photoRepository.find({ relations: ["metadata"] });
}).catch(error => console.log(error));你可以在TypeORM docs上阅读更多关于它的信息。
根据你在TypeORM中设计集合/模式的方式,你的查询可能是这样的,我没有尝试过这个查询,但你可以让它像这样工作:
Collection.find({slug: req.params.slug}, {relations : ['products']});注意,还有像.innerJoinAndSelect和.leftJoinAndSelect这样的函数,您可以将它们与QueryBuilder(.createQueryBuilder)一起使用,并填充来自其他集合的文档,比如mongoose .populate()
我建议您阅读TypeORM,这里也有许多示例,它将帮助您构建所需的查询。
https://stackoverflow.com/questions/64295578
复制相似问题