How can we implement search functionality on the encrypted data in mongoDB database?

868 Views Asked by At

I have used the mongoose-field-encryption package which allows me to encrypt and decrypt the data before storing and accessing it. But I need to implement search functionality for the encrypted fields directly in the query itself.

The fields are email id, name, mobile number, address, etc.

1

There are 1 best solutions below

8
Usama Masood On

You can use aggregate query's $function feature to decrypt data within the query and apply filters. Explore $function here. Something like

Model.aggregate([
  {
    addFields: {
      decryptedEmail: {
        {
          $function: {
          body: function decrypt(email){ ... },
          args: ["$emailColumnName"],
          lang: "js"
        }
      }
    }
  },
  {
    $match: { decryptedEmail: emailToMatch }
  }
])

what it does is, create a new field named decryptedEmail and the value of it is being computed by a decrypt function, and then we are filtering out the email we want