简体   繁体   English

Javascript-从mongodb的多个集合中收集数据,然后合并到数组中

[英]Javascript - Collect data from mongodb from multiple collections then merge into array

I want to fetch the newest object from multiple collections and save all into an array with collection name as key and the newest object as value. 我想从多个集合中获取最新对象,然后将所有对象保存到一个数组中,集合名称为键,最新对象为值。

How can I achieve this sequentially or async? 我怎样才能顺序地或异步地做到这一点?

        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);

The log at the end gives me an empty array. 最后的日志给了我一个空数组。

Looks like an async issue to me. 对我来说似乎是一个异步问题。 You can wrap your code in a function and return the promise chain all the way down. 您可以将代码包装在一个函数中,并一直返回承诺链。 This should give you the full array. 这应该给您完整的阵列。 Then use it as you need. 然后根据需要使用它。

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

You could try using async/await as: 您可以尝试使用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);
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM