NodeJS Mongoose getter和setter无法正常工作

iswrvxsc  于 2023-03-17  发布在  Node.js
关注(0)|答案(2)|浏览(109)

我尝试在插入MongoDB之前和之后对值进行加密和解密。我使用mongoose模式并调用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}
});

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

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;
}

如有任何帮助,我们将不胜感激,object_value和type_value在保存到数据库时被加密,但在从数据库检索时未被解密。

ohfgkhjo

ohfgkhjo1#

我也遇到过类似的问题,它对我很有效:
1.在Schema中添加“转换为json时使用getters”选项,例如:
new mongoose.Schema({...}, {toJSON: {getters: true}})
1.将mongoose结果Map到json,如下所示:
Products.find({}).then(a => console.log(a.map(p => p.toJSON())))
(说明:似乎mongoose只在转换到json时使用getter,并且默认情况下禁用它。)

hwazgwia

hwazgwia2#

我找到了this issue,这可能是您的问题所在。
如果objectstype_params是作为对象(而不是数组)* 传递的,getter就可以正常工作。
我创建了一个代码片段来测试您的代码(希望我理解正确)。encrypt()decrypt()是简化的,因为它们在问题中不重要:

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},
    runSettersOnQuery: true
});

var tempModel = mongoose.model('tempmodel', tempSchema);

var dataToSave = {name: 'Name',
                  sample_details: {
                    objects: { //just an object here, no array
                            object_key: 'ObjKey',
                            object_value: 'ObjVal'
                        },
                    type_params: { //just an object here, no array
                            type_key: 'TypeKey',
                            type_value: 'TypeVal'
                        },
                    test_body: 'TestBody'
                  }
};

var doc = new tempModel(dataToSave);

doc.save().then((doc) => {
    console.log(util.inspect(doc, false, null));
    mongoose.disconnect();
});

function encrypt(text){
    return text + '_enc';
}

function decrypt(text){
    return text + '_dec';
}

控制台中的结果:

{ sample_details:
  { objects: { object_key: 'ObjKey', object_value: 'ObjVal_enc_dec' }, //'_dec' postfix is the result of decript()
    type_params: { type_key: 'TypeKey', type_value: 'TypeVal_enc_dec' }, //'_dec' postfix is the result of decript()
    test_body: 'TestBody_enc_dec' },
  name: 'Name',
  _id: 5aaec6c2b8f0701c9476420f,
  __v: 0,
  id: '5aaec6c2b8f0701c9476420f' }

相关问题