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

Yield to select option in schema

Open onemartini opened this issue 7 years ago • 4 comments

For my use case, I need to encrypt a single field of a document:

var User = mongoose.Schema({
  secret: {
    select: false
  }
})

As you can see, by using the select option, I'm trying to instruct mongoose by default not to return this field.

However, it looks like when i use mongoose-encryption, the decrypted secret is returned in queries.

Is this the intended behavior ?

Many thanks !

onemartini avatar May 16 '17 03:05 onemartini

I think this approaches being a bug, but I'm not sure how straightforward the fix would be. In order to ensure that when documents are re-saved, all appropriate fields are included in the encrypted block, and need to be stored somewhere on the document.

I think the easiest fix for your issue might be to deselect the ciphertext (_ct) from your query. That way, you could avoid having the deciphered fields added to your mongoose object, but note that you'll need to select _ct any time you'll want to modify secret via a subsequent save

To achieve this could either

  1. do this in every query
  2. add to your schema
_ct: {
  type: Buffer,
  select: false
}
  1. modify the schema similarly after adding the plugin

joegoldbeck avatar May 16 '17 05:05 joegoldbeck

Thanks for the quick reply. That solution works 👍
When I get a moment, I'll play around and see if I can propose a more seamless solution. cheers

onemartini avatar May 16 '17 06:05 onemartini

Sounds great!

joegoldbeck avatar May 16 '17 06:05 joegoldbeck

I would also upvote that enhancement so the plugin handles select: false properly. The workaround did work for me too though. Thanks. But it also required me to set _ac_as well. My model file has:

_ct: {
    type: Buffer,
    select: false
  },
  _ac: {
    type: Buffer,
    select: false
  }

Then when I want to select the encrypted fields I have to do this:

MyModel.find(query)
    .select('+_ct +_ac')
    .exec()

chipallen2 avatar Sep 15 '17 22:09 chipallen2