I am using the mongoose-field-encryption package which allows me to encrypt and decrypt the data before storing and accessing it. The encrypted fields are name, email and number.
I need to implement search functionality for the encrypted fields directly in the query itself.
import crypto from 'crypto'
import mongoose, { Schema } from 'mongoose'
const mongooseFieldEncryption = require("mongoose-field-encryption").fieldEncryption;
import { encryptionSecret } from '../../config'
const userSchema = new Schema({
email: {
type: String,
match: /^S+@S+.S+$/,
required: true,
unique: true,
trim: true,
lowercase: true,
index: true,
},
name: {
type: String,
trim: true
},
contactNumber: {
type: String,
default:null
}
}, {
timestamps: true
})
userSchema.plugin(mongooseFieldEncryption, {
fields: ["email", "contactNumber"],
secret: encryptionSecret,
saltGenerator: function (secret) {
return "1452819847269312";
},
});
const model = mongoose.model('User', userSchema)
export const schema = model.schema
export default model
import { User } from '.'
export const getUsers = async (req, res) => {
try {
let { email } = req.query
if (email) {
const messageToSearchWith = new User({ email });
messageToSearchWith.encryptFieldsSync();
query.email = messageToSearchWith.email
}
let users = await User.find(query)
return res.status(200).json(users)
} catch (error) {
console.log('error in getting users', error)
}
}
Above is the model and the function. Encrypted data is stored in the database but I am not able to search on the same.
I tried logging the encrypted fields, the email being saved and the encrypted email in the logs are coming out to be different. These should be same for the exact match.
I need to search over the encrypted email
Please let me know what needs to be modified to make this work as per expectations.