Bor*_*ald 13 firebase typescript google-cloud-firestore
你好,我正在关注 firestore 教程
https://firebase.google.com/docs/firestore/query-data/queries#web-version-9_14
首先,他们指示我为数据库播种
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"] });
Run Code Online (Sandbox Code Playgroud)
在本教程的后面,他们指示我运行此代码来创建一些子集合
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'
})
]);
Run Code Online (Sandbox Code Playgroud)
但是,这会导致错误
errors.ts:94 Uncaught FirebaseError: Invalid document reference. Document references must have an even number of segments, but cities/SF/landmarks has 3.
有人知道这是什么原因吗?
Fra*_*len 20
这看起来像是示例代码中的错误。由于citiesRef是集合引用,所以 是doc(citiesRef, 'SF', 'landmarks'),并且您不能调用setDoc集合引用。
调用addDoc代替setDoc和collection代替doc,事情应该会更好:
addDoc(collection(citiesRef, 'SF', 'landmarks'), {
name: 'Golden Gate Bridge',
type: 'bridge'
}),
Run Code Online (Sandbox Code Playgroud)
2022 年 6 月 16 日更新:该文档页面已修复,现在使用addDoc()代替setDoc()和collection()代替doc()。
| 归档时间: |
|
| 查看次数: |
26007 次 |
| 最近记录: |