Mongoose getters不在数组上工作

时间:2018-05-31 22:32:06

标签: node.js mongoose getter

我正在尝试通过Node.js api对mongodb集合进行一些加密。我遇到的解决方案似乎大部分工作,除了解密数组/嵌套文档中的任何数据。

到目前为止

代码..

memberModel.js

var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var crypto = require('crypto');
var connection = mongoose.connection;

var memberSchema = new Schema({
        title: {type: String, trim: true},
        firstname: {type: String, trim: true, get: decrypt, set: encrypt},
        lastname: {type: String, trim: true},
        address: [{
            addressRef: {type: String, trim: true},
            address1: {type: String, trim: true, get: decrypt, set: encrypt},
            postcode: {type: String, trim: true}
        }],
        ...
    }    , { collection: 'memberStage'});

memberSchema.set('toObject', { getters: true });
memberSchema.set('toJSON', { getters: true });

function encrypt(text){
    var cipher = crypto.createCipher('aes-256-cbc', 'test');
    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', 'test');
    var dec = decipher.update(text,'hex','utf8');
    dec += decipher.final('utf8');
    return dec;
};

module.exports = connection.model('memberStage', memberSchema);

member.js

member.find(query, function(err, member){
    res.status(200).json({
        meta : { success: true, message: 'Member Data'},
        data : member
    });
});

在数据库中,firstname和address.address1字段都按预期加密,但是从member.find调用返回的json返回解密的firstname,但address1字段仍然是加密的。

{
    "meta": {
        "success": true,
        "message": "Member Data"
    },
    "data": [
    {
        "_id": "5b1072549378101218c7039c",
        "title": "Mr",
        "firstname": "Test",
        "lastname": "Record",
        "address": [
            {
                "addressRef": "Home",
                "address1": "cfefdf8c4813fac7bcc34d919aa81483",
                "postcode": "PST CDE",
            }
        ]
    }],
    ...
}

非常感谢有关此问题的任何帮助。

1 个答案:

答案 0 :(得分:0)

地址应定义为架构,并对其getter应用相同的toObjecttoJSON处理。

var addressSchema = new Schema({
    addressRef: {type: String, trim: true},
    address1: {type: String, trim: true, get: decrypt, set: encrypt},
    postcode: {type: String, trim: true}
})

var memberSchema = new Schema({
        title: {type: String, trim: true},
        firstname: {type: String, trim: true, get: decrypt, set: encrypt},
        lastname: {type: String, trim: true},
        address: [addressSchema],
    }    , { collection: 'memberStage'});

addressSchema.set('toObject', { getters: true });
addressSchema.set('toJSON', { getters: true });

memberSchema.set('toObject', { getters: true });
memberSchema.set('toJSON', { getters: true });