Search Flow in MERN Stack

Viewed 135

First of all, I tried searching a lot but I am not able to find any resource which satisfies my need. I know there might be some answers already, if you know one please help with the link.

I know how to show search suggestions but I don't know how to show full search results when someone clicks on a search suggestion. Like how to do that in MERN stack with an example if possible.

I need a solution that best fits my scenario:

I have three models,

  • tags - holds tags

  • categories - holds categories

  • items - holds items data - has categories and tags both currently, I am not storing references to categories and tags table instead storing a copy directly inside items

  • Now, I basically want to search the items having the specific categories and tags when someone searches for a keyword.

  • What I am doing currently is, I search for tags matching the keyword, then categories, then taking out their _id(s) and finding that in items collection

    const tags = await Tags.find(
     { tag: { $regex: category.toString(), $options: "i" } },
     { projection: { createdBy: 0 } });
    const categories = await Categories.find(
     { category: { $regex: category.toString(), $options: "i" } },
     { projection: { createdBy: 0 } });
    
    
    
    const tagsIdArray = tags.map((item) => new ObjectId(item._id));
    const catIdArray = categories.map((item) => new 
                       Object(item._id));
    $match: {
    $and: [
     {
       $or: [
         { "tags._id": { $in: [...tagsIdArray] } },
         { "category._id": { $in: [...catIdArray] } },
       ],},],},
    

And I know that this is not the best way, and it takes a lot of time to search for a given keyword.

Please suggest me schema structure and way to implement search with suggestions.

0 Answers
Related