使用mongoose保存数组数据的清洁代码

时间:2016-02-03 13:39:37

标签: javascript node.js mongodb mongoose

我创建了一个使用下面的逻辑将数据保存到mongoDB中的函数,但我真的很难重构代码并使其更清晰,有太多烦人的代码重复,我怎么能有DRY原则?

逻辑: 1.传入一个标志来决定是否在结束时关闭数据库连接。 2.根据传入的var saveArrayToDB = function(returnedArray, flagToCloseDBConnection) { var objectToSave, object, type = returnedArray[0].type, arrayToSave = []; if (type === 'user') { for (var i = 0; i < returnedArray.length; i++) { object = returnedArray[i]; objectToSave = new User({ fullName: object['full_name'], activatedAt: object['activated_at'], location: object['location'], timezone: object['timezone'], imageURL: object['mugshot_url'], stats: object['stats'] }); arrayToSave.push(objectToSave); } User.create(arrayToSave, function(err) { if (err) { console.log('err ' + err); } if(flagToCloseDBConnection) { mongoose.connection.close(); } }); } else if (type === 'group') { for (var j = 0; j < returnedArray.length; j++) { object = returnedArray[j]; objectToSave = new Group({ fullName: object['full_name'], createdAt: object['created_at'], stats: object['stats'], url: object['web_url'] }); arrayToSave.push(objectToSave); } Group.create(arrayToSave, function(err) { if (err) { console.log('err ' + err); } if(flagToCloseDBConnection) { mongoose.connection.close(); } }); } else { objectToSave = null; console.log('ERROR: unrecognized type in data. Not saved.'); } }; 创建不同的mongoDB模型并保存到DB中。

{{1}}

2 个答案:

答案 0 :(得分:1)

只需添加@JohnnyHK对您的问题发表评论,最好是在应用生命周期中保持您的mongoose连接处于打开状态。除此之外,你可以使用一些JavaScript函数,如 map() 来初始化数组,定义可以在create和map方法中重用的公共回调函数:

var saveArrayToDB = function(returnedArray, flagToCloseDBConnection) {
    var type = returnedArray[0].type,
        arrayToSave = [];

    var callback = function(err) {
        if (err) {  console.log('err ' + err); }
    };

    var newUser = function(u){
        return new User({
            fullName: u['full_name'],
            activatedAt: u['activated_at'],
            location: u['location'],
            timezone: u['timezone'],
            imageURL: u['mugshot_url'],
            stats: u['stats']
        });
    };

    var newGroup = function(g){
        return new Group({
            fullName: g['full_name'],
            createdAt: g['created_at'],
            stats: g['stats'],
            url: g['web_url']
        });
    };


    if (type === 'user') {      
        arrayToSave = returnedArray.map(newUser);       
        User.create(arrayToSave, callback);
    } else if (type === 'group') {
        arrayToSave = returnedArray.map(newGroup);
        Group.create(arrayToSave, callback);
    } else {
        console.log('ERROR: unrecognized type in data. Not saved.');
    }

};

答案 1 :(得分:1)

无需关闭连接。这是一个已经大大改进的版本:

var factories = {
    'user': {
        method: function(object){
            return {
                fullName: object['full_name'],
                activatedAt: object['activated_at'],
                location: object['location'],
                timezone: object['timezone'],
                imageURL: object['mugshot_url'],
                stats: object['stats']
            };
        },
        model: User
    },
    'group': {
        method: function(object){
            return {
                fullName: object['full_name'],
                createdAt: object['created_at'],
                stats: object['stats'],
                url: object['web_url']
            };
        },
        model: Group
    }
}

var saveArrayToDB = function(returnedArray) {
    var saveQueue=[],
        factory = factories[returnedArray[0].type];
    if(!factory){
        return console.log('ERROR: unrecognized type in data. Not saved.');
    }

    returnedArray.forEach(function(item){
        saveQueue.push(factory.method(item));
    });

    factory.model.create(saveQueue, function(err){
        if(err){
            console.log('err ' + err);
        }
    });
};

(您不需要传递文档实例,普通对象对于Model.create来说已经足够了)