富國滬深
2022-12-22 11:57:55
我正在尋找用 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
提交
取消