Home > OS >  How can i do the pagination without modifying the limit?
How can i do the pagination without modifying the limit?

Time:05-28

How can I get the same elements what the user asked?

for example if I do this, the user asked 30

query = query.limit(30)
const qSnap = await query.get(); // 30 objects

qSnap.docs.forEach((doc) => { // i will get fewer than 30
  const item = doc.data().data.tools.find(t => t.trait === 'color1' && t.value == 'red');
  console.log(item)
})

i need to filter because i have this structure:

name:carla
data: {
   sign: "carly",
   tools: [{trait:color1, value:red}, {trait:color2, value:white}] }
},
name:dany
data: {
   sign: "dan",
   tools: [{trait:color1, value:blue}, {trait:color2, value:black}] 
}

or how can i enhacement my structure to dont have this problem?

CodePudding user response:

You need to filter the data first, them limit it. Using this synatax.

 const toolsFilter = {
    trait: 'color1',
    value:'red'
  }
 
 const qSnap = await query.whereArrayContains('tools',toolsFilter)
                          .limit(30)
                          .get();
    
    qSnap.docs.forEach((doc) => { 
      const item = doc.data().data;
      console.log(item)
    }))

See the Firebase online documentation for more info on query syntax etc.. https://firebase.google.com/docs/firestore/query-data/queries

Also this explains pagination using query cursors https://firebase.google.com/docs/firestore/query-data/query-cursors

CodePudding user response:

Taking Stewart's answer and changing it a bit (I couldn't do that in a comment, sorry)

const toolsFilter = {
    trait: 'color1',
    value:'red'
  }
 
 const qSnap = await query.where('tools','array-contains-any', toolsFilter)
                          .limit(30)
                          .get();
    
    qSnap.docs.forEach((doc) => { 
      const item = doc.data().data;
      console.log(item)
    }))
  • Related