您想知道“如何在一次执行 sendFirestore() 函数中创建多个文档?”
有几种方法可以做到这一点。
例如,您可以创建多个 data 的唯一实例,并在每个实例之后执行 firestore.createDocument();。
这不是特别有效或方便,但有可能。
var data01 = ...;
firestore.createDocument("document1",data01);
var data02 = ...;
firestore.createDocument("document2",data02);
var data03 = ...;
firestore.createDocument("document3",data03);
比起编辑脚本,将数据输入到 Google 电子表格然后检索它会更高效、更方便。这种方法的关键是创建一个循环,在该循环中 i) 检索数据并 ii) 执行 createdocument。这将使您能够创建任意数量的文档。
在下面的例子中,有几点需要注意:
电子表格可能如下所示:
电子表格示例
代码输出三个data 值,如下所示:
- [{name=abc1_1, id=xyz1_1}, {name=abc1_2, id=xyz1_2}, {name=abc1_3, id=xyz1_3}]
- [{name=abc2_1, id=xyz2_1}, {name=abc2_2, id=xyz2_2}, {name=abc2_3, id=xyz2_3}]
- [{name=abc3_1, id=xyz3_1}, {name=abc3_2, id=xyz3_2}, {name=abc3_3, id=xyz3_3}]
function so5745433303() {
// Firestore setup
const email = "...";
const key = "...";
const projectId = "...";
var firestore = FirestoreApp.getFirestore (email, key, projectId);
// get document data from ther spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetname = "firebase_data3";
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
// Logger.log("DEBUG: Last row = "+sheetLR+", and Last Column = "+sheetLC);
var dataSR = 3; // the first row of data
// define the data range
var sourceRange = sheet.getRange(3,1,sheetLR-dataSR+1,sheetLC);
// Logger.log("DEBUG: the source range is "+sourceRange.getA1Notation());
// 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;
// Logger.log("DEBUG: the source data length = "+sourceLen);
// Loop through the rows
for (var i=0;i<sourceLen;i++){
var data = [];
var title = sourceData[i][0];
// Logger.log("DEBUG: the document title is "+title);
// #1 ID and Name
data.push({
"id": sourceData[i][1],
"name": sourceData[i][2]
});
// Logger.log("DEBUG: id#1 is "+sourceData[i][1]+", and name#1 = "+sourceData[i][2]);
// #2 ID and Name
data.push({
"id": sourceData[i][3],
"name": sourceData[i][4]
});
// Logger.log("DEBUG: id#2 is "+sourceData[i][3]+", and name#2 = "+sourceData[i][4]);
// #3 ID and Name
data.push({
"id": sourceData[i][5],
"name": sourceData[i][6]
});
// Logger.log("DEBUG: id#3 is "+sourceData[i][5]+", and name#3 = "+sourceData[i][6]);
// Logger.log(data);
firestore.createDocument(title, data);
}
}
仅供参考
Google app script - looping through the rows in a spreadsheet
Iterating over an object in a Google Apps script and printing to Google Sheets(特定于 Firebase)