Notes
FireStore
Content of the notes (2)
Page 1
Write On DB:
db.collection("cities").doc("LA").set(
{ name: "Los Angeles", state: "CA", country: "USA" })
.then(function() { console.log("Document successfully written!"); })
.catch(function(error) { console.error("Error writing document: ", error); });
If the document does not exist, it will be created. If the document does exist, its contents will be overwritten with the newly provided data, unless you specify that the data should be merged into the existing document, as follows:
var setWithMerge = cityRef.set({ capital: true }, { merge: true });
When you use set() to create a document, you must specify an ID for the document to create. For example:
db.collection("cities").doc("new-city-id").set(data);
But sometimes there isn't a meaningful ID for the document, and it's more convenient to let Cloud Firestore auto-generate an ID for you. You can do this by calling add():
// Add a new document with a generated id.
db.collection("cities").add({ name: "Tokyo", country: "Japan" })
.then(function(docRef) { console.log("Document written with ID: ", docRef.id); })
.catch(function(error) { console.error("Error adding document: ", error); });
Page 2
Read DB
get a document :
var cityRef = db.collection('cities').doc('SF');
var getDoc = cityRef.get()
.then(doc => { if (!doc.exists) { console.log('No such document!'); } else { console.log('Document data:', doc.data()); } }) .catch(err => { console.log('Error getting document', err); });
Get multiple documents from a collection
var citiesRef = db.collection('cities');
var query = citiesRef.where('capital', '==', true).get()
.then(snapshot => { snapshot.forEach(doc => { console.log(doc.id, '=>', doc.data()); }); })
.catch(err => { console.log('Error getting documents', err); });
Get all documents in a collection
var citiesRef = db.collection('cities');
var allCities = citiesRef.get()
.then(snapshot => { snapshot.forEach(doc => { console.log(doc.id, '=>', doc.data()); }); })
.catch(err => { console.log('Error getting documents', err); });
Information
- Description
- Note on FireStore , created by Khaled Jabari on 29/10/2017.
- Created by
- Khaled Jabari · Oct 2017
- Updated
- Oct 29, 2017
- Views
- 0
- Rating