Firebase, coding with Javascript - examples. part-1 
Tags: javascript, nosql, firebase, webdev
Published: 2020-12-11 14:12:16

**Collection Reference**
The collection reference is used to read or write documents or query for the documents that are available in the cloud firestore or db(These document in the cloud can be accessed using for..of method

<pre>
'''javascript
const fs = require('firebase-admin');
var db = fs.firestore();
const collRef = db.collection('fieldname').doc('fieldname');
let arrayVal = new Array();

// async function to get the data

async function myFunction(){
 let docSnapshot = await collRef.get(); 
 for(let val of Object.key(docSnapshot.data())) 
  {
       arrayVal.push([docSnapshot.data()[val],val]);
   }
}
console.log(arrayVal);
'''
</pre>

The output will be:
<pre>
[["value1","key1"],["value2","key2"]]
</pre>

or the object can be enumerated by applying a foreach method). 

<pre>
'''javascript
const fs = require('firebase-admin');
var db = fs.firestore();
const collRef = db.collection('fieldname').doc('fieldname');
let arrayVal = new Array();

// async function to get the data

async function myFunc(){
   let docSnapshot = await collRef.get(); 
Object.keys(docSnapshot.data()).foreach((item) => 
 {
   arrayVal.push([docSnapshot.data()[item],item]);
 }
}

console.log(arrayVal);
'''
</pre>

The output will be:
<pre>
[["value1","key1"],["value2","key2"]]
</pre>

**.get()**
The get method is used to query the db for the documents that the firebase is having. This method is implemented in such a way that you can only retrieve existing data. So the query will request the cloud for the data and the response will be a promise that has a Query snapshot(Read the below two definition and read this method again!). You only get query snapshot if and only if you request entire collection, else it becomes a query document snapshot.

<pre>
'''javascript
const collRef = db.collection('fieldname')

//this is called inside async function as 
//docsnapshot in previous example

let querySnapshot = await collRef.get(); 

'''
</pre>

**Document Snapshot**
This will return the field from documents selectively, because the user will be manually typing the path for the document.  This document snapshot, figuratively speaking will have a collection of data fields which are called document data.

The document snapshot and Query Document snapshot are similar but the only difference is it will contain additional query parameters as part of a query. 

Both the query document snapshot and document snapshot return values can be retrieved using .data() or .get('field').

Response values wil be:
<pre>
QueryDocumentSnapshot {
  _fieldsProto: {
    email: { stringValue: 'mbalaaji1995@gmail.com', valueType: 'stringValue' }
  },
  _ref: DocumentReference {
    _firestore: Firestore {
      _settings: [Object],
      _settingsFrozen: true,
      _serializer: [Serializer],
      _projectId: 'quizapp-011220',
      registeredListenersCount: 0,
      bulkWritersCount: 0,
      _backoffSettings: [Object],
      _clientPool: [ClientPool]
    },
    _path: ResourcePath { segments: [Array] },
    _converter: {
      toFirestore: [Function: toFirestore],
      fromFirestore: [Function: fromFirestore]
    }
  },
  _serializer: Serializer {
    createReference: [Function (anonymous)],
    createInteger: [Function (anonymous)],
    allowUndefined: false
  },
  _readTime: Timestamp { _seconds: 1607694363, _nanoseconds: 641576000 },     
  _createTime: Timestamp { _seconds: 1606843021, _nanoseconds: 548845000 },   
  _updateTime: Timestamp { _seconds: 1607497484, _nanoseconds: 962141000 }    
}
</pre>

**Query Snapshot**
Query snapshot is something you will get when requested all the documents in a collection. 

Response values wil be:
<pre>
QuerySnapshot {
  _query: CollectionReference {
    _firestore: Firestore {
      _settings: [Object],
      _settingsFrozen: true,
      _serializer: [Serializer],
      _projectId: 'quizapp-011220',
      registeredListenersCount: 0,
      bulkWritersCount: 0,
      _backoffSettings: [Object],
      _clientPool: [ClientPool]
    },
    _queryOptions: QueryOptions {
      parentPath: [ResourcePath],
      collectionId: 'FreshPrinceChoice',
      converter: [Object],
      allDescendants: false,
      fieldFilters: [],
      fieldOrders: [],
      startAt: undefined,
      endAt: undefined,
      limit: undefined,
      limitType: undefined,
      offset: undefined,
      projection: undefined
    },
    _serializer: Serializer {
      createReference: [Function (anonymous)],
      createInteger: [Function (anonymous)],
      allowUndefined: false
    },
    _allowUndefined: false
  },
  _readTime: Timestamp { _seconds: 1607695217, _nanoseconds: 742184000 },
  _size: 4,
  _materializedDocs: null,
  _materializedChanges: null,
  _docs: [Function (anonymous)],
  _changes: [Function (anonymous)]
}
</pre>