0

In my Node API with MongoDB, I added a search feature to allow a client to search the profile collection for other users' profiles. At this time my search functionality takes in the query 3 params: first name (fn), last name (ln) and company (cp).

The results are from single param or from the combination of those 3. For now, it is the exact match like if I search fn=joe I get as results all profile with Joe.

My goal is to be able to find also writing like J or Jo becasue in the front end will be implemented a system to live search so when a user is starting typing the results come ups. I need to modify my search to match the requirements but I don't have much knowledge in Mongo to do so.

My search feature:

const SearchController = {
    async getQuery(req, res) {
        try {
            // Set
            const set = {};

            // query params
            const { fn, ln, cp } = req.query;

            // RexExp to allow upper and lower case in the search
            // First name
            if (fn) {
                set["firstname"] = new RegExp(
                    "\\b" + req.query.fn + "\\b",
                    "i"
                );
            }

            // Last name
            if (ln) {
                set["surname"] = new RegExp("\\b" + req.query.ln + "\\b", "i");
            }

            // Company
            if (cp) {
                set["experience.company"] = new RegExp(
                    "\\b" + req.query.cp + "\\b",
                    "i"
                );
            }

            //
            if (Object.keys(set).length != 0) {
                // Searching the profile results
                const searchResult = await Profile.find(set, (err, doc) => {
                    return doc;
                });

                // No results
                if ((await searchResult).length === 0)
                    throw new ErrorHandlers.ErrorHandler(
                        404,
                        `Query do not provided any result`
                    );

                // Response
                res.status(200).json(searchResult);
            } else {
                // No result
                throw new ErrorHandlers.ErrorHandler(
                    404,
                    "Query do not provided any result"
                );
            }
        } catch (err) {
            res.status(500).json({ message: err.message });
        }
    }
};  

The URL I'm composing to search:

URL/search?cp=...&fn=...&ln=... 

As mentioned I can search only one or a combination between the three params and it is no case sensitive. I can use G as g.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jakub
  • 2,367
  • 6
  • 31
  • 82

0 Answers0