Get single record from Firestore using Vue.js

Multi tool use


Get single record from Firestore using Vue.js
I am trying to get a single record from a Firestore db where I am pulling the ID from the path but it doesn't seem to be working.
When I console log I get nothing at all in the log so not sure why the created code doesn't seem to be running
Can you see what I am doing wrong please
// Import firestorm Database
import db from '~/services/fireinit.js'
export default {
data() {
return {
post:
}
},
created() {
let ref = db.collection('post').doc(this.$route.params.id)
ref.get()
.then(snapshot => {
snapshot.forEach(doc => {
let post = doc.data()
console.log(post)
})
})
}
I should add that get all works fine
db.collection('post').get()
my console.log returns nothing even if I add a string to it so it doesn't appear this block of code is running, but I have no errors at all in the console.
1 Answer
1
By doing let ref = db.collection('post').doc(this.$route.params.id)
you get a DocumentReference
as detailed in the documentation here.
let ref = db.collection('post').doc(this.$route.params.id)
DocumentReference
Then by doing get()
on this DocumentReference
you get a DocumentSnapshot
, as detailed here, and not a QuerySnapshot
.
get()
DocumentReference
DocumentSnapshot
QuerySnapshot
So you should get the doc data via the data()
method (or the get(<field>)
to get a specific field) and not by doing snapshot.forEach(doc => {})
which should be used on a QuerySnapshot
.
data()
get(<field>)
snapshot.forEach(doc => {})
QuerySnapshot
So, in other words, do as follows:
let ref = db.collection('post').doc(this.$route.params.id)
ref.get()
.then(snapshot => { //DocSnapshot
if (doc.exists) {
let post = snapshot.data()
} else {
// snapshot.data() will be undefined in this case
console.log("No such document!");
}
})
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.