This would add a document with an auto-generated ID:
// Add a new document with a generated id.
const res = await db.collection('cities').add({
name: 'Tokyo',
country: 'Japan'
});
console.log('Added document with ID: ', res.id);
Read one document by ID
async function getDocument(db) {
const cityRef = db.collection('cities').doc('SF'); // 'SF' is the doc's ID
const doc = await cityRef.get();
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
}
Get multiple documents
The query results, stored in the snapshot object, will be iterable.
To get all documents in a collection, the where clause is removed.
async function getMultiple(db) {
// Create a reference to the cities collection
const citiesRef = db.collection('cities');
const snapshot = await citiesRef.where('capital', '==', true).get();
if (snapshot.empty) {
console.log('No matching documents.');
return;
}
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
}