Home > Net >  Why getting Invalid collection reference error?
Why getting Invalid collection reference error?

Time:05-11

I am updating a document in firebase when user enters a comment.The code for the same is:

 const docRef=collection(db,"posts",post.id);
        console.log(docRef);
        updateDoc(docRef,{
          user:localStorage.getItem('Name'),
          title: post.title,
          comment:temppost ,
          upVotesCount: 0,
          downVotesCount: 0,
          createdAt: post.createdAt,
          updatedAt: date.toUTCString(),
          isCommentVisible:false
        });

But I m getting this error:

Uncaught (in promise) FirebaseError: Invalid collection reference. Collection references must have an odd number of segments, but posts/PQAvoGjUeX8aPVVZxMNC has 2.

I haven't used any subcollections here.

CodePudding user response:

You need a DocumentReference to update a single document that you can create using doc(). The collection() is used to create a CollectionReference:

// use doc() instead of collection()
const docRef = doc(db,"posts",post.id);

Also checkout: Firestore: What's the pattern for adding new data in Web v9?

CodePudding user response:

You are trying to pass a document in a collection function. (db,"posts") is how you refer to a collection and (db,"posts",post.id) is how you refer to a document. So use one of these:

const docRef = doc(db,"posts",post.id);    // 3 arguments for a document
------
const postsRef = collection(db,"posts");   // 2 arguments for a collection
const docRef = (postsRef,post.id);         // in essence 2 1 arguments for a document
  • Related