Mongoose getter 和 setter 无法正常工作

Nag*_*dra 2 mongoose node.js mongoose-schema node-crypto

我正在尝试在插入 MongoDB 之前和之后加密和解密值。我正在使用猫鼬模式并调用 get 和 set 方法进行加密和解密。通过调用 set 方法对数据进行加密,但是在从 MongoDB 检索数据时它没有解密。这是我的架构和加密解密方法:

var tempSchema = new Schema({    
  _id: {type: Schema.ObjectId, auto: true},
  name:{type: String},
  sample_details:{
    _id: false,
    objects: [{
      object_key:{type: String},
      object_value:{type: String, get:decrypt, set:encrypt}
    }],
    type_params:[{
      type_key:{type: String},
      type_value:{type: String, get:decrypt, set:encrypt}
    }],
    test_body:{type: String, get:decrypt, set:encrypt}
  }}, {
  toObject : {getters: true, setters: true},
  toJSON : {getters: true, setters: true}
});
Run Code Online (Sandbox Code Playgroud)

以下是使用的加密和解密方法:

function encrypt(text){
     var cipher = crypto.createCipher('aes-256-cbc', secret_key);
     var crypted = cipher.update(text,'utf8','hex');
     crypted += cipher.final('hex');
     return crypted;
}

function decrypt(text){
     if (text === null || typeof text === 'undefined') {
         return text;
     };
     var decipher = crypto.createDecipher('aes-256-cbc', secret_key);
     var dec = decipher.update(text, 'hex', 'utf8');
     dec += decipher.final('utf8');
     return dec;
}
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏,object_value 和 type_value 在保存到 db 时被加密,但在从 db 检索时没有解密。

yay*_*aya 10

我遇到了类似的问题,它对我有用:

  1. 将“转换为 json 时使用 getter”选项添加到 Schema,例如:

new mongoose.Schema({...}, {toJSON: {getters: true}})

  1. 将猫鼬结果映射到 json,例如:

Products.find({}).then(a => console.log(a.map(p => p.toJSON())))

(说明:似乎 mongoose 在转换为 json 时只使用 getter,并且默认情况下禁用。)