如何在 JavaScript 中动态链接方法
How to chain methods dynamically in JavaScript
我想用 Mongoose 填充文档的各种路径,但找不到动态链接各种填充方法的方法。一次性检索所有这些字段对于提高性能非常重要。这是代码:
let fields = [path1, path2, ...]
let result = document.findById(id).populate(path1).populate(path2).populate(...)
你们知道这样的魔法吗?
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]);
}
我不确定这是否是您要找的:
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(' '))
我想用 Mongoose 填充文档的各种路径,但找不到动态链接各种填充方法的方法。一次性检索所有这些字段对于提高性能非常重要。这是代码:
let fields = [path1, path2, ...]
let result = document.findById(id).populate(path1).populate(path2).populate(...)
你们知道这样的魔法吗?
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]);
}
我不确定这是否是您要找的:
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(' '))