React Native 无法在Firebase Firestore中添加数据

jgwigjjp  于 2023-06-24  发布在  React
关注(0)|答案(3)|浏览(115)

code for uploading data in firestore
控制台:“使用ID编写的文档:未定义”

try {
  console.log
  const docRef = addDoc(collection(db, "users"), {
    name: "Alan",
    //middle: "Mathison",
    //last: "Turing",
    //born: 1912
  });
  console.log('yyyyy');
  console.log("Document written with ID: ", docRef.id);
} catch (e) {
  console.error("Error adding document: ", e);
}

尝试在Firebase Firestore中添加数据,

gv8xihay

gv8xihay1#

addDoc是异步操作。您需要使用await关键字来暂停代码的执行,直到添加文档为止。否则docRef将不代表您的文档。

try {
  const docRef = await addDoc(collection(db, "users"), {
    name: "Alan",
  });
  console.log('yyyyy');
  console.log("Document written with ID: ", docRef.id);
} catch (e) {
  console.error("Error adding document: ", e);
}
bqf10yzr

bqf10yzr2#

试试那个

try {
  console.log
  const docRef = addDoc(collection(db, "users"), {
    name: "Alan",
    //middle: "Mathison",
    //last: "Turing",
    //born: 1912
  }).then(res => {
    console.log('yyyyy');
    console.log("Document written with ID: ", docRef.id);
  });
  
} catch (e) {
  console.error("Error adding document: ", e);
}
kpbwa7wx

kpbwa7wx3#

这个应该可以。您可以删除过多的console.logs

import { collection, addDoc } from "firebase/firestore"; 

const docRef = await addDoc(collection(db, "users"), {
  name: "Alan"
});
console.log("Document written with ID: ", docRef.id);

相关问题