【问题标题】:How to set the id of document of firestore using google sheets如何使用谷歌表格设置firestore文档的id
【发布时间】:2020-05-31 12:57:49
【问题描述】:

我在 google 表格中有一个表格,我想使用自定义文档 ID 将其上传到 firstore 以防止数据重复。如何更改文档的 ID。

完整代码:


function classRoutineFunction() {
   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 = {};
       var dateSt = sourceData[i][0].toString();
       var stDate = new Date(dateSt);
       var stringfied = JSON.stringify(stDate);
       var updatedDt = stringfied.slice(1,11);

       data.date = updatedDt;
       data.time = sourceData[i][1];
       data.batch = sourceData[i][2];
       data.topic = sourceData[i][3];
       data._id = dateStr + batch; // Want to set a custom id

       firestore.createDocument("classRoutine",data);
     }

  }
}

【问题讨论】:

  • 我看到一些库允许您从 Apps 脚本访问 Firestore。您能提供您在此处使用的库的链接吗?

标签: firebase google-apps-script google-sheets google-cloud-firestore


【解决方案1】:

您可以在调用createDocument 时将新文档的名称传递到字符串参数中。来自creating documents in Firestore from your script的文档:

或者,我们可以在名为FirstDocumentFirstCollection 集合中创建文档:

firestore.createDocument("FirstCollection/FirstDocument", data)

这里FirstDocumentFirstCollection中文档的名称。

所以对你来说,这看起来像:

firestore.createDocument("classRoutine/yourCustomId",data);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多