Reputation: 2875
I'm trying to create a query string, so the response from Firebase only returns the rows with corresponding userId
(Not in top level).
The goal is to only get the orders for the user who currently logged in.
My Javascript object is like this:
const order = {
itemId: "9T9WvJBbHiQpqyWdhBO0yX7lRny1"
price: 5.3,
customer: {
userId: "-L9EyOPFB2PnyAPFUH9M",
name: "demo user",
address: "some place in earth",
}
}
In Firebase, I have rules like this:
{
"rules": {
"orders": {
".read": "auth != null",
".write": "auth != null",
".indexOn": ["userId"]
}
}
}
However, this is obviously not working out, since the index is pointing at top level.
Here is the URL I created for the API call:
const queryParams = `?auth=${token}&orderBy="userId"&equalTo="${userId}"`;
axios
.get('/orders.json' + queryParams)
.then(res => {
// get orders for the currently logged-in user
})
.catch(err => {
console.error(err);
});
If I move userId
one level up, this works completely fine, but customer and authenticated user are using same ID, so I rather keep them in one object.
Is it possible to query data with nested index in Firebase?
If so, what rules and query string should I use?
Upvotes: 0
Views: 168
Reputation: 600116
You're looking to order on orderBy="customer/userId"
.
You'll also need to define the index on that nested field, which is done like this:
{
"rules": {
"orders": {
".read": "auth != null",
".write": "auth != null",
".indexOn": ["customer/userId"]
}
}
}
Just quickly confirmed that last one against Tom's answer here.
Upvotes: 3