我假设您使用实时数据库;但是,我确信 Firestore 的设计/实现是相似的。
您可能需要考虑这样的替代结构:
statistics: {
unix_ts_for_sept_2016: {
unix_ts: unix_ts_for_sept_2016
hours:
},
unix_ts_for_oct_2016: {
unix_ts: unix_ts_for_oct_2016
hours:
},
unix_ts_for_nov_2016: {
unix_ts: unix_ts_for_nov_2016
hours:
}
[,...]
}
时间戳作为键允许您获取/设置任何单个月份,而时间戳作为子值允许您执行范围查询。
const path_to_statistics = 'statistics/';
const hours_field_name = 'hours';
const ts_field_name = 'unix_ts';
// Update the hours for a given month/yr in 'MM-DDDD' format
var update_hours = function(mm_dash_yyyy, delta_hours) {
const unix_ts = moment(mm_dash_yyyy, 'MM-YYYY').valueOf();
const path = path_to_statistics + unix_ts + '/' + hours_field_name;
const ref = firebase.database().ref(path);
var deferred = $q.defer();
ref.transaction(function(current) {
if (current !== null) { return current + delta_hours; }
return current;
}, function(error) {
if (error) { deferred.reject(error); }
else { deferred.resolve(); }
});
return deferred.promise;
};
// Returns sum of hours in a given date range.
var get_hours_in_range = function(start_mm_dash_yyyy, end_mm_dash_yyyy) {
const start_ts = moment(start_mm_dash_yyyy, 'MM-YYYY').valueOf();
const end_ts = moment(end_mm_dash_yyyy, 'MM-YYYY').valueOf();
const ref = firebase.database().ref(path_to_statistics);
const query = ref.orderByChild(ts_field_name).startAt(start_ts).endAt(end_ts);
var deferred = $q.defer();
query.once('value').then(function(snap) {
var hours = 0;
snap.forEach(function(child_snap) {
hours += child_snap.val()[hours_field_name];
});
deferred.resolve(hours);
}).catch(function(error) { deferred.reject(error); });
return deferred.promise;
};
//usage
update_hours('09-2016', 10).then(function() {
console.log('updated hours.');
}).catch(function(error) { console.error(error); })
get_hours_in_range('09-2016', '10-2016').then(function(hours) {
console.log(hours);
}).catch(function(error) { console.error(error); });