简体   繁体   中英

OR queries in Firebase

I am trying to build a message system. I am planning on having a collections of messages and then querying messages based on sender and receivers. In order to do so I need to query for example: all messages that are sent by Bob and received by Tony and all messages that were sent by Tony and received by Bob. I am quite unclear about how to do this "or" statement. As of now I have

MessageRef.once('value', function(dataSnapshot) {
  console.log(dataSnapshot.val());
});

which return all messages. I could then do a forEach but it seems not very efficient. Would you guys have any suggestions?

Also, do you have thoughts on wether my model to build that message system is good vs having chat rooms for example.

Thank you

Firebase currently can only query on a single child property. So if you want to query multiple properties, you'll have to combine them into one:

Messages
  -DFHJ3498ua
    from: Tony
    to: Bob
    from_to: Tony_Bob
    message: "Hello Bob, this is Tony"
  -DFHJ3598uz
    from: Bob
    to: Tony
    from_to: Bob_Tony
    message: "Hello Tony, What can I do for you?"
  -EFHJ3498ua
    from: Tony
    to: Bob
    from_to: Tony_Bob
    message: "Can you help me with this Firebase query?"

You can then query for messages from Bob to Tony using:

var ref = new Firebase('https://your.firebaseio.com/Messages');
var query = ref.orderByChild('from_to').equalTo('Bob_Tony');
query.on('value', function(snapshot) {
  console.log(snapshot.val()); // all messages from Bob to Tony
});

In a chat-like application, you might want to consider actually using the sender-receiver pair as the key:

Messages
  from_Bob_to_Tony
    -DFHJ3598uz
      from: Bob
      to: Tony
      message: "Hello Tony, What can I do for you?"
  from_Tony_to_Bob
    -DFHJ3498ua
      from: Tony
      to: Bob
      message: "Hello Bob, this is Tony"
    -EFHJ3498ua
      from: Tony
      to: Bob
      message: "Can you help me with this Firebase query?"

With this data structure you won't have to run a query to get the relevant messages, but can do a direct lookup.

var ref = new Firebase('https://your.firebaseio.com/Messages');
var query = ref.child('from_Bob_to_Tony');
query.on('value', function(snapshot) {
  console.log(snapshot.val()); // all messages from Bob to Tony
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM