简体   繁体   English

从谷歌表格 API 导入数据到 Firestore 时选择 DocumentID

[英]Selecting DocumentID when importing data from google sheets API to Firestore

I want to send data from google sheets API to Firestore.我想将数据从谷歌表格 API 发送到 Firestore。 I have achieved this goal but I would like to select my own documentID and not have a generated one.我已经实现了这个目标,但我想 select 我自己的documentID并且没有生成的。

I want to send data to specific userID so I plan on inputting the data on the google sheets spreadsheets and having that data stored under that userID in Firestore.我想将数据发送到特定的用户 ID ,因此我计划在 Google 表格电子表格中输入数据,并将该数据存储在Firestore中的该用户 ID 下。

In my spreadsheet I have a field titled userID .在我的电子表格中,我有一个名为userID的字段。 Is there a way to modify my script code so I can use the userID as the documentID ?有没有办法修改我的脚本代码,以便我可以使用userID作为documentID

图像1

Script code can be seen here:脚本代码可以在这里看到:

![image2][2] ![图像2][2]

var firestore = FirestoreApp.getFirestore (email, key, projectId);  
  // get document data from ther spreadsheet
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheetname = "Sheet1";
   var sheet = ss.getSheetByName(sheetname); 


   // get the last row and column in order to define range
   var sheetLR = sheet.getLastRow(); // get the last row
   var sheetLC = sheet.getLastColumn(); // get the last column

   var dataSR = 2; // the first row of data
   // define the data range
   var sourceRange = sheet.getRange(2,1,sheetLR-dataSR+1,sheetLC);


   // get the data
   var sourceData = sourceRange.getValues();
   // get the number of length of the object in order to establish a       loop value
   var sourceLen = sourceData.length;

  // Loop through the rows
   for (var i=0;i<sourceLen;i++){
     if(sourceData[i][1] !== '') {
       var data = {};
       data.userid = sourceData[i][0];
       data.store = sourceData[i][1];
       data.price = sourceData[i][2];
       data.department = sourceData[i][3];
       data.date = sourceData[i][4];
   
  
       var userId = sourceData[i][0]
       firestore.createDocument("User/" + userId + "/Receipts", data);
  
   

     }

  }
}

I make the assumption that you use the FirestoreGoogleAppsScript library, since you do firestore.createDocument() .我假设您使用FirestoreGoogleAppsScript库,因为您使用的是firestore.createDocument()

As explained in the library documentation, you can specify the ID of the new Firestore document by passing the entire path of the document (ie collection + ID separated by a slash) as follows:正如库文档中所解释的,您可以通过传递文档的整个路径(即集合 + 由斜杠分隔的 ID)来指定新 Firestore 文档的 ID,如下所示:

// ...
var userId = sourceData[i][0]
firestore.createDocument("User/" + userId, data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM