Home > database >  Firebase - search data by phone number
Firebase - search data by phone number

Time:07-29

I am making a site with a lesson schedule for teachers. For recording, a person indicates his phone number. I have been trying to find it by phone number for a long time, but it does not work.

Understandable database example

By phone number you need to find out all the days and hours when this number is used. I am trying to do it like this:

ref = db.ref("/user1/");
ref.orderByChild("Phone").equalTo(' 7 999 999 99 99').on("value", function(snapshot){
    console.log(snapshot.val());
});

null is displayed in the console

I almost got it. If you change ref to

ref = db.ref("/user1/28-07-2022");

then output to the console:

{
   '10-00': {
     Comment: 'DemoTest',
     Free: false,
     Name: 'Jack',
     Phone: ' 7 999 999 99 99',
     Time: '10-00'
   }
 }

But this method only looks for one day. And I want to search everywhere

CodePudding user response:

Firebase can only order/filter on a value at a fixed path under each direct child node of the location you query. So you can for example filter on the keys/dates right under user1, or you can search for the Phone value for a specific date, but you cannot search across all phone number for all dates, let alone for across all dates for all users.

If you want to allow that you'll need to either:

  • Maintain an additional flat list of time slots (for each user), for example putting the date as a property into each slot then, and query that.

      slots: {
        "2022-07-08T10:00": { ... },
        "2022-07-08T11:00": { ... },
        "2022-07-29T10:00": { ... },
        "2022-07-29T11:00": { ... }
      }  
    
  • Create a so-called reverse index, where you map from the phone number as a key back the dates/times for that number.

      phoneToSlots: {
        ' 7 999 999 99 99": {
          "2022-07-08T10:00": true
        }
      }
    
  • Related