DocumentSnapshot vs QuerySnapshot

GonnabeAlright·2021년 12월 31일
0
post-thumbnail

Getting a single document

Retrieving a single document from Cloud Firestore is done with the following steps.

1. Create a DocumentReference the points to the document you want.

// This points to the document with the ID 'SF'
// in the collction 'cities'
let documentReference = db.collection('cities').doc('SF');

2. Call get() on the DocumentReference to get a DocumentSnapshot.

documentReference.get().then(function (documentSnapshot) {
  // check and do something with the data here.
});

3. Check if the document you specified actually exists.

if (documentSnapshot.exists) {
  // do something with the data
} else {
  console.log('document not found');
}

4. Retrieve and use the data.

let data = documentSnapshot.data();

Querying a collection

When querying a collection you can get zero, one or more documents as a result, by going through the following steps.

1. Create a CollectionReference that points to the collection you want documents from.

let collectionReference = db.collection('cities');

2. (Optional) Create a Query based on the collection.

let query = collectionReference.where('capital', '==', true);

3. Call get() to get a QuerySnapshot.

query.get().then(function(querySnapshot) {
  // check and do something with the data here.
});

4. Check whether there are any documents in the result.

if (querySnapshot.empty) {
  console.log('no documents found');
} else {
  // do something with the data
}

or

if (querySnapshot.size > 0) {
  // do something with the data
} else {
  console.log('no documents found');
}

5. Retrieve and use the data. Two different ways to do so:

// go through all the results
querySnapshot.forEach(function (documentSnapshot) {
  let data = documentSnapshot.data();
  // do something with the data of each document.
});

or

let data = querySnapshot.docs.map(function (documentSnapshot) {
  return documentSnapshot.data();
});

0개의 댓글