martin james
martin james

Reputation: 41

How to connect to Firebase Firestore?

I want to get data from a Firestore Database, however, instead of getting an Array of 1 element, I get [Al] which I'm not sure what it is.

This is the code I have in my Index.html. I have changed the information inside the config object for security reasons here.

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-firestore.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-analytics.js"></script>

<script>
  // Your web app's Firebase configuration
  var firebaseConfig = {
    apiKey: "my api key",
    authDomain: "demo",
    databaseURL: "my url",
    projectId: "my project",
    storageBucket: "bucket",
    messagingSenderId: "1051539927876",
    appId: "my app id",
    measurementId: "0000000000"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  var db = firebase.firestore();
  firebase.analytics();
</script>

<script src="app.js"></script>

And this is what I have inside my app.js file

db.collection('cafes').get().then((snapshot) => {
  console.log(snapshot.docs);
}).catch(err => {
  console.log(err);
});

Upvotes: 2

Views: 585

Answers (2)

bigant02
bigant02

Reputation: 318

var docRef = db.collection("cafes").doc("cafe_name");

docRef.get().then(function(doc) {
    console.log("document data:", doc.data());
}).catch(function(error) {
    console.log("Error getting data:", error);
});

or

db.collection("cafes").doc("cafe_name").get().then(function(doc) {
    console.log("document data:", doc.data());
}).catch(function(error) {
    console.log("Error getting data:", error);
});

You need to change "cafe_name" to the name of an item of cafes.

Upvotes: 0

Peter Haddad
Peter Haddad

Reputation: 80944

You need to do the following to get the data:

db.collection('cafes').get().then((snapshot) => {
 snapshot.forEach((doc) => {
 console.log(doc.id, " => ", doc.data());
 });
}).catch(err => {
  console.log(err);
});

doc.data() will contain the data of the documents.

https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_collection

Upvotes: 2

Related Questions