Hello I am following the firestore tutorial
First they instruct me to seed the database with
import { collection, doc, setDoc } from "firebase/firestore";
const citiesRef = collection(db, "cities");
await setDoc(doc(citiesRef, "SF"), {
name: "San Francisco", state: "CA", country: "USA",
capital: false, population: 860000,
regions: ["west_coast", "norcal"] });
await setDoc(doc(citiesRef, "LA"), {
name: "Los Angeles", state: "CA", country: "USA",
capital: false, population: 3900000,
regions: ["west_coast", "socal"] });
await setDoc(doc(citiesRef, "DC"), {
name: "Washington, D.C.", state: null, country: "USA",
capital: true, population: 680000,
regions: ["east_coast"] });
await setDoc(doc(citiesRef, "TOK"), {
name: "Tokyo", state: null, country: "Japan",
capital: true, population: 9000000,
regions: ["kanto", "honshu"] });
await setDoc(doc(citiesRef, "BJ"), {
name: "Beijing", state: null, country: "China",
capital: true, population: 21500000,
regions: ["jingjinji", "hebei"] });
Later in the tutorial they instruct me to run this code to create some sub-collections
import { collection, doc, setDoc } from "firebase/firestore";
const citiesRef = collection(db, 'cities');
await Promise.all([
setDoc(doc(citiesRef, 'SF', 'landmarks'), {
name: 'Golden Gate Bridge',
type: 'bridge'
}),
setDoc(doc(citiesRef, 'SF', 'landmarks'), {
name: 'Legion of Honor',
type: 'museum'
}),
setDoc(doc(citiesRef, 'LA', 'landmarks'), {
name: 'Griffith Park',
type: 'park'
}),
setDoc(doc(citiesRef, 'LA', 'landmarks'), {
name: 'The Getty',
type: 'museum'
}),
setDoc(doc(citiesRef, 'DC', 'landmarks'), {
name: 'Lincoln Memorial',
type: 'memorial'
}),
setDoc(doc(citiesRef, 'DC', 'landmarks'), {
name: 'National Air and Space Museum',
type: 'museum'
}),
setDoc(doc(citiesRef, 'TOK', 'landmarks'), {
name: 'Ueno Park',
type: 'park'
}),
setDoc(doc(citiesRef, 'TOK', 'landmarks'), {
name: 'National Museum of Nature and Science',
type: 'museum'
}),
setDoc(doc(citiesRef, 'BJ', 'landmarks'), {
name: 'Jingshan Park',
type: 'park'
}),
setDoc(doc(citiesRef, 'BJ', 'landmarks'), {
name: 'Beijing Ancient Observatory',
type: 'museum'
})
]);
However, this results in the error
errors.ts:94 Uncaught FirebaseError: Invalid document reference. Document references must have an even number of segments, but cities/SF/landmarks has 3.
Anyone know what the reason for that is?
That looks like a mistake in the sample code. Since citiesRef is a collection reference, so is doc(citiesRef, 'SF', 'landmarks'), and you can't call setDoc on a collection reference.
Call addDoc instead of setDoc and collection instead of doc and things should work much better:
addDoc(collection(citiesRef, 'SF', 'landmarks'), {
name: 'Golden Gate Bridge',
type: 'bridge'
}),
Update 16-06-2022: That documentation page has been fixed and now uses addDoc() instead of setDoc() and collection() instead of doc().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With