0%

连表查询populate用法

mongodb中连表查询很方便,mongoose中的populate可以很方便的实现

如下:我们有两个Model,User和File,User的avatar属性是关联着File的id:

现在,这两张表是关联表,查询User的时候如何关联查询出File中的所有属性呢?
如下是一个查询接口的实现,根据user name查询出user和关联的File所有数据:

返回数据如下:

可见,File通过连表查询populate查询出了File所有的数据。
populate函数还有其他参数:

表示只返回File的name属性,不返回其他属性。