'Why error Expected first argument to collection() to be a CollectionReference
I am getting the following error when trying to get all documents from a collection in Firestore using firebase admin SDK:
[nuxt] [request error] Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore
I am testing via a simple console.log:
/server/api/posts.js:
import { firestore } from '../utils/firebase'
import { collection, getDocs } from 'firebase/firestore'
export default defineEventHandler(async (event) => {
const colRef = collection(firestore, 'posts')
console.log(colRef)
})
Here is how I am initializing firestore:
/server/utils/firebase.js:
import { initializeApp, cert } from 'firebase-admin/app'
import { getFirestore } from 'firebase-admin/firestore'
import serviceAccount from '../../service-account.json'
export const app = initializeApp({
credential: cert(serviceAccount)
})
export const firestore = getFirestore()
Note: The following code works on the server-side and I am able to get a document back, but for some reason I can't use the collection() like in the above example.
import { firestore } from '../utils/firebase'
export default defineEventHandler(async (event) => {
const ref = firestore.doc(`animals/dog`)
const snapshot = await ref.get()
const data = snapshot.data()
console.log(data)
// return {
// data
// }
})
Also, if I run the collection() function on the client side, I can successfully retrieve the posts. I just can't figure out why it won't work server-side.
Anyone know why I get the above error?
Solution 1:[1]
None of the server code you have shared align to such an error message. The error indicates that you are calling .get() or .onSnapshot() with something that is not a DocumentReference or a CollectionReference.
Note: collection() and doc() are functions that return References. They don't actually communicate to the FS service...a Reference is (essentially) a string such as `/posts' or '/posts/1234567'
So, somewhere in your code, you need to find where it is hitting the above error and either share it here or understand why what you are calling it on is not a valid CollectionReference or DocumentReference.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Greg Fenton |
