我正在使用reactjs,并试图将firestore中集合的文档中的一个字段的"value“设置为另一个文档的文档引用。
例如,我尝试使用下面的代码,它是一个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()它已经初始化了,因为如果我删除整行,一切都是正常的。
该怎么办呢?
发布于 2021-07-24 15:38:07
这个问题可能与您使用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
</>)
}瞧!:)希望这能有所帮助。
https://stackoverflow.com/questions/53469766
复制相似问题