Manipulating Data in Firestore
While, a majority of the time, data will only be retrieved from a Firestore database, it is still necessary to manipulated the data from time to time. This includes adding new documents, updating existing documents, and deleting documents.
Adding Documents
The add()
method is used to add a new document to an existing collection. The method is applied to a collection reference, and receive an object for its data. The add()
method returns a Promise
, which will result in the document that was just added.
db.collection('restaurants')
.add({
name: this.name,
city: this.city
})
.then(doc => { console.log(doc.id) })
Updating Documents
The update()
method is used to update one or more fields of an existing document. The method is applied to a document reference, and receives an object of the update data. Only properties in the passed object will be updated, any additional properties will left unchanged. A callback function can be added to execute after the document has been updated.
db.collection('restaurants').doc(this.id)
.update({
name: this.name,
city: this.city
})
.then(() => { console.log('The document has been updated') })
Deleting Documents
The delete()
method is used to delete existing documents. The method is applied to a document reference. A callback function can be added to execute after the document has been deleted.
db.collection('restaurants').doc(this.id)
.delete()
.then(() => { console.log('The document has been deleted') })