简体   繁体   中英

Mongoose Middleware findOneAndUpdate Issue

I have used aes-256 to encrypt my values and saved in DB. I have used pre and post mongoose middleware to encrypt before POST and decrypt before GET. I have a scenario to findOneAndUpdate. For that I need to decrypt the mongoose value of the condition but I have no idea how to do it.

Encrypt POST data

userSchema.pre('save', function (next) {
  var data = Encrypt(this);
this.phone = data.phone //asded324ffdsf
}

Decrypt GET data

userSchema.post('findOne', function (document) {
  var data = Decrypt(document);
  if(document.phone){
    document.phone = data.phone; //123456780
  }
});

Requirement

user.findOneAndUpdate({phone:'1234567890'},{ $set: { pwd_token: random } }); //Query fails as the number is asded324ffdsf

How do I decrypt the phone number from my DB and compare here with the given number?

What should I do in userSchema.pre('findOneAndUpdate', function (document) {}?

Please note that you cannot access the document being updated in pre('findOneAndUpdate') query middleware. In order to access the document, you need to execute an explicit query for the document.

Refer to the documentation for more info: https://mongoosejs.com/docs/middleware.html#notes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM