Reputation: 625
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.
Can you see what I am doing wrong please,
If I run the following code
created() {
//fetch data from firestore
let ref = db.collection('post').doc(this.$route.params.id)
ref.get()
.then(snapshot => { //DocSnapshot
console.log(snapshot.data)
if (doc.exists) {
// doesnt run
console.log('test')
let post = snapshot.data()
} else {
// snapshot.data() will be undefined in this case
// also doesn't run
console.log("No such document!");
}
})
},
I get the following in the console
function (options) {
validateBetweenNumberOfArgs('DocumentSnapshot.data', arguments, 0, 1);
options = validateSnapshotOptions('DocumentSnapshot.data', options);
return !this._document
? undefined
: this.convertObject(this._document.data, FieldValueOptions.fromSnapshotOptions(options, this._firestore._areTimestampsInSnapshotsEnabled()));
}
Upvotes: 1
Views: 3375
Reputation: 83093
By doing let ref = db.collection('post').doc(this.$route.params.id)
you get a DocumentReference
as detailed in the documentation here.
Then by doing get()
on this DocumentReference
you get a DocumentSnapshot
, as detailed here, and not a 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
.
So, in other words, do as follows:
let ref = db.collection('post').doc(this.$route.params.id)
ref.get()
.then(snapshot => { //DocSnapshot
if (snapshot.exists) {
let post = snapshot.data()
} else {
// snapshot.data() will be undefined in this case
console.log("No such document!");
}
})
Upvotes: 4