如果最近两小时没有记录,则返回0,javascript逻辑

时间:2015-04-03 12:14:16

标签: javascript for-loop

我希望一周内每两小时返回一次平均记录。我有开始和日期时间戳,我返回了计算的平均值。但是我必须检查是否有6小时的记录,然后在这种情况下每小时必须返回0。

我所做的一切如下:

var average = [];

// db query with start-end 
db.table.find(query_criteria).sort({"date_time": 1}).toArray(function() {

forEach(function() {

// got record

}

// calculated average for tow hours
average.push(/*average for tow hours*/);

res.send( average );

});

结果看起来像

average: 2450,
time: "Sun Mar 22 2015 02:00:00",
hour: "2:00"

average: 2780,
time: "Sun Mar 22 2015 04:00:00",
hour: "4:00"

average: 2360,
time: "Sun Mar 22 2015 08:00:00",
hour: "8:00"

请注意,第6小时没有任何内容。我想检查两小时之间是否没有记录,然后发送0平均值。

请帮助制定此检查的逻辑。

/***********************************************************************
 ***********************************************************************
 ** MongoDb
 ** Will scan MongoDb for weekly temperature average graph.
 **
 ** @author     Created by Sajjad
 ** @date       18/03/15
 ** @access     private
 ***********************************************************************
 ***********************************************************************/
var helper = require('../helpers/jsHelper.js');


/**
 * Return average of temp from DB
 * @param      event from service call
 * @return
 */
module.exports.temp_graph_by_week = function (event, resp) {

    // Selecting table from DB in this case "gateway_status"
    var gateway_status = db.collection("gateway_status");

    // This will contain records from DB
    var temp_record = [];

    // This will send average record and other data of device to client side
    var temp_list_data = {};

    //gateway_id & device_id start date and end date from client side
    var gateway_id = parseInt(event.params.gateway_id);
    var device_id = parseInt(event.params.device_id);
    var start_date = parseInt(event.params.start_date);
    var end_date = parseInt(event.params.end_date);

    temp_list_data.device_id = device_id;
    temp_list_data.gateway_id = gateway_id;
    temp_list_data.data = [];

    // query criteria
    var query_criteria;

    if (start_date && end_date != null) {
        query_criteria = { "date_time": { "$gte": start_date, "$lte": end_date},
            "device_id": device_id, "gateway_id": gateway_id };

        // Getting records from DB
        gateway_status.find(query_criteria).sort({"date_time": 1}).toArray(function (err, res_data) {

                if (err) {

//                    resp.send(err);

                } else {

                    // will contain indoor temperature average
                    var temp_average = 0;

                    // will contain set point average
                    var setPoint_average = 0;

                    // sum of indoor temperature
                    var temp_sum = 0;

                    // sum of set point temperature
                    var setPoint_sum = 0;

                    // for graph weekly bases
                    var hours_difference = 120;

                    // Counting the quantity of records
                    var record_count = 0;

                    // Date time of first record
                    var first_time = null;

                    // Time difference of records
                    var time_difference = null;

                    var record_day = '';

                    var record_check = 0;

                    res_data.forEach(function (data) {

                        // Local object
                        var device_record = {};

                        if (data.data != null && data.data.length != null) {
                            var json_data = data.data;

                            // for indoor temp
                            for (var i = 0; i < json_data.length; i++) {
                                if (json_data[i].r == 203) {

                                    //Pass in the data of indoor temp and time
                                    device_record.indoor = json_data[i].v;
                                    device_record.time = data.date_time;

                                }

                                // for set point temp
                                else if (json_data[i].r == 1004) {

                                    //Pass in the data of set point
                                    device_record.setPoint = json_data[i].v;

                                }
                            }
                        }

                        // Start time
                        if (first_time == null) {
                            first_time = new Date(device_record.time);
                        }

                        // Time difference of records
                        time_difference = helper.MinutesBetweenTwoDates(new Date(device_record.time), first_time);

                        // If we have all records of last two hours
                        if (time_difference >= hours_difference) {

                            record_check = 2;
                            if(new Date(device_record.time).getHours() > record_check){
                                console.log(new Date(device_record.time).getHours());
                            }
                            // Date time of first record
                            first_time = new Date(device_record.time);

                            // Calculating average
                            temp_average = Math.round(temp_sum / record_count);
                            setPoint_average = Math.round(setPoint_sum / record_count);


                            var temp_Date = new Date(device_record.time);
                            temp_Date.setMinutes(0);
                            temp_Date.setSeconds(0);
                            temp_Date.setMilliseconds(0);

                            //  console.log(temp_Date,temp_Date.getDay());
                            if (temp_Date.getDay() == 1) {
                                record_day = "Monday";
                            } else if (temp_Date.getDay() == 2) {
                                record_day = "Tuesday";
                            } else if (temp_Date.getDay() == 3) {
                                record_day = "Wednesday";
                            } else if (temp_Date.getDay() == 4) {
                                record_day = "Thursday";
                            } else if (temp_Date.getDay() == 5) {
                                record_day = "Friday";
                            } else if (temp_Date.getDay() == 6) {
                                record_day = "Saturday";
                            } else if (temp_Date.getDay() == 0) {
                                record_day = "Sunday";
                            }

                            // Push average data of month for sending to client side
                            temp_list_data.data.push({"indoor": temp_average,
                                "time": temp_Date.toString(),
                                "day": record_day,
                                "hour": temp_Date.getHours().toString() + ":00",
                                "setPoint": setPoint_average
                            });

                            // Set them for next two hours
                            record_count = 0;
                            temp_sum = 0;
                            setPoint_sum = 0;
                        }
                        else {

                            //keep adding values in sum till two hours are filled
                            temp_sum += device_record.indoor;
                            setPoint_sum += device_record.setPoint;

                            //keep counting records
                            record_count++;
                        }
                    });
                }
                resp.send(temp_list_data);
            }
        );
    }

};

1 个答案:

答案 0 :(得分:1)

如果我理解的是正确的,那么你希望用一些数据填充一些时隙,如果这些时隙中没有数据,你想用0填充它们。你可以预先用0填充时隙然后用来自db的数据重新填充它们。

//data with record to send
var average_data = [];

//array with time slots
//differ in start date and end date
var array_with_dates = [1,2,3,4,5,6,7,8,9,10];

// Pre fill time slots with 0
for (var j = 0; j < array_with_dates.length; j++){

    //required JSON
    var data_for_day = {}; 

    data_for_day.day = array_with_dates[i];
    //pre fill with 0
    data_for_day.average = 0;

    //push to the data
    average_data.push(data_for_day);
}

//Now refill them with the data from db
db.table.find(query_criteria).sort({"date_time": 1}).toArray(function(err, record) { 

record.forEach(function() {

// got record
var record_amount = record.amount;
var current_day = record.day;

//find the right pre filled record and update its avg
for (var i = 0; i < average_data.data.length; i++) {
    if (average_data[i].day == current_day) {

        average_data[i].ctr++;
        average_data[i].sum += (device_record.indoor);
        average_data[i].average = Math.round(average_data[i].sum / average_data[i].ctr);
    }
}

res.send(average_data);

});