0

I'm trying to update my Firebase data but I can't seem to quite get it.

Here is my JSON tree:

{
"users" : {
"K1lQ2ALPQRM9SG3pPoZafHCF4Qg1" : {
  "budgets" : {
    "-Ky043hTLPVQ8E7Ji4v3" : {
      "amount" : 55,
      "category" : "sports & dance",
      "expenseName" : "registration fees",
      "finalPayment" : "none",
      "firstPayment" : "none",
      "hasDueDate" : false,
      "order" : 0,
      "ownerName" : "Savannah",
      "repeats" : "never",
      "totalNumberOfPayments" : 1
    },

As you can see, I'm using childByAutoID and so I have to do a query to find the node that I want.

So I used this code:

ref.child("budgets").queryOrdered(byChild: "ownerName").queryEqual(toValue: currentUserName).observeSingleEvent(of: .childAdded, with: { (snapshot) in
                snapshot.ref.updateChildValues(["expenseName" : self.expenseNameTextField.text!,
                                                "amount" : Int(self.expenseAmountTextField.text!)!])
})

But it only changes the first item in the JSON tree, and not the right one.

So this is what I need to do: I need to match three items from my JSON tree (currentUserName, category, and expenseName). Only when all three of those items match will I find a unique item. But when I try to query all three of those items, I get an error telling me I can't queryEqual(toValue:) more than once per call.

Here is that code I tried, and resulted in an error:

ref.child("budgets").queryEqual(toValue: currentUserName).queryEqual(toValue: expense?.category).queryEqual(toValue: expense?.expenseName).observeSingleEvent(of: .childAdded, with: { (snapshot) in
                snapshot.ref.updateChildValues(["expenseName" : self.expenseNameTextField.text!,
                                               "amount" : Int(self.expenseAmountTextField.text!)!])
})

So I know that code is no good.

The reason this is complex is because the "ownerName" has about 50 of these items, of which about 10 might belong to a certain "category", and so I can't just search by "category" or even by "expenseName" because another "category" may have an expense with that same name. I have to match the username, the category, AND the expenseName to make sure I'm updating the correct item.

So how do I do it?

Thanks!!

Phontaine Judd
  • 428
  • 7
  • 17
  • And yes, I've looked at the documentation as well as this link [https://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase] and its subsequent links. – Phontaine Judd Nov 03 '17 at 11:52
  • I'm thinking I'm going to have to rework my data structure to allow for more effective querying, rather than trying to figure out how to come up with a query for my particular data structure. Fit the structure to match the query, rather than fit the query to match the structure... – Phontaine Judd Nov 03 '17 at 18:56

0 Answers0