2

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 Answers1

0

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

Usama Masood
  • 141
  • 5
  • Can you please show me some examples of how to use it for decryption? I am not able to find proper solutions so. Thanks – Harshal Faldu Jun 22 '22 at 08:19
  • First, if you're not fimiliar with aggregation and how it works [explore here](https://mongoosejs.com/docs/api/aggregate.html). Then, with a `$function` pipeline, you can simply write a js function which would take arguments from query, decrypt them and return back to query, and then you can use another pipeline after it for your filters (most likely `$match` pipeline) – Usama Masood Jun 22 '22 at 08:54
  • Thanks for the explanation, I am familiar with aggregation functions and their pipeline. I am not familiar with `$function` pipeline. Here is the implementation I have done using `$function` in aggregation `{ $addFields: { decryptedValue: { $function: { body: function(email){return fieldEncryption.decrypt(email, process.env.SECRET_KEY);}, args: ["$email"], lang: "js" }}}},` fieldEncryption => **mongoose-field-encryption**. – Harshal Faldu Jun 22 '22 at 09:04
  • But I am getting the error `PlanExecutor error during aggregation:: caused by:: ReferenceError: fieldEncryption is not defined` while executing it. – Harshal Faldu Jun 22 '22 at 09:04
  • make sure the mongodb version you're using is min 4.4 – Usama Masood Jun 22 '22 at 09:05
  • Yes, I am using mongoDB above 5.0 version – Harshal Faldu Jun 22 '22 at 09:07
  • great. Make sure if `fieldEncryption` service being injected – Usama Masood Jun 22 '22 at 09:09
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/245811/discussion-between-harshal-faldu-and-usama-masood). – Harshal Faldu Jun 22 '22 at 09:09