mongoose-encryption
mongoose-encryption copied to clipboard
Yield to select option in schema
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 !
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
- do this in every query
- add to your schema
_ct: {
type: Buffer,
select: false
}
- modify the schema similarly after adding the plugin
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
Sounds great!
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()