firebase 使用react将数据添加到firestore数据库

pbwdgjma  于 2023-10-22  发布在  React
关注(0)|答案(2)|浏览(125)

我想添加一个数组的用户作为一个集合到消防商店数据库这里是我的代码,我认为它应该是工作,但我在消防商店数据库集合什么都没有,所以我到底应该做什么,有人可以帮助我吗??

import { addDoc ,  collection , setDoc , doc , getDocs} from "firebase/firestore";
import { db } from "./config";

 const Users = [
    {
      userId: "XF9EvlJQZHfZEClM23Bd39A7gai1",
      username: "John",
      fullName: "John John",
      emailAddress: "[email protected]",
      dateCreated: Date.now(),
    },
    {
      userId: "XF9EvlJQZHfZEClM23Bd39A7gai1",
      username: "John",
      fullName: "John John",
      emailAddress: "[email protected]",
      dateCreated: Date.now(),
    }]

Users.forEach(async (user) => {
     try {
      const docRef = await addDoc (collection(db , "users" , user.userId) ,{
        userId: user.userId,
        username: user.username,
        fullName: user.fullName,
        emailAddress: user.emailAddress,
        dateCreated: user.dateCreated,
      })
      console.log("Document written with ID : ",docRef.id)
     } catch(err){
      console. Error("Error adding document ",err)
     }
 })

以下是我的Firestore数据库:

import { initializeApp } from "firebase/app";
import { getStorage } from 'firebase/storage';
import { getFirestore } from 'firebase/firestore';
import { getAuth } from "firebase/auth";


const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: ""
};

export const app = initializeApp(firebaseConfig);
export const storage = getStorage();
export const db = getFirestore(app);
export const auth = getAuth();
rqdpfwrv

rqdpfwrv1#

不应该在forEach()循环中使用async/await,请参阅“JavaScript: async/await with forEach()“和“Using async/await with a forEach loop“。
您可以使用Promise.all()如下:

const Users = [
  {
    userId: "XF9EvlJQZHfZEClM23Bd39A7gai1",
    username: "John",
    fullName: "John John",
    emailAddress: "[email protected]",
    dateCreated: Date.now(),
  },
  {
    userId: "XF9EvlJQZHfZEClM23Bd39A7gai1",
    username: "John",
    fullName: "John John",
    emailAddress: "[email protected]",
    dateCreated: Date.now(),
  }]

try {
  const promises = [];
  Users.forEach((user) => {
    promises.push(
      setDoc(doc(db, "users", user.userId),
        {
          userId: user.userId,
          username: user.username,
          fullName: user.fullName,
          emailAddress: user.emailAddress,
          dateCreated: user.dateCreated,
        })
    );
  });

  await Promise.all(promises);
} catch (error) {
  console.log(error)
}
63lcw9qa

63lcw9qa2#

我认为你给它设置新用户到集合的路径没有得到用户的id,所以它没有添加文档

addDoc(collection(db, "users", user.userId)

这样做,让Firebase给他们一个唯一的ID

addDoc(collection(db, "users")

或者也可能是Renaud说的,也许你还没有设置允许你编辑数据库的规则。

相关问题