CRUD operations
Set Data
This would set data (inserting a document) with an explicit ID.
async function exampleData(db) {
// Create a reference to the cities collection
const citiesRef = db.collection('cities');
await citiesRef.doc('SF').set({ // 'SF' would be the doc's ID
name: 'San Francisco', state: 'CA', country: 'USA',
capital: false, population: 860000,
regions: ['west_coast', 'norcal']
});
await citiesRef.doc('LA').set({
name: 'Los Angeles', state: 'CA', country: 'USA',
capital: false, population: 3900000,
regions: ['west_coast', 'socal']
});
await citiesRef.doc('DC').set({
name: 'Washington, D.C.', state: null, country: 'USA',
capital: true, population: 680000,
regions: ['east_coast']
});
await citiesRef.doc('TOK').set({
name: 'Tokyo', state: null, country: 'Japan',
capital: true, population: 9000000,
regions: ['kanto', 'honshu']
});
await citiesRef.doc('BJ').set({
name: 'Beijing', state: null, country: 'China',
capital: true, population: 21500000,
regions: ['jingjinji', 'hebei']
});
}
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());
});
}
Last updated
Was this helpful?