firebase 使用Google App Script Extension更新现有记录时创建的重复Firestore子集合

gmol1639  于 2023-05-18  发布在  Go
关注(0)|答案(1)|浏览(88)

我正在使用谷歌应用程序脚本扩展导入我现有的数据/行从谷歌工作表使用这个编写良好的库-https://github.com/grahamearley/FirestoreGoogleAppsScript
我尝试使用 firestore.updateDocument 函数来更新Firestore中由一组主键标识的现有文档,然后将它们与googlesheets中的现有行进行比较。
我相信,基于Javascript的代码可以在update函数运行之前识别现有文档,但实际上它会在目标集合中创建一个“子集合项目”。这会导致我的应用无法检索最新更新的记录,而只能检索原始过时的Firestore文档。
请参阅屏幕截图。

我遵循了库的说明和所有的东西,有没有一个擅长javascript的人可以查看我的代码并指导我?

var collectionName = "collectionNameTest"

       // Check if a document with the same primary keys exists in the existing Firestore collection
       var duplicateDocs = firestore.query(collectionName)
       .Where(primaryKey1Column,"==",primaryKey1)
       .Where(primaryKey2Column,"==",primaryKey2)
       .Execute();

 if (duplicateDocs.length > 0) {
         // A document with the same primary key already exists in the collection

        const name = duplicateDocs[0].name

         console.log(`Documents with primaryKey1 '${primaryKey1}' and with primaryKey2 '${primaryKey2}'  already exists. Updating existing record with new record...`);

         try { var result = firestore.updateDocument(`${collectionName}/${name}`, data);
                console.log("Firestore document updated, Firestore result: ", result);
              } catch (e) {
                console.error("Firestore update failed: ", e);
              }                 

       } else {
         // No document with the same primary key exists, so create a new document
         var result = firestore.createDocument(collectionName, data);
         console.log("New Firestore document created, Firestore result: ", result);
       }
8yoxcaq7

8yoxcaq71#

在你的情况下,下面的修改怎么样?

发件人:

const name = duplicateDocs[0].name

收件人:

const name = duplicateDocs[0].name.split("/").pop();

注意:

  • 在这种情况下,假设data是有效值。请小心点。

参考:

  • 更新Firestore for Google Apps脚本的文档

相关问题