我正在使用reactjs,并尝试将Firestore中的集合文档中字段的“值”设置为另一个文档的文档引用。
例如,我正在尝试使用以下代码,这是我使用的系统读取的json文件。
import * as firebase from 'firebase';
require("firebase/firestore");
var collectionMeta={
"users":{
"fields":{
"firstname":"",
"lastname":"",
"email": "",
"gender":"",
"birthday":"",
"group":"",
"subGroups":"",
"roles":"-",
"code":""
},
"collections":[],
},
"announcements":{
"fields":{
"title":"",
"content":"",
"active":false,
"start":"",
"end":"",
"group": new firebase.firestore.DocumentReference("/groups/docID")
},
"collections":[],
},
"groups":{
"fields":{
"name":"",
"registerCode":""
},
"collections":[]
},
}
module.exports = collectionMeta;
此刻,我在“新的firebase.firestore.DocumentReference(“ / groups / docID”)”部分收到错误消息。
我得到的错误:
Uncaught Error: This constructor is private. Use firebase.firestore().doc() instead.
但是当我尝试这样做时,出现以下错误:
Firebase: No Firebase App '[DEFAULT]' has been cre…- call Firebase App.initializeApp()
它已经被初始化,因为如果我删除整行,一切都很好。
该怎么办?
答案 0 :(得分:0)
问题可能与您使用 firebase 的顺序有关。确保先初始化 firebase,然后使用 firestore 获取或更新任何类型的数据。
这是完成 firebase 初始化的 firebase utils/config 文件!
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
storageBucket: "mygiene-f2d83.appspot.com",
messagingSenderId: "sender_id",
appId: "app_id",
measurementId: "measurement-id",
};
// Initialize Firebase
// this if condition checks if your firebase app is already intialized then it // stops it from re-initializing again
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
// only exporting firebase auth and firestore.
export const auth = firebase.auth();
export const firestore = firebase.firestore();
然后简单地通过将其导入其他文件来使用它,如下所示
import { firestore } from "../../firebase/utils";
import { useContext, useEffect, useState } from "react";
export const Component = () => {
const [product, setproduct] = useState();
useEffect(async () => {
const productRef = await firestore.doc("products/grooming_kit").get();
const { id } = productRef;
setproduct({ ...productRef.data(), pId: id });
}, []);
return(<>
//Simply use the value stored over state however you linke
</>)
}
瞧! :) 希望这会有所帮助。