【问题标题】:nodejs return array of objects from mongodbnodejs从mongodb返回对象数组
【发布时间】:2018-07-18 14:34:10
【问题描述】:

我想返回一个对象数组,其中包含集合名称及其每个对象的文档计数,例如 [ { col:col1, count:1 } , { col:col2, count:2} ]

目前,通过将查询解析为承诺,我只返回每个集合的文档计数数组。

我的主要问题是从 .map 函数返回一个对象,因为它必须返回 Promise。

db.listCollections()
  .toArray()
  .then(collections => {
    let promises = collections.map(col => {

      // Cannot return {col,count} here :/
      return db.collection(col["name"]).countDocuments();
    });
    return Promise.all(promises);
  })
  .then(res => console.log(res));

【问题讨论】:

    标签: javascript node.js mongodb promise


    【解决方案1】:

    或者,将async 函数传递给collections.map(),您可以返回{ col, count }

    db.listCollections()
      .toArray()
      .then(collections => {
        const promises = collections.map(async col => {
          return {
            col: col.name,
            count: await db.collection(col.name).countDocuments()
          };
        });
        return Promise.all(promises);
      })
      .then(res => { console.log(res); });
    

    【讨论】:

      【解决方案2】:

      修复它

      return Promise.all([
          db.collection(col["name"]).countDocuments(),
          Promise.resolve(col["name"])
      ]);
      

      【讨论】:

      • Promise.resolve() 周围的 col["name"] 不是必需的,你也不需要计算属性来做到这一点,所以简化的答案是 return Promise.all([db.collection(col.name).countDocuments(), col.name])
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      相关资源
      最近更新 更多