user12481721
user12481721

Reputation:

Does Firestore's `get()` count as 1 document read?

I'm building user-to-user chat in my app, so I'm a little worried about the Firestore's pricing. I'm looking for the best way to structure my database, since I'm not sure if I can change it in the future. Does get() count as one read, or it will charge me for each message as a different read?


This is what I've done, I hope that it's the best way to do it:

// Set the user's IDs
var userA = 1
var userB = 2

// Naming the conversation
var conversation = (userA < userB ? userA + '_' + userB : userB + '_' + userA)

// Initialize Firebase
firebase.initializeApp()

// Initialize Firestore
var db = firebase.firestore()

// INSERT conversation name to the conversations list of each user
db.collection('users/' + userA + '/conversations').doc(conversation).set({})
db.collection('users/' + userB + '/conversations').doc(conversation).set({})

// SELECT conversations list for userA
db.collection('users/' + userA + '/conversations').get().then((response) => {
  response.forEach((document) => {
    console.log(document.id)
  })
})

// SELECT conversations list for userB
db.collection('users/' + userB + '/conversations').get().then((response) => {
  response.forEach((document) => {
    console.log(document.id)
  })
})

// INSERT message "Hello" from userA
db.collection('conversations/' + conversation + '/messages').add({
  time: firebase.firestore.Timestamp.fromDate(new Date()).seconds,
  user: userA,
  text: 'Hello'
})

// INSERT message "World" from userB
db.collection('conversations/' + conversation + '/messages').add({
  time: firebase.firestore.Timestamp.fromDate(new Date()).seconds,
  user: userB,
  text: 'World'
})

// SELECT messages from conversation
db.collection('conversations/' + conversation + '/messages').get().then((response) => {
  response.forEach((document) => {
    console.log(document.id + ': ' + JSON.stringify(document.data()))
  })
})

Upvotes: 0

Views: 818

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317362

When you call get() on a collection reference or a query, it will cost one read for every document matched by that query. When you call get() on a document reference, it will cost one read for that individual document. The billing is all about number of documents read, not the number of times you call get().

Upvotes: 4

Related Questions