mongoose-field-encryption icon indicating copy to clipboard operation
mongoose-field-encryption copied to clipboard

Model populate returns encrypted fields

Open ArielGavrielov opened this issue 4 years ago • 1 comments

I have thats schemas:

const schema1 = new mongoose.Schema({
    field1: String,
    field2: String
});

schema1.plugin(mongooseFieldEncryption, {
    fields: ['field1', 'field2'],
    secret: process.env.SECRET,
    saltGenerator: (secret) => secret.slice(0, 16)
});

const schema2 = new mongoose.Schema({
    fieldEncrypted: [{type: mongoose.Schema.Types.ObjectId, ref: 'schema1'}]
});

schema2.plugin(mongooseFieldEncryption, {
    fields: ['fieldEncrypted'],
    secret: process.env.SECRET,
    saltGenerator: (secret) => secret.slice(0, 16)
});
const Model = mongoose.model('schema2', schema2);

and when I run this line: Model.findOne({_id: '6151a9221e014f27a6398e96'}).populate('fieldEncrypted'); it return encrypted document of schema1. how can I do that it will return decrypted document?

thanks for answers.

ArielGavrielov avatar Sep 28 '21 16:09 ArielGavrielov

Hi @ArielGavrielov

Did you try just doing a findOne without the populate? As you can see from this test https://github.com/wheresvic/mongoose-field-encryption/blob/036917d580e0d43c28f3331d0025af439d6ee18c/test/test-db.js#L297, findOne works normally as is.

If you want to use populate you can also perhaps use the decryptSync static function to then decrypt the field?

wheresvic avatar Oct 01 '21 07:10 wheresvic