Manipulating Data in Firestore
While data will only be retrieved from a Firestore database a majority of the time, it is still necessary to manipulate the data from time to time. This includes adding new documents and updating and deleting existing documents.
However, just like retrieving data, each task requires specific methods that must be imported before using.
Adding Documents
Adding a new document to an existing collection requires the collection
and addDoc
methods. The addDoc
method will return a promise and thus should be accompanied by async
and await
.
import { collection, addDoc } from 'firebase/firestore'
import db from './db'
export default {
methods: {
addRestaurant: async function () {
const c = collection(db, 'restaurants')
const document = await addDoc(c, {
name: this.name,
city: this.city
})
console.log(document.id)
}
}
}
Updating Documents
The doc
and updateDoc
methods will be employed when updating a document. Like the addDoc
, the updateDoc
method will return a promise.
import { doc, updateDoc } from 'firebase/firestore'
import db from './db'
export default {
methods: {
updateRestaurant: async function () {
const d = doc(db, 'restaurants', this.id)
await updateDoc(d, {
name: this.name,
city: this.city
})
console.log('The document has been updated')
}
}
}
Deleting Documents
The doc
and deleteDoc
methods will be used to delete an existing document. The deleteDoc
method does return a promise.
import { doc, deleteDoc } from 'firebase/firestore'
import db from './db'
export default {
methods: {
deleteRestaurant: async function () {
const d = doc(db, 'restaurants', this.id)
await deleteDoc(d)
console.log('The document has been deleted')
}
}
}