How to chain methods dynamically in JavaScript
const result = fields.reduce((r, path) => r.populate(path), document.findById(id));
Or somewhat more verbosely:
let result = document.findById(id);for (let i = 0; i < fields.length; i++) { result = result.populate(fields[i]);}
I'm not sure if it's what you're looking for:
let query = document.findById(id)for (const field of fields) { query = query.populate(field)}const result = await query
if you want to go with ES6 .reduce():
const result = await fields.reduce((query, field) => query.populate(field), document.findById(id))
Edit:
From mongoose v3.6 you can use also .populate(fields.join(' '))