问题
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