如何有效地将项目添加到与firebase firestore收集

如何有效地将项目添加到与firebase firestore收集

问题描述:

我有一个标签,我想添加到一个firestore集合数组。如何有效地将项目添加到与firebase firestore收集

如果我没有误解我在这里的方法,我想我会对该集合进行个别添加,因为我认为将它们“分组”并将它们一次全部设置会更有效。是这样的可能吗?也可以同时将文档添加到锻炼集合中吗?

现在我正在查看tags.length + 1为每次调用此函数时写入firebase。我想尽可能地减少它。

logWorkoutAsync({ userId, timeStamp, tags }){ 
    var db = this.firebase.firestore(); 

    return db.collection('users').doc(userId).collection('workouts').add({ 
     timeStamp, 
     'class': false 
    }).then(doc => { 

     var tagsCollection = doc.collection('tags') 

     var promises = [] 

     tags.forEach(t => { 
      promises.push(tagsCollection.doc(t.id.toString()).set(t)) 
     }) 

     return Promise.all(promises) 
    }) 
} 

云公司的FireStore有成批写入的支持,看到这里的文档: https://firebase.google.com/docs/firestore/manage-data/transactions

所以你可以做这样的事情:

logWorkoutAsync({ userId, timeStamp, tags }){ 
    var db = this.firebase.firestore(); 

    return db.collection('users').doc(userId).collection('workouts').add({ 
     timeStamp, 
     'class': false 
    }).then(doc => { 

     var tagsCollection = doc.collection('tags'); 

     // Begin a new batch 
     var batch = db.batch(); 

     // Set each document, as part of the batch 
     tags.forEach(t => { 
      var ref = tagsCollection.doc(t.id.toString()); 
      batch.set(ref, t); 
     }) 

     // Commit the entire batch 
     return batch.commit(); 
    }) 
} 
+0

哇!这太棒了!我是否也可以在批处理中包含最初的.add?也许如果我做一些像batch.set(db.collection('users')。doc(userId).collection('workouts')。doc(timeStamp.toString),{timeStamp,'class':false})?在这种情况下,我只需要提供一个'id',对吧? – Robodude

+0

是的,你绝对可以做到这一点!您最多可以在一批中添加500个操作。你的直觉是正确的,为了得到'batch.add()',你需要在其他地方执行'.doc()'来创建引用,然后在该引用上调用'batch.set()'。 –

+0

@hatboysam如果我们想在单个批次中编写500多个操作,我们可以做些什么?可以连接多次?我的意思是,有两个批次,一个有500个操作,另一个有250个,等等。 –