【问题标题】:Javascript - Collect data from mongodb from multiple collections then merge into arrayJavascript - 从多个集合中收集来自 mongodb 的数据,然后合并到数组中
【发布时间】:2019-05-11 14:29:45
【问题描述】:

我想从多个集合中获取最新的对象并将所有对象保存到一个数组中,其中集合名称为键,最新的对象为值。

我怎样才能实现顺序或异步?

        let dat = ["test", "test2"];
        let merged = [];

        dat.map((collName) => {
          const promise = new Promise((resolve, reject) => {
            db.collection(collName).find().sort({ timestamp: -1 }).limit(1).forEach((d) => {
              resolve(d);
            });
          })
          .then((result) => {
            merged.push(result);
          });

        console.log(merged);

最后的日志给了我一个空数组。

【问题讨论】:

    标签: javascript node.js mongodb merge


    【解决方案1】:

    对我来说似乎是一个异步问题。您可以将代码包装在一个函数中,并一直返回承诺链。这应该给你完整的数组。然后根据需要使用它。

    let dat = ["test", "test2"]
    
    const mergeData = async () => {
      const promises = await dat.map(async (collName) => {
        let value = ''
        await new Promise((resolve, reject) => {
          db.collection(collName).find().sort({ timestamp: -1 }).limit(1).forEach((d) => {
            resolve(d)
          })
        }).then(response => {
          value = response
        })
        return value
      })
      const results = await Promise.all(promises)
      
      console.log('results: ', results)
    }
    mergeData()

    【讨论】:

    • console.log(mergeData()) 返回 [ undefined, undefined ]
    • @J.Doe 抱歉,我已经进行了编辑,希望它现在对你有用
    【解决方案2】:

    您可以尝试使用 async/await 作为:

    let dat = ["test", "test2"];
    
    const promises = dat.map(async (collName) => {
        try {
            const data = await db.collection(collName)
                 .find({})
                 .sort({ timestamp: -1 })
                 .limit(1)
                 .toArray();
            return data[0];
        } catch(err) {
            console.error(err);
        }
    });
    
    (async () => {
        const merged = await Promise.all(promises);
        console.log(merged);
    })();
    

    【讨论】:

    • console.log 打印 [ Promise { }, Promise { } ],我也尝试了 .then() 的 Promise 但它仍然无法解决
    • 您可以使用 Promise.all() 获得一个 Promise,当合并数组中的所有 Promise 都已解析时,该 Promise 将解析
    • 做到了!非常感谢,我也投了赞成票,但目前还没有记录
    猜你喜欢
    • 2013-04-26
    • 2016-09-27
    • 2021-11-04
    • 2021-10-30
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    相关资源
    最近更新 更多