简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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