Skip to content

Instantly share code, notes, and snippets.

@asimmittal
Last active February 12, 2018 17:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asimmittal/e047901590325639fb1e to your computer and use it in GitHub Desktop.
Save asimmittal/e047901590325639fb1e to your computer and use it in GitHub Desktop.
Access values in a Google sheet
/********************************************************
* grab all the rows from the sheet and POST to the DB
********************************************************/
function grabRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
//these labels will be used to mark the fields in
//the various columns
var labels = {
0: "timestamp",
1: "age",
2: "usesGoogle",
3: "faveFood"
}
//first row contains titles - ignore this for now
for(var i = 1; i < numRows; i++){
var row = values[i];
var rowJson = {};
//label every value appropirately, and save in rowJson
for(var j = 0; j < row.length; j++){
var label = labels[j];
rowJson[label] = row[j];
}
//this row is now a json object - send it to the DB
pushToDB(rowJson);
}
}
/********************************************************
* this function posts a single JSON object to mongoDB
* using their REST API
********************************************************/
function pushToDB(row){
var db_name = "asimdb";
var coll_name = "testcoll";
var api_key = "XXXX Enter your API key here XXXX";
// Forming mongolab URL
var base_url = "https://api.mongolab.com/api/1/databases/";
base_url += db_name + '/collections/';
base_url += coll_name;
base_url += '?apiKey=' + api_key;
//post this shit
var options = {"method":"post","payload":JSON.stringify(row),"contentType":"application/json"};
return UrlFetchApp.fetch(base_url, options);
}
@Estonhumphrey
Copy link

Awesome work! I hope to get hereonr day

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment