Reputation: 438
Here is my database structure:
"current" : {
"-MPcUEyEdXiotnBybJFM" : {
"completed" : 123456789,
"completedBy" : "Mom",
"name" : "🍼 Babysit (2 hours)",
"repeats" : 12,
"startDate" : 1609144537,
"value" : 884
},
"-MPcUEyF9YsmQrGpt78Q" : {
"completed" : 1609144538,
"completedBy" : "Mom",
"name" : "🛠 Organize garage",
"repeats" : 6,
"startDate" : 1609144538,
"value" : 884
},
"-MPkV1sOlx3wNS8UvEqQ" : {
"name" : "🕸 Dust for cobwebs",
"repeats" : 1,
"startDate" : 1611957359,
"value" : 221
}
}
And here is my Firebase query:
static func deleteOldCompletedItems(completion: @escaping () -> Void) {
let previousPayday = FamilyData.calculatePayday().previous.timeIntervalSince1970
FB.ref
.child(FB.jobJar)
.child(FB.current)
.queryOrdered(byChild: FB.completed)
.queryEnding(atValue: previousPayday)
.observeSingleEvent(of: .value, with: { (snapshot) in
print(previousPayday)
guard snapshot.exists() else {
completion()
return
}
var deletedItemsCount = 0
for item in snapshot.children {
guard let snap = item as? DataSnapshot else { return }
snap.ref.removeValue { (_, _) in
deletedItemsCount += 1
if deletedItemsCount == snapshot.childrenCount {
completion()
}
}
}
})
}
And here is the data model:
struct JobJar {
var name: String
var value: Int
var repeats: Int
var startDate: Double
var completed: Double?
var completedBy: String?
}
Note that two of the parameters are optional: completed:
and completedBy:
.
I want to only get the items from my database that match the completed:
timestamp and that are more than a week old. Then I want to delete those items.
The code works fine for items that have a completed:
parameter.
But for some reason, my query is returning items that don't have the completed:
timestamp. In other words, my query is deleting the items that are more than a week old (good!) but also all the other items that don't have any timestamp. It's deleting too much stuff.
Why? Is it because the completed:
parameter is optional?
How do I query the database so that I ONLY get items that have the completed:
parameter that are more than a week old?
Upvotes: 2
Views: 55
Reputation: 598728
I'm surprised that the database returns items that don't have the property you order on. But as a workaround, you can probably add a queryStarting(atValue: 1)
to the query.
Upvotes: 1