Reputation: 3466
I am using Express and Firebase Real time database Admin SDK to manage database. I need to get all the tickets whose status are pending
or open
from the logged in user, but I am not sure how to get this data and I am not finding the solution in the documentation. In SQL would be something like:
SELECT *
FROM tickets as t
INNER JOIN users as u
WHERE t.owner = u.id
AND (
status = 'pending'
OR status = 'open'
);
In case you need to see some code to understand what I am talking about this is what so far I've tried:
router.post('/', async (req: Request, res: Response) => {
const existingRef = database.ref('tickets')
.orderByChild('owner')
.equalTo(req.user.key)
.orderByChild('status')
.equalTo('open')
.orderByChild('status')
.equalTo('pending);
const existingSnapshot = await existingRef.on('child_added');
if (existingSnapshot.val() !== null) {
return res.json(existingSnapshot.val());
}
}
The previous code will return the tickets whose status are pending
and open
which does not make sense since there should be only one status per ticket.
So, what should I do? Thanks in advance
Upvotes: 1
Views: 788
Reputation: 26313
The Realtime Database can only query on one child field at a time, so the query you're proposing won't work. You'd need to filter the results after fetching them, something like:
const snap = await database.ref('tickets')
.orderByChild('user').equalTo(user.uid)
.once('value');
const out = {};
snap.forEach(t => {
if (['open','pending'].includes(t.child('status').val())) {
out[t.key] = t.val();
}
});
res.json(out);
You may want to consider using Cloud Firestore instead, as it can do more complex queries:
firebase.firestore().collection('tickets')
.where('user','==',user.uid)
.where('status','in',['open','pending'])
Upvotes: 1