Home > Software engineering >  Add document with auto-generated ID in sub collection?
Add document with auto-generated ID in sub collection?

Time:05-11

I'm trying to add a document with auto-generated ID in reviews/something using:

await addDoc(collection(dbFirestore, "reviews", route.params.id), {
  rating: rating,
  text: text,
  user: {
    id: user.id,
    username: user.username,
    avatar: user.avatar,
  },
});

But I get:

Invalid collection reference. Collection references must have an odd number of segments, but reviews/XXX has 2.

CodePudding user response:

Assume reviews is a collection and want to add a document (with auto generated id) to its subcollection

await addDoc(collection(dbFirestore, "reviews/document_id/subcollection"), {
  rating: rating,
  text: text,
  user: {
    id: user.id,
    username: user.username,
    avatar: user.avatar,
  },
});

CodePudding user response:

As the error says, a CollectionReference must have odd number of path segments but you have 2. You just need to specify the collection name so try refactoring the code as shown below:

// i.e. remove route.params.id
await addDoc(collection(dbFirestore, "reviews"))
  • Related