简体   繁体   中英

Autocomplete search with multiple fields in nodeJS

I'm using nodejs, mongodb and want to build an autocomplete search like Facebook. when typing a keyword, it needs to search groups, users, pages etc.

For example, I have two collections: users and companies. They both have a name field. When someone type a keyword in the search bar, I will provide suggestions containing both the users and companies that have the entered text. Using stuff like User.find(name:"typed name") and Company.find("name:"typed name"). The part I'm stuck on is how to suggest names from both collections, yet have the results look like it's from a single collection.

How can I combine the results from multiple collections into a single result collection?

You could build a "search" method in your Controllers / Services layer by means of which you execute the searches of each collection (User.find, Company.find, etc) sequentially and independently. You must concatenate the results into a new entity that could be named "SuggestionDTO" applying the Data Transfer Object pattern. You would only use this new entity to present / transfer the 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