如何根据查询在Firestore上更新文档

时间:2019-11-10 09:45:44

标签: javascript firebase google-cloud-firestore

我正在创建一个Web表单页面,该页面将根据条件将输入字段更新到相应的Firestore文档中。该怎么办?

我获得查询结果的第一部分是可以的,因为控制台日志显示了正确的查询结果。但是,用于更新该文档的第二部分不起作用

  const reportForm = document.querySelector('#daily-reports');



reportForm.addEventListener('submit', (e) => {
    e.preventDefault();

    const forward = reportForm['forward'].value;
    const reflected = reportForm['reflected'].value;
    const upserror = reportForm['ups-switch'].value;
    const transerror = reportForm['trans-switch'].value;
    const transDesc = reportForm['transDesc'].value;
    const upsDesc = reportForm['upsDesc'].value;


    console.log(forward, reflected, upserror, transerror, transDesc, upsDesc);
    firebase.initializeApp(config);
    const db = firebase.firestore();
    db.settings({timestampsInSnapshots: true});
    firebase.auth().onAuthStateChanged(user => { 
         if(user) {
      console.log(user.uid); 
      console.log(user.email);

//Query begins here
     db.collection('Stations').where('userId', "==",    user.uid).get().then(function(querySnapshot) {
                 querySnapshot.forEach(function (doc) {
                     doc.data().update(
                         {
                                          "ForwardPower": forward,
                                          "ReflectedPower": reflected,
                                          "TransDesc": transDesc,
                                          "TransmitterError": transerror,
                                          "UPSError" : upserror,
                                          "UPSDesc": upsDesc}
                     );
                     console.log(doc.id, " => ", doc.data());
                 });
             }).catch(function(error) {
                 console.log("Error getting documents: ", error);
             });

}
});



});

运行代码后,这是我得到的错误:

Error getting documents:  TypeError: "doc.data(...).update is not a function"
    <anonymous> func.js:42
    forEach database.ts:2131
    forEach document_set.ts:97
    inorderTraversal sorted_map.ts:324
    inorderTraversal sorted_map.ts:136
    forEach document_set.ts:96
    forEach database.ts:2130
    <anonymous> func.js:41

1 个答案:

答案 0 :(得分:0)

data()仅在DocumentSnapshot上用于保留其原始内容。返回的对象只是一个普通的JavaScript对象,没有任何方法。

如果要更新由DocumentSnapshot表示的文档,请使用该对象的ref属性来获取DocumentReference,然后对该对象调用update()方法。

doc.ref.update({...})