我正在寻找用 Mongoose 填充文档的各种路径,但我找不到动态链接各种填充方法的方法。一次性检索所有这些字段对于提高性能非常重要。这是代码:let fields = [path1, path2, ...]let result = document.findById(id).populate(path1).populate(path2).populate(...)你们有人知道这样的巫术吗?
2 回答

眼眸繁星
TA贡献1873条经验 获得超9个赞
const result = fields.reduce((r, path) => r.populate(path), document.findById(id));
或者更详细一点:
let result = document.findById(id);
for (let i = 0; i < fields.length; i++) {
result = result.populate(fields[i]);
}

慕的地8271018
TA贡献1796条经验 获得超4个赞
我不确定这是否是您要找的:
let query = document.findById(id)
for (const field of fields) {
query = query.populate(field)
}
const result = await query
如果你想使用 ES6 .reduce():
const result = await fields.reduce((query, field) => query.populate(field), document.findById(id))
编辑:
从 mongoose v3.6 你也可以使用.populate(fields.join(' '))
添加回答
举报
0/150
提交
取消