database – How should I structure my collection and documents to create a chat app, using Googe Cloud Firestore and react native?

I am writing a chat app. Each user has a profile, so every user can message to another user (one to one).

My idea so far: Once a user message to another user I call createChat function:

const createChat = async () => {
  await firebase
      //this is the part which bothers me the most
      users: (currentUser.uid, user.uid),
      lastMessage: "Send the first message",
      lastMessageTimestamp: firebase.firestore.FieldValue.serverTimestamp(),

I am storing the two user ids in the users field. Later when a user press the Send button:

const onSend = () => {
      creator: firebase.auth().currentUser.uid,
      text: textToSend,
      creation: firebase.firestore.FieldValue.serverTimestamp(),

I also want to display all current user’s chats on a separate page. So when the user go to “My chats” page, they will see a list of all of their chats. In order for me to fetch all current user’s chats, I am calling fetchUserChats :

  function fetchUserChats() {
  return (dispatch) => {
      .where("users", "array-contains", currentUser.uid)
      .onSnapshot((snapshot) => {
        let chats = => {
          //do something

Is that a good approach from architectural/performance point of view? Should I store chat’s ids inside my Users collection. Currently my user collection has the following fields: name, age, user_id, so I thought to add chat_id, in order for me to fetch particular users chats more easily/faster. Would that be a better approach?

How do I enforce App Check in a Firestore instance?

I have set up App Check in my Firebase Project, for both my mobile app and my web app.

I have followed the instruction for enabling App Check in various Firebase products such as Functions and Storage, following the instructions here.

How do I enable it in Firestore? The link above doesn’t provide any info and I could not find anything in the Firestore guides.

firebase – firestore flutter recalculate all data stored if another data is updated

enter image description hereI have data stored in firebase as below

The planned Start and planned finish are calculated mathematically
planned finish = planned start +duration
planned Start = planned finish of dependent sl no
for sl no 10 dependent is 9 so planned Start of 10 is equal to planned finish of 9
So my problem is if I updated planned finish of sl no 9 then how can I make 10 to automatically update it planned start and finish
The code on how data is saved is as below

 if (slno != null && activity != null) {
                      if (action == 'create') {
                        // Persist a new product to Firestore
                        Future<Timestamp> getslno() async {
                          var document =
                              await _schedule.doc(dependent.toString()).get();
                          Timestamp sl = await document('plannedfinish');
                          return sl;

                        var planneds = await getslno();
                        await _schedule.doc(slno.toString()).set({
                          "slno": slno,
                          "activity": activity,
                          "duration": duration,
                          "dependent": dependent,
                          "plannedstart": planneds,
                          "plannedfinish": planneds
                              .add(Duration(days: duration!.toInt()))

                      if (action == 'update') {
                        // Update the product
                        await _schedule.doc(documentSnapshot!.id).update({
                          "slno": slno,
                          "activity": activity,
                          "duration": duration,
                          "dependent": dependent

I need all the data stored to be automatically updated if at least one data is changed
Any suggestions on how to do it

firebase – Erro Firestore react native

Estou tentando pegar as informações da minha coleção no firebase mais estou recebendo o seguinte erro:

TypeError: undefined is not an object (evaluating ‘_firebaseConnection.default.db.collection’)

esse é meu código do firebase

import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
import 'firebase/database';

let firebaseConfig = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""


if (!firebase.apps.length) {

const db = firebase.firestore();

export {db}

export default firebase;

o firestore só aparece quando eu coloco:

 const db = firebase.firestore();
  export default {

desse formato acima eu não consigo sair do aplicativo da erro de auth

Código da minha tela de livro aonde o erro ocorre:

const (Libery, setLibery) = useState();

    useEffect(() => {
        firebase.db.collection("biblioteca").onSnapshot((querySnapshot) => {
            const Libery = ();
   => {
                const { title, category, uri, pdf } =;
    }, ());

nodejs – Firebase – Firestore – lectura datos desde JavaScript

Tengo el formato del siguiente JSON en FireStore.

  coleccion1: {
    documento1: {
      notas: {
        colegios: {
          "2020": {
            publicos: (
                nombre: "Felipe II",
                cursos: (
                    clase: "1A",
                    califiacion: (
                        codigo: "a",
                        nota: "2"
                        codigo: "11bbcc",
                        nota: "2"

Aunque he encontrado otras alternativas para acceder a un dato concreto, no se muy bien como se haría si quiero acceder poniendo la URL completa en el mtodo get.

Por ejemplo, quiero acceder al nombre del primer colegio publico.

La forma que SI me funciona es haciendolo así:

const db = firebase.firestore();
const datosRef  = await db.collection('coleccion1').doc('documento1').get();
const publicos = datosRef.get('notas.colegios.2020.publicos');
const nombreIndex_0 = publicos (0).nombre;
console.log(nombreIndex_0) // Felipe II

Pero si por ejemplo quiero acceder y hacerlo todo en una misma sentencia, la URL no admite corchetes “()” para especificar la posición 0 del array; y el “.” tampoco funciona.

const db = firebase.firestore();
const datosRef  = await db.collection('coleccion1').doc('documento1').get();
const publicos = datosRef.get('notas.colegios.2020.publicos(0).nombre');

Me da el siguinte error de caracter no permitido:

Invalid field path (notas.colegios.2020.publicos(0).nombre). Paths must not contain '~', '*', '/', '(', or ')'

De la siguiente forma, tampoco me ha funcionado:

const nombre = datosRef.get('notas.colegios.2020.publicos.0.nombre');

En este caso no ha dado error, pero nombre no tiene valor. “undefin..”

Gracias y saludos.

android – Firestore Java Get fields ​of documents within collections without knowing the name of them

I’m programming an activity that through firebaserecyclerview gets all the posts from the following firestore structure:

--- posts (collection)
         --- uid (documents)
              --- userPosts (collection)
                    --- postId (documents)
                    |     |
                    |     --- title: "Post Title"
                    |     |
                    |     --- date: September 03, 2018 at 6:16:58 PM UTC+3
                    --- postId (documents)
                          --- title: "Post Title"
                          --- date: 08/06/2021
                          --- description: "this is the description of the post"

This is my incorrect query sketch:

Query query = FirebaseFirestore.getInstance()

Obviously, the above query is wrong for what I want to get, because that query stops at selecting the contents of userpost which are nothing more than the ids of the posts that I actually have to fetch:

effect of the previous query

Instead, I want to take all the contents of the various user posts but the only problem is that I do not know the post id (because they are all different). Is there a way then to get the posts from that firestore structure that I inserted at the beginning of the post? I hope I have made you understand my problem

In case it can help you, I leave my complete code:

Full Code:

EditText searchEt;
    TextView ustxt;

    private RecyclerView findUsersList;  //fidnfirendlist

    private String str = "", uidVisit = "";
    private DatabaseReference usersRef;

    protected void onCreate(Bundle savedInstanceState) {
        overridePendingTransition(0, 0);

        Intent intent = getIntent();
        uidVisit = intent.getStringExtra("uidVisit");

        findUsersList = findViewById(;

        searchEt = findViewById(;
        ustxt = findViewById(;
        findUsersList.setLayoutManager(new LinearLayoutManager(getApplicationContext()));


    protected void onStart() {

        Query query = FirebaseFirestore.getInstance()

        FirestoreRecyclerOptions<GetInfoPost> options = new FirestoreRecyclerOptions.Builder<GetInfoPost>()
                .setQuery(query, GetInfoPost.class)

        FirestoreRecyclerAdapter<GetInfoPost, FindFriendsViewHolder> firestoreRecyclerAdapter = new FirestoreRecyclerAdapter<GetInfoPost, FindFriendsViewHolder>(options) {
            protected void onBindViewHolder(@NonNull FindFriendsViewHolder holder, int position, @NonNull GetInfoPost model) {
               // holder.txtLikenmb.setText(model.getLike());

            public FindFriendsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

                View view = LayoutInflater.from(parent.getContext())
                        .inflate(, parent, false);

                return new FindFriendsViewHolder(view);



    public static class FindFriendsViewHolder extends RecyclerView.ViewHolder {

        TextView nameInPost, txtData, txtTag, txtTitoloInPost, txtLikenmb, txtDescrizione;
        ImageView img_profinPost, imgPost;
        RelativeLayout cardView;

        public FindFriendsViewHolder(@NonNull View itemView) {

            nameInPost = itemView.findViewById(;
            txtData = itemView.findViewById(;
            txtTag = itemView.findViewById(;
            txtTitoloInPost = itemView.findViewById(;
            txtLikenmb = itemView.findViewById(;
            txtDescrizione = itemView.findViewById(;

            img_profinPost = itemView.findViewById(;
            imgPost = itemView.findViewById(;

            cardView = itemView.findViewById(;


android – Could not reach Cloud Firestore backend. Connection failed 1 times

i’m using a very simple code and fetching data from firestore

import firebase from 'firebase/app';
import 'firebase/firestore'

const firebaseApp = firebase.initializeApp({
        apiKey: "...",
        authDomain: "...",
const db = firebaseApp.firestore();
export default db;

but i keep getting this error

(2021-06-05T00:58:41.274Z)  @firebase/firestore: Firestore (8.6.5): Could not reach Cloud Firestore backend. Connection failed 1 times.
Most recent error: FirebaseError: (code=permission-denied):
 Permission denied on resource project.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.

  1. i do have a very fast internet connection
  2. my clock is also synced with the standard time

Now, i have no clue why is this happening?

please someone help me out!!!

android – Error al abrir mi Activity con un RecyclerView conectado a Firebase Firestore

estoy haciendo una app que utiliza un recycler view en una activity y la información la saco desde Firebase Firestore .Pero cuando abro esa activity se cierra la app. Paso el error que me salta cuando se cierra.

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ezdev.chepesdelivery, PID: 23947
    at com.ezdev.chepesdelivery.Repo$getTiendaData$1.onSuccess(Repo.kt:18)
    at com.ezdev.chepesdelivery.Repo$getTiendaData$1.onSuccess(Repo.kt:7)
    at Source:4)
    at android.os.Handler.handleCallback(
    at android.os.Handler.dispatchMessage(
    at android.os.Looper.loop(
    at java.lang.reflect.Method.invoke(Native Method)

Creo que el error se produce por culpa del Repo, Paso el código del Repo.

package com.ezdev.chepesdelivery

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData

class Repo {

    fun getTiendaData():LiveData<MutableList<Tiendas>>{
        val mutableData = MutableLiveData<MutableList<Tiendas>>()
        FirebaseFirestore.getInstance().collection("tiendasOnline").get().addOnSuccessListener { result ->
            val listData = mutableListOf<Tiendas>()
            for(document in result){
                val imageUrl = document.getString("Url")
                val nombre =  document.getString("Nombre")
                val online = document.getBoolean("Online")
                val descripcion = document.getString("Descripcion")
                val tienda = Tiendas(nombre!!, descripcion!!, online!!, imageUrl!!)
            mutableData.value = listData

        return  mutableData


EL programa compila bien pero cuando se lanza la activity se cierra la app. estoy usando Kotlin

Muchas gracias desde ya.