使用JavaScript在循环内将数据添加到Firestore

时间:2018-08-15 15:37:43

标签: firebase google-cloud-firestore google-cloud-functions

我正在尝试根据另一个集合的触发器来更新Firestore中的集合。我正在使用for循环使用批处理写入数据batch.commit()在所有set和update方法之后被调用。但是我收到错误消息“无法修改已提交的写入批处理”。我的方法有什么问题?

这是我的代码:

 var batch = admin.firestore().batch();

 exports.addUnregisteredUsers = functions.firestore
.document('activities/{activity_id}')
.onCreate((event,context) => {


var activity = event.data();
var activity_id = context.params.activity_id;
var userArray = JSON.parse(activity.users);
console.log(activity_id);

userArray.forEach(function(user){
    user.activities_id = activity_id;
    //check if user already exist in pending_list
    var reference =   admin.firestore().collection('pending_reg_users').doc(user.user_phone)
           reference.get()
                .then((docSnapshot) => {
                    if (docSnapshot.exists) {
                        reference.onSnapshot((doc) => {
                        //  update the existing item
                            reference.update(reference,{activities_id:doc.get("activities_id")+","+activity_id});

                        });
                    } else {

                        //add the item  
                        batch.set(reference,user); // create the document
                    }
                });

        });

    return batch.commit();

0 个答案:

没有答案