getMarkedItems.js

/**
 * Created by WORKER on 05-09-2015.
 */
var async = require("async");

/**
 * Build list of habits.
 * @param  {Object} options Input parameters
 */
function getMarkedItems(options) {
    var templateCode = options.data.templateCode || options.data.templates[0].templateCode;
    var data = {
        list: []
    };
    var items = [];
    var asyncTasks = [];

    // get mark items query
    var getMarkItemQuery = [];
    getMarkItemQuery.push({
        $match : {"templateCode": templateCode}
    });
    getMarkItemQuery.push({
        $project: {
            _id : 0,
            fields : 1
        }
    });

    // get mark items from TemplateClln
    options.DB.TemplateClln.aggregate(getMarkItemQuery, onComplete);

    function onComplete(err, snippets){
        if(err) { console.log(err); }
        else {
            console.log('get mark items from TemplateClln');
            console.log(snippets);
        }

        for(var snippet in snippets) {
            var item = snippets[snippet];
            (function (item) {
                asyncTasks.push(function(_callback){
                    processSnippets(item, _callback);
                })
            }) (item);
        }

        async.series(asyncTasks, function(){
            console.log(items);
            data.list = items;
            options.res.json(data);
        });
    }

    function processSnippets(item, _callback) {
        // for each item get the corresponding name from MarkClln
        console.log(item);
        var getNameFromIdQuery = [{$match : { _id: item.fields[0].name }}, {$project: { _id: 1, name: 1 }}];
        options.DB.MarkClln.aggregate(getNameFromIdQuery, function (err, snippets) {
            console.log('Item from MarkClln');
            if(err) { console.log(err); }
            else {
                console.log('for each item get the corresponding name from MarkClln');
                console.log(snippets);
            }
            
            if(snippets && snippets.length > 0) {
                item.name = snippets[0].name;
                item.id = snippets[0]._id;
                items.push(item);
            }
            _callback();
        });
    }
}

module.exports = getMarkedItems;