Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose encryption

How to encrypt the sub docs excluding specific fields in the sub docs?

I am trying to implement encryption on below schema using the mongoose-encryption plugin. My parent schema i.e. "parentSchema" gets encrypted, but not the child schema. I need to encrypt the "childSchema" and "childinformationSchema". What i am missing here?

var childinformationSchema = new Schema({
    otherwitnes: String,
    reportedemployOther: String,
    status: String,
    updateddate: Date,
    updatedby: String
});

childinformationSchema.plugin(encrypt, {
    key: encryptionKey,
    exclude: ['status', 'updateddate', 'updatedby']
});

var childSchema = new Schema({
    childdata: {
        childinformation: [childinformationSchema]
    }
});

childSchema.plugin(encrypt.encryptedChildren, {
    key: encryptionKey
});

var parentSchema = new Schema({
    practicename: String,
    createddate: Date,
    createdby: String,
    updateddate: Date,
    updatedby: String,
    patientrecordno: String,
    state: String,
    child: [childSchema]
});

 parentSchema.plugin(
    encrypt.encryptedChildren,
    { 
        key: encryptionKey,
        exclude: ['createddate', 'createdby', 'updateddate', 'updatedby', 'state', 'patientrecordno', 'child'] 
    }
);
like image 225
Praveen Avatar asked Apr 07 '26 01:04

Praveen


1 Answers

In your use case you have subdocuments of subdocuments. From some testing, Mongoose doesn't appear to fully support middleware on sub-subdocuments and so this plugin won't work without restructuring your schema some. This might be a good idea in general because MongoDB itself doesn't have full support for nested nested arrays.

Would it work if you referenced the children at one of the levels instead of including them directly as a subdoc? For example:

childinformationSchema.plugin(encrypt, {
    encryptionKey: encryptionKey,
    authenticationKey: authenticationKey, // latest version adds authentication
    excludeFromEncryption: ['status', 'updateddate', 'updatedby']
});

var childSchema = new Schema({
    childinformation: [childinformationSchema]
});

// because childSchema itself has encrypted children
childSchema.plugin(encrypt.encryptedChildren);

var parentSchema = new Schema({
    ...
    child: [type: mongoose.Schema.Types.ObjectId, ref: 'Child']
});

parentSchema.plugin(encrypt, { 
    key: encryptionKey,
    excludeFromEncryption: ['createddate', 'createdby', 'updateddate', 'updatedby', 'state', 'patientrecordno', 'child']
});

Similarly, you could leave childSchema nested directly inside parentSchema and include childinformationSchema by reference instead.

More details on using subdocuments with mongoose-encryption in the docs

Disclosure: I am the plugin author

like image 57
joegoldbeck Avatar answered Apr 09 '26 14:04

joegoldbeck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!