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
    .firestore()
    .collection("chats")
    .add({
      //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 = () => {
  firebase
    .firestore()
    .collection("chats")
    .doc(chat.id)
    .collection("messages")
    .add({
      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) => {
    firebase
      .firestore()
      .collection("chats")
      .where("users", "array-contains", currentUser.uid)
      .onSnapshot((snapshot) => {
        let chats = snapshot.docs.map((doc) => {
          //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
                              .toDate()
                              .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) {
  firebase.initializeApp(firebaseConfig)
}

const db = firebase.firestore();



export {db}

export default firebase;

o firestore só aparece quando eu coloco:

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

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 = ();
            querySnapshot.docs.forEach((doc) => {
                const { title, category, uri, pdf } = doc.data();
                Libery.push({
                    id: doc.id,
                    title,
                    category,
                    uri,
                    pdf
                });
            });
            console.log(Libery)
            setLibery(Libery);
        });
    }, ());

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"
                          (...etc)

This is my incorrect query sketch:

Query query = FirebaseFirestore.getInstance()
        .collection("post").document(uidVisit).collection("userPosts")
        .limit(1000);

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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_visualizza_post);
        overridePendingTransition(0, 0);

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

        findUsersList = findViewById(R.id.usersSearched);

        searchEt = findViewById(R.id.txt_ricerca);
        ustxt = findViewById(R.id.name_text);
        findUsersList.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

    }


    @Override
    protected void onStart() {
        super.onStart();

        Query query = FirebaseFirestore.getInstance()
                .collection("post").document(uidVisit).collection("userPosts")
                //.orderby
                .limit(50);

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

        FirestoreRecyclerAdapter<GetInfoPost, FindFriendsViewHolder> firestoreRecyclerAdapter = new FirestoreRecyclerAdapter<GetInfoPost, FindFriendsViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull FindFriendsViewHolder holder, int position, @NonNull GetInfoPost model) {
                holder.txtTitoloInPost.setText(model.getTitle());
                holder.txtData.setText(model.getdate());
                Picasso.get().load(model.getUrlImage()).into(holder.imgPost);
                holder.txtDescrizione.setText(model.getDescription());
                holder.txtTag.setText(model.getGenre());
               // holder.txtLikenmb.setText(model.getLike());
            }

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

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

                return new FindFriendsViewHolder(view);
            }
        };

        findUsersList.setAdapter(firestoreRecyclerAdapter);
        firestoreRecyclerAdapter.startListening();






    }

    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) {
            super(itemView);

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

            img_profinPost = itemView.findViewById(R.id.img_profinPost);
            imgPost = itemView.findViewById(R.id.imgPost);


            cardView = itemView.findViewById(R.id.card_viewR);

        }
    }

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
java.lang.NullPointerException
    at com.ezdev.chepesdelivery.Repo$getTiendaData$1.onSuccess(Repo.kt:18)
    at com.ezdev.chepesdelivery.Repo$getTiendaData$1.onSuccess(Repo.kt:7)
    at com.google.android.gms.tasks.zzn.run(Unknown Source:4)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7656)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

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
import com.google.firebase.firestore.FirebaseFirestore

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!!)
                listData.add(tienda)
            }
            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.