简体   繁体   中英

How to query (find) from multiple Mongo collections at once and combine results

I want to get the results from multiple collections that have no relations to one another. I am creating a search engine that will take a term, pass to the back end and do a query/find on multiple collections (Books, Authors, Tags) and combine them into one object to return. There are no foreign keys relation for any of these collections, I just want to find results matching the text term.

However I am having difficulties finding the right solution. The models I am using to do the find queries returns a promise so I want to find a way to properly retrieve since it is asynchronous.

I've tried a Promise.all approach but it ended up failing with a 500 error because I know I did this wrong.

router.post('/', (req, res, next) => {
   var results = {}, term = req.body.term;

   var authors = Authors.find().or([
                           {first_name: new RegExp(term, 'i')},
                           {last_name: new RegExp(term, 'i')}
                       ]);
   var books = Books.find().or([
                           {title: new RegExp(term, 'i')},
                           {author: new RegExp(term, 'i')},
                           {description: new RegExp(term, 'i')}
                       ]);
   var tags = Tags.find().or([
                           {name: new RegExp(term, 'i')}
                       ]);

   Promise.all([authors, books, tags])
       .then(results => res.send(results));        
});

I want to grab the results from all the collections and be able to combine it into a single JSON object. Something like:

{
    books: {
          // results from Books collection
    },
    authors: {
          // results from Authors collection
    },
    tags: {
          // results from Tags collection
    },
}

use async await, and ideally to make a router.get request instead of router.post

router.get('/', async (req, res) => {
   let term = req.body.term;

   let authors = await Authors.find().or([
                       {first_name: new RegExp(term, 'i')},
                       {last_name: new RegExp(term, 'i')}
                   ]);
   let books = await Books.find().or([
                       {title: new RegExp(term, 'i')},
                       {author: new RegExp(term, 'i')},
                       {description: new RegExp(term, 'i')}
                   ]);
   let tags = await Tags.find().or([
                       {name: new RegExp(term, 'i')}
                   ]);
    let results = {
                   authors,
                   books,
                   tags
                  }  

     res.send(results));        
   });

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