简体   繁体   中英

How to query multiple values for a given key in firebase

I attempted to use an 'OR' || statement in the equalTo() method, but this does not seem to work. Do I have to make a separate call for each value or is there a way to make conditional queries in firebase?

export const startSetContent = () => {
  return (dispatch, getState) => {
    const ref = database.ref("content");
    return ref
      .orderByChild("category")
      .equalTo('one-act-play' || 'ten-min-play' || 'full-length-play')
      .once('value')
      .then(snapshot => {
        const content = [];
        snapshot.forEach(childSnapshot => {
          content.push({
            id: childSnapshot.key,
            ...childSnapshot.val()
          });
        });
        dispatch(setContent(content));
      });
  };
}; 

What you typed there was a logical OR that JavaScript the programming language interprets. The result of the expression:

'one-act-play' || 'ten-min-play' || 'full-length-play'

is going to be simply:

'one-act-play'

So, Firebase Realtime Database will not see what you're trying to tell it.

Firebase Realtime Database has no concept of a kind of query that has ORs in it. You will have to query each type of thing separately and merge them together in your code as needed.

There is no concept of doing that you are asking for. You can do a turn around in which you can get the values on basis of one filter one-act-play using equalTo and rest you can filter on user end like:

export const startSetContent = () => {
  return (dispatch, getState) => {
    const ref = database.ref("content");
    return ref
      .orderByChild("category")
      .equalTo('one-act-play')
      .once('value')
      .then(snapshot => {
        const content = [];
        Object.keys(snapshot.val()).map(k => {
        if(k == 'ten-min-play' || k == 'full-length-play'){
        snapshot.forEach(childSnapshot => {
          content.push({
            id: childSnapshot.key,
            ...childSnapshot.val()
          });
        });
        }
        dispatch(setContent(content));
      });
  };
}; 

Or you can use library made to fulfil this kind of requirement Querybase

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