这是我的firebase中的结构:
"receipts" : {
"-L7ug4xPoZYvk72Pynjh" : {
"date" : "18-2-2018",
"name" : "ABC",
"price" : 50,
"product" : "1122",
"quantity" : 1
},
"-L7ug5phx4x7OUA8Pyxa" : {
"date" : "18-3-2018",
"name" : "XYZ",
"price" : 50,
"product" : "1122",
"quantity" : 1
}
我正在使用angularfire 2版本4.0.0。我希望使用startAt
和endAt
以及orderByChild
"date"
的组合来限制结果。我使用以下代码,但它返回数据库中的所有数据:
getFullReceipts(dateFrom, dateTo) {
console.log(dateFrom); //dateFrom = 3-3-2018
console.log(dateTo); //dateTo = 31-3-2018
return this.afData.list('receipts', {
query: {
orderByChild: 'date',
startAt: dateFrom,
endAt: dateTo
}
});
}
此代码只返回一条日期为18-3-2018
的记录,但会返回所有记录。
答案 0 :(得分:0)
存储日期的字符串格式不容易排序。由于Firebase会对这些字符串进行字符串比较,因此它们与您的预期结果不符。如果我们在纯JavaScript中重现问题而不涉及Firebase,这是最容易看到的:
var dates = [
"18-2-2018",
"18-3-2018"
];
var dateFrom = "3-3-2018"
, dateTo = "31-3-2018"
;
dates.forEach(function(date) {
if (date < dateFrom) console.log(date+" is before "+dateFrom);
if (date > dateFrom) console.log(date+" is after "+dateFrom);
if (date < dateTo) console.log(date+" is before "+dateTo);
if (date > dateTo) console.log(date+" is after "+dateTo);
if (date >= dateFrom && date <= dateTo) console.log(date+" is within range");
});
&#13;
考虑将它们存储在ISO-8601 format中,例如2018-03-03
和2018-03-31
。或者将它们存储为时间戳,这些时间戳是数字(自纪元以来的毫秒数),并且不会出现此问题。
var dates = [
"2018-02-18",
"2018-03-18"
];
var dateFrom = "2018-03-03"
, dateTo = "2018-03-31"
;
dates.forEach(function(date) {
if (date < dateFrom) console.log(date+" is before "+dateFrom);
if (date > dateFrom) console.log(date+" is after "+dateFrom);
if (date < dateTo) console.log(date+" is before "+dateTo);
if (date > dateTo) console.log(date+" is after "+dateTo);
if (date >= dateFrom && date <= dateTo) console.log(date+" is within range");
});
&#13;