admin管理员组

文章数量:1318156

I'm trying to lazy load firebase items to later on load more of them whenever user reaches end of div container. When i remove .endAt() and .startAt() i'm receiving the 15 items though they are not beeing incremented and it's stuck at these 15 items.

When i keep .endAt() and .startAt() i'm receiving firebase warning Using an unspecified index. Consider adding ".indexOn": "title" at /items even though .indexOn is set. I'm confused by that warning. Thanks in advance for any help.

Firebase structure

{
  "items" : {
    "-Kk6aHXIyR15XiYh65Ht" : {
      "author" : "joe", 
      "title" : "Product 1"
    },
    "-Kk6aMQlh6_E3CJt_Pnq" : {
      "author" : "joe",
      "title" : "Product 2"
    }
  },
  "users" : {
    "RG9JSm8cUndpjMfZiN6c657DMIt2" : {
      "items" : {
        "-Kk6aHZs5xyOWM2fHiPV" : "-Kk6aHXIyR15XiYh65Ht",
        "-Kk6aMTJiLSF-RB3CZ-2" : "-Kk6aMQkw5bLQst81ft7"
      },
      "uid" : "RG9JSm8cUndpjMfZiN6c657DMIt2",
      "username" : "joe"
    }
  }
}

Security rules

{
  "rules": {
    ".read": true,  
    ".write": "auth != null",  
    "users":{
      "$uid": {
        ".write": "$uid === auth.uid"
        "items":{
          ".indexOn": "title",
          "$itemId": {
            "title": {".validate": "...}
            "type": {".validate": "...}
            }
          }
        }
      }
    }
  }
}

Code structure for lazy load

let _start = 0,
    _end = 14,
    _n = 15;

function lazyLoadItems(){
  firebase.database().ref('items')
        .orderByChild('title')
        .startAt(_start)
        .endAt(_end)
        .limitToFirst(_n)
        .on("child_added", snapshot=> console.log(snapshot.val()));
  _start += _n;
  _end += _n;
}

I'm trying to lazy load firebase items to later on load more of them whenever user reaches end of div container. When i remove .endAt() and .startAt() i'm receiving the 15 items though they are not beeing incremented and it's stuck at these 15 items.

When i keep .endAt() and .startAt() i'm receiving firebase warning Using an unspecified index. Consider adding ".indexOn": "title" at /items even though .indexOn is set. I'm confused by that warning. Thanks in advance for any help.

Firebase structure

{
  "items" : {
    "-Kk6aHXIyR15XiYh65Ht" : {
      "author" : "joe", 
      "title" : "Product 1"
    },
    "-Kk6aMQlh6_E3CJt_Pnq" : {
      "author" : "joe",
      "title" : "Product 2"
    }
  },
  "users" : {
    "RG9JSm8cUndpjMfZiN6c657DMIt2" : {
      "items" : {
        "-Kk6aHZs5xyOWM2fHiPV" : "-Kk6aHXIyR15XiYh65Ht",
        "-Kk6aMTJiLSF-RB3CZ-2" : "-Kk6aMQkw5bLQst81ft7"
      },
      "uid" : "RG9JSm8cUndpjMfZiN6c657DMIt2",
      "username" : "joe"
    }
  }
}

Security rules

{
  "rules": {
    ".read": true,  
    ".write": "auth != null",  
    "users":{
      "$uid": {
        ".write": "$uid === auth.uid"
        "items":{
          ".indexOn": "title",
          "$itemId": {
            "title": {".validate": "...}
            "type": {".validate": "...}
            }
          }
        }
      }
    }
  }
}

Code structure for lazy load

let _start = 0,
    _end = 14,
    _n = 15;

function lazyLoadItems(){
  firebase.database().ref('items')
        .orderByChild('title')
        .startAt(_start)
        .endAt(_end)
        .limitToFirst(_n)
        .on("child_added", snapshot=> console.log(snapshot.val()));
  _start += _n;
  _end += _n;
}
Share Improve this question edited May 14, 2017 at 20:48 nehel asked May 14, 2017 at 12:15 nehelnehel 8853 gold badges17 silver badges32 bronze badges 6
  • You're querying /items, while you added an index to /users/$uid/items. – Frank van Puffelen Commented May 14, 2017 at 14:17
  • Hmm, yeah, though I want to list all items from all users, so querying /users/$uid/items without uid won't do the job. And adding .indexOn('items') in "rules" doesn't make sense. Could it be badly structured rules then? – nehel Commented May 14, 2017 at 14:53
  • That's impossible to say with what you shared. A minimal snippet of the JSON might help. You can get this by clicking the "Export JSON" link in your Firebase Database console. – Frank van Puffelen Commented May 14, 2017 at 15:31
  • Where items === decks. pastebin./wskVaNPy – nehel Commented May 14, 2017 at 15:39
  • I added the JSON to the question. But there is no /items in there. Please provide a single MCVE (read the link on why this is a more efficient way to get help than the back-and-forth we've been having). – Frank van Puffelen Commented May 14, 2017 at 17:37
 |  Show 1 more ment

2 Answers 2

Reset to default 8

You're misunderstanding how Firebase queries work. It's easiest to see if you use hard-coded values:

firebase.database().ref('items')
    .orderByChild('title')
    .startAt(0)
    .endAt(14)
    .limitToFirst(15)

There is no item with title=0 or title=14, so the query doesn't match anything.

Firebase Database queries match on the value of the property you order on. So when you order by title the values you specify in startAt and endAt must be titles. E.g.

ref.child('items')
   .orderByChild('title')
   .startAt("Product 1")
   .endAt("Product 1")
   .limitToFirst(15)
   .on("child_added", function(snapshot) { console.log(snapshot.val()); });

See for the working sample of this: http://jsbin./hamezu/edit?js,console

To implement pagination, you'll have to remember the last item of the previous page and pass that in to the next call: startAt(titleOfLastItemOnPreviousPage, keyOfLastItemOnPreviousPage).

startAfter is the last element

each time you have to send the last element:

const lastAlert = querySnapshot.docs[querySnapshot.docs.length - 1]

here an example:

export const fetchAlerts = (createdForId, startAfter) => {
  return new Promise((resolve, reject) => {
    firebase
    let query = firebase
      .firestore()
      .collection('alerts')
      .where('generated_for.uid', '==', createdForId)
      .where('read', '==', false)
      .orderBy('created_at', 'desc')
      .limit(25)
    if (startAfter) {
      query = query.startAfter(startAfter)
    }

    query
      .get()
      .then(querySnapshot => {
        const lastAlert = querySnapshot.docs[querySnapshot.docs.length - 1]
        const alerts = querySnapshot.docs.map(doc => ({
          ...doc.data(),
          uid: doc.id,
        }))
        resolve(alerts)
        resolve({ alerts, lastAlert })
      })
      .catch(error => {
        console.log(error.message)

本文标签: javascriptFirebase lazy loadStack Overflow