mongoose-encryption and updating objects mongoose-encryption and updating objects mongoose mongoose

mongoose-encryption and updating objects


As you quoted, the documentation for mongoose-encryption clearly tells that it does not work for update.

https://github.com/joegoldbeck/mongoose-encryption

Mongoose update hook is little tricky as well.

What you can do potentially is model your collection in such a way that fields which needs to be encrypted are a separate collection altogether and in the paren collection just link them via ids.

Person = {  _id: <ObjectId>  name: Blah  ..  ..  documents: [    { 'doc_id': <ObjectId1> },    { 'doc_id': <ObjectId2> },  ]}Documents = [{    "_id" : <ObjectId1>,    "_ac" : BinData(0,"YdJjOUJhzDWuDE5oBU4SH33O4qM2hbotQTsF6NzDnx4hWyJfaWQiLCJfY3QiXQ=="),    "_ct" : BinData(0,"YaU4z/UY3djGCKBcgMaNIFHeNp8NJ9Woyh9ahff0hRas4WD80V80JE2B8tRLUs0Qd9B7IIzHsq6O4pYub5VKJ1PIQA+/dbStZpOH/KfvPoDC6DzR5JdoAu+feU7HyFnFCMY81RZeJF5BKJylhY1+mG4="),    "__v" : 0}......]

This will increase code reuse as well.


I have implemented an strategy that i don´t think it is most efficient but it works.

I need to have all my data in database encrypted so i can´t use the above approach.

What i did is to create an update function that finds the document i want to modify, then i construct a new schema object and assing the _id of the found document to the new object.Then i delete the original document and after that save the new object wich has the original _id. The only problem i found is that mongoose throw an error because duplicated _id that is printed in the console but it still works and _id aren´t duplicated.

I have tried replacing the_id and traking the document with another property but it still throw that error, anyway data is stored as expected.

exports.update= (req, res, next) => {  Solucion.findOne({_id: req.params.id})  .then(document => {    if (!document) {      res.status(404).json({        message: notFoundMessage,        data: null,        error: null      })    } else {      const solucion = new Solucion({        _id: document._id,        identificacion: document.identificacion,        informacion: document.informacion,        estado: req.body    })    Solucion.deleteOne({_id: document._id})      .then(() => {return solucion.save()})      .then(result=> {        return res.status(201).json({          message: editedSavedMessage,          data: result,          error: null        });       })      .catch(err => {        errorHandler.errorHandler(err, res);      })    }  })};

UPDATE 29/07/2020I have found that if you use the save method using the same _id, data is stored encrypted but Mongo creates your schema structure but with all values set to null.

Beyond that it seems to work as expected as data is not visible in DB.