flamefire2事务和firestore中的批处理写入

时间:2017-11-13 15:46:55

标签: angular firebase google-cloud-firestore

如何在angular2应用程序中使用firestore批量写入/运行事务?

http://rss.cnn.com/rss/cnn_allpolitics.rss

如果可能,我如何在一个angular2应用程序中将JS代码转换为TS代码。

2 个答案:

答案 0 :(得分:14)

如果您使用的是AngularFirestore,首先需要确保构造函数的设置如下:

constructor(private db: AngularFirestore)

现在您可以使用db.firestore来获取firebase.firestore实例。

您只需从链接中复制代码,然后将 db 替换为 db.firestore 即可。或者你可以使用箭头功能使它更加花哨:

使用交易更新数据:

// Create a reference to the SF doc.
const sfDocRef = db.firestore.collection("cities").doc("SF");

// Uncomment to initialize the doc.
// sfDocRef.set({ population: 0 });

db.firestore.runTransaction(transaction => 
// This code may get re-run multiple times if there are conflicts.
  transaction.get(sfDocRef)
  .then(sfDoc => {
    const newPopulation = sfDoc.data().population + 1;
    transaction.update(sfDocRef, { population: sfDoc.data().population + 1 });
  })).then(() => console.log("Transaction successfully committed!"))
.catch(error => console.log("Transaction failed: ", error));

将信息传递出交易:

// Create a reference to the SF doc.
const sfDocRef = db.firestore.collection("cities").doc("SF");

db.firestore.runTransaction(transaction =>
  transaction.get(sfDocRef).then(sfDoc => {
      const newPopulation = sfDoc.data().population + 1;
      if (newPopulation <= 1000000) {
          transaction.update(sfDocRef, { population: newPopulation });
          return newPopulation;
      } else {
          return Promise.reject("Sorry! Population is too big.");
      }
    }))
    .then(newPop => console.log("Population increased to ", newPop)
  ).catch(err => console.error(err));  // This will be an "population is too big" error.

批量写入:

// Get a new write batch
var batch = db.firestore.batch();

// Set the value of 'NYC'
var nycRef = db.firestore.collection("cities").doc("NYC");
batch.set(nycRef, {name: "New York City"});

// Update the population of 'SF'
var sfRef = db.firestore.collection("cities").doc("SF");
batch.update(sfRef, {"population": 1000000});

// Delete the city 'LA'
var laRef = db.firestore.collection("cities").doc("LA");
batch.delete(laRef);

// Commit the batch
batch.commit().then(() => {
    // ...
});

答案 1 :(得分:5)

很简单:

constructor(private db: AngularFirestore){}

inserting(){
        //--create batch-- 
        var batch = this.db.firestore.batch();

        //--create a reference-- 
        const userRef = this.db.collection('users').doc('women').ref;
        batch.set(userRef , {
          name: "Maria"
        });

        //--create a reference-- 
        const userRef = this.db.collection('users').doc('men').ref;
        batch.set(userRef , {
          name: "Diego"
        });

        //--Others more 54 batch's--

        //--finally--
        return batch.commit();
    }