Mongoose:在一次调用中填充多个查询 [英] Mongoose: multiple query populate in a single call
问题描述
在Mongoose中,我可以使用查询填充来在查询后填充其他字段。我也可以填充多个路径,例如
In Mongoose, I can use a query populate to populate additional fields after a query. I can also populate multiple paths, such as
Person.find({})
.populate('books movie', 'title pages director')
.exec()
然而,这会产生在书籍上查找收集标题,页面和导演的字段 - 以及查找收集标题,页面和导演字段的电影。我想要的只是从书本中获取标题和页面,从电影中获取导演。我可以这样做:
However, this would generate a lookup on book gathering the fields for title, pages and director - and also a lookup on movie gathering the fields for title, pages and director as well. What I want is to get title and pages from books only, and director from movie. I could do something like this:
Person.find({})
.populate('books', 'title pages')
.populate('movie', 'director')
.exec()
给了我预期的结果和查询。
which gives me the expected result and queries.
但是有没有办法让第二个片段的行为使用类似的单行像第一个片段的语法?原因是我想以编程方式确定populate函数的参数并将其输入。我不能为多个填充调用执行此操作。
But is there any way to have the behavior of the second snippet using a similar "single line" syntax like the first snippet? The reason for that, is that I want to programmatically determine the arguments for the populate function and feed it in. I cannot do that for multiple populate calls.
推荐答案
在查看了mongoose的源代码之后,我解决了这个问题:
After looking into the sourcecode of mongoose, I solved this with:
var populateQuery = [{path:'books', select:'title pages'}, {path:'movie', select:'director'}];
Person.find({})
.populate(populateQuery)
.execPopulate()
这篇关于Mongoose:在一次调用中填充多个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!