【问题标题】:react firebase firestore insert json反应firebase firestore插入json
【发布时间】:2021-07-03 17:20:06
【问题描述】:

我正在使用 react with firebase firestore 插入一个完整的集合,其中包含 firebase firestore 中尚不存在的文档。

但是我的代码没有插入任何集合,我也没有收到任何错误,好像什么都没发生一样。

这是返回我的 json 的代码

createJson.js

const jsonArray = [{name:"Bill" , age : "5"} ,{name:"Jom" , age : "3"} ]
return jsonArray;

插入Json.js

import 'firebase/firestore';
const db = firebase.firestore();
export const insertJson = (jsn)=>{
    
  try{
    jsn.forEach(itm=>{
      let id = db.collection("doctors").doc().id;
       db
      .collection("doctors")
      .doc(id)
      .set(itm)
      .then(doc=>{
        console.log("Doc inserted with " +doc.id);
      })
    });
  }catch(err){
    console.log("Error : " +err);
  }

}

App.js

useEffect(()=>{
   const j = createJson();
   insertJson(j);
},[])

所以换句话说,我的脚本不会创建包含文档的集合。

感谢您的帮助。

【问题讨论】:

    标签: javascript json reactjs firebase google-cloud-firestore


    【解决方案1】:

    您应该使用 Firestore add() 方法和 Promise.all(),如下所示:

    export const insertJson = (jsn) => {
        try {
          const promises = [];
          jsn.forEach((itm) => {
            promises.push(db.collection('doctors').add(itm));
          });
          Promise.all(promises).then((results) => {
            console.log(results.length + ' doctors added');
          });
        } catch (err) {
          console.log('Error : ' + err);
        }
    }
    

    或者,map():

    export const insertJson = (jsn) => {
        try {
          Promise.all(jsn.map((itm) => db.collection('doctors').add(itm))).then(
            (results) => {
              console.log(jsn.length + ' doctors added');
            }
          );
        } catch (err) {
          console.log('Error : ' + err);
        }
    }
    

    如果医生人数少于 500 人,您也可以使用batched write

    export const insertJson = (jsn) => {
        try {
          const batch = db.batch();
          jsn.forEach((itm) => {
            const docRef = db.collection('doctors').doc();
            batch.set(docRef, itm);
          });
          batch.commit().then((results) => {
            console.log('doctors added');
          });
        } catch (err) {
          console.log('Error : ' + err);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-11
      • 2019-09-25
      • 2021-02-12
      • 1970-01-01
      • 2021-12-30
      • 2020-03-31
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      相关资源
      最近更新 更多