'How to get decrypted values in the aggregation result by the using of getter and setter in node.js

var mongoose = require("mongoose");
const Schema = mongoose.Schema;
let CryptoJS = require("crypto-js");

function encrypt(text) {
  try {
    let ciphertext = CryptoJS.AES.encrypt(
      text,
      process.env.MONGOOSE_PII_KEY
    ).toString();
    console.log("encryptencrypt", encrypt);
    return ciphertext;
  } catch (err) {
    console.log("error", err);
  }
}


function decrypt(text) {
  try {
    let bytes = CryptoJS.AES.decrypt(text, process.env.MONGOOSE_PII_KEY);
    var originalText = bytes.toString(CryptoJS.enc.Utf8);
    return originalText;
  } catch (err) {
    console.log("error", err);
  }
}

var callSchema = new mongoose.Schema(
  {
    from: { type: String, default: null, set: encrypt, get: decrypt },
    to: { type: String, default: null, set: encrypt, get: decrypt },
  },
  {
    versionKey: false,
    toObject: { getters: true, setters: true },
    toJSON: { getters: true, setters: true },
    runSettersOnQuery: true,
  }
);

module.exports = mongoose.model("Call", callSchema);

I am using encryption techniques (getters and setter). In normal mongo query (like find({from : "+91232323233"})) working fine but when i try to get "from" value from phone number then i'm getting encrypted value.

Is that any solution to get decrypted value by the using of mongo aggregation.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source