Search code examples
node.jsregexmongodbmongodb-querynode-mongodb-native

Mongo function to find if superstring exists in array. Nodejs,


A document in my mongo 'companies' collection looks like this:

{
    "companyName": "",
    "companyIcon": "",
    "domains": [
        "companyDomainA.com",
        "companyDomainB.dev"
    ],
    "allowSubDomains": true
}

In my application the user enters his/her email address. Using the Nodejs native mongo driver (https://mongodb.github.io/node-mongodb-native), I want to query (find) which company the user belongs to.

The problem is when the user enters the email as name@dept.companyDomainA.com. I want to be able to query and find the company document of the user based on his email (subdomained 0 or more levels), ie. if the superstring of a string exists in an array in mongo. (Caveat, I cannot store all the subdomains of the company as they are dynamic and can change at will)

Is there a regular expression way/db schema change way, to achieve this?

Thanks in advance!!


Solution

  • I would do it like this. First find the root domain from the email address. To do that I would split the email and fetch the domain first.

    const email = "name@dept.companyDomainA.com";
    const domain = email.split('@')[1]; // dept.companyDomainA.com
    

    Now fetch the host (companyDomainA.com) from it. Follow this link.

    So, I have found the root domain which is companyDomainA.com. Now run the find query.

    db.collection('documents').find({"domains": "companyDomainA.com"});
    

    I didn't test this code.