【问题标题】:How to chain methods dynamically in JavaScript如何在 JavaScript 中动态链接方法
【发布时间】:2020-11-25 10:58:44
【问题描述】:

我希望使用 Mongoose 填充文档的各种路径,但我找不到动态链接各种填充方法的方法。一次检索所有这些字段以提高性能非常重要。代码如下:

let fields = [path1, path2, ...]

let result = document.findById(id).populate(path1).populate(path2).populate(...)

你们中有人知道这种魔法吗?

【问题讨论】:

    标签: javascript mongodb mongoose methods populate


    【解决方案1】:
    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]);
    }
    

    【讨论】:

      【解决方案2】:

      我不确定它是否是你要找的:

      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(' '))

      【讨论】:

      • 嗯不会查询只保留最后一个查询的值。populate(field) 只填充一个字段?
      • 不,相当于.populate().populate()
      猜你喜欢
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 2015-05-08
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多