How to avoid duplication when exporting from Google Sheets to Firebase

非 Y 不嫁゛ 提交于 2021-02-08 10:53:37

问题


I'm trying to export data from Google Sheets to a collection in Google Firestore. I'm using script editor in Google Sheets to write the code. I've successfully transferred the data to Firestore. However, if I add new data to the Google Sheet and try to export to Firestore all of the data that was already in Firestore duplicates. How can I have the code only add new data and not add everything when I export?

//Create a menu item for 'Export to Firestore'
function onOpen() {
  SpreadsheetApp.getUi().createMenu('🔥 Firebase').addItem('Export to Firestore', 'main').addToUi();
}

function main() {
  //Get the active spreadsheet and its name for the collection name
  var sheet = SpreadsheetApp.getActiveSheet();
  var sheetName = sheet.getName();
  
  //Get the first row as object properties
  // ['Author', 'ISBN', 'Category', 'Title']
  var properties = getProperties(sheet);
  
  //Get the next 4 rows as records
  //[ ['Hansley Ford', '34787426409', 'Drama', 'Grim Peeks'], ..., ...]
  var records =  getRecords(sheet);
  
  //Export to Firestore
  var firestore = FirestoreApp.getFirestore('','','');
  
   
  exportToFirestore(firestore, sheetName, properties, records);
}
function exportToFirestore(firestore, collectionName, properties, records) {
  records.map(function(record) {
    //record: ['Hansley Ford', '34787426409', 'Drama', 'Grim Peeks']
    //props: ['Author', 'ISBN', 'Category', 'Title']
    var data = {};
    properties.forEach(function(prop,i) { data[prop] = record[i]; });
    return data;
  }).forEach(function(data) {
    firestore.createDocument(collectionName, data);
  });
}

function getProperties(sheet) {
  return sheet.getRange(1, 1, 1, 4).getValues()[0]; //['Author', 'ISBN', 'Category', 'Title']
}

function getRecords(sheet) {
  return sheet.getRange(2, 1, 5, 4).getValues();
}

来源:https://stackoverflow.com/questions/62898262/how-to-avoid-duplication-when-exporting-from-google-sheets-to-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!