I have e-commerce project with multi product type, i got some problem when querying product search.

the collection on my db like this: - products_craft - products_fashion - products_travel - products_food

Currently i try .find() each collection and merge it.

My existing code

const searchString = 'some product'

const final result = []

const resultOne = await ModelOne.find({ title: searchString })
const resultTwo = await ModelTow.find({ title: searchString })
const resultThree = await ModelThree.find({ title: searchString  })


What the efficient, fast and best method for this problem ?

1 Answers

tom slabbaert On Best Solutions

This is the fastest Mongo related way, make sure the field is indexed.

i would also use something like bluebird to run all 3 searches simultaneously, that will save you alot of time.

it would look like this:

let Promise = require("bluebird");
const searchString = 'some product'

const final result = []
let results = Promise.all([ModelOne.find({ title: searchString }),
                           ModelTow.find({ title: searchString }),
                           ModelThree.find({ title: searchString })]);
return results.flat();

If you keep using your code result.push(resultOne) does not concat arrays but actually pushes the array as a whole, not sure you meant for this behavior.

Also note that if you do end up using bluebird you need to make sure your mongo/mongoose promises are a bluebird promise. depending what you use you should read further on how to do it.

for mongoose i add mongoose.Promise = Promise; after the import.