wheresvic / mongoose-field-encryption

A simple symmetric encryption plugin for individual fields. Dependency free, only mongoose peer dependency.
MIT License
74 stars 32 forks source link

How to remove encrypted field? #53

Closed sean-hill closed 3 years ago

sean-hill commented 3 years ago

Hi! I'd like to remove an encrypted field from a document, but I'm not sure how to do it. In this case the inputs key would be the encrypted field. This is my best try so far:

const doc = await userModel.create({ inputs: { username: 'secret' } })

await userModel.updateMany({}, { inputs: {} })
// or
await userModel.updateMany({}, { $unset: { inputs: '' } })

const updatedDoc = await userModel.findById(doc._id)
console.log(updatedDoc)

// Spits out a doc where the `inputs` field is still an object with the username available.
wheresvic commented 3 years ago

Hi @sean-hill ,

Unfortunately the plugin does not execute on updateMany, See mongoose documentation here: https://mongoosejs.com/docs/middleware.html#notes

You will need to manually do a find - get the document, make your changes and then save it back again. A bit annoying yes, but it is a solution :)

sean-hill commented 3 years ago

@wheresvic sounds good. I'll redo my implementation to allow for that 😄

So something like this?

const doc = await model.findById(id)
doc.inputs = undefined
await doc.save()
wheresvic commented 3 years ago

@sean-hill

Yes, you might want to set it to an empty string to indicate that it was once filled but this is of course dependent on the design of your object :).

Cheers,