The library reference is
MPAHw_-cHNDxsYAg263J7Fai_d-phDA33
Background to implementation.
MongoLab offers a number of plans for cloud based MongoDB. I discovered they have a .5gb Free Sandbox plan, so I thought I’d give it a go. They recommend using their supplied libraries, but of course there is not one for Google Apps Script, so I used their REST API access to implement enough capabilities to cover all the features of Database abstraction with google apps script. Of course, MongoDB has zillions of other features that I don’t use, but in this mode it’s a great substitute for ScriptDB and alternative to Parse.com – and the performance is excellent.
Authentication
It’s simple – just an API key you can get from your MongoLab dashboard
Getting started
- Sign up with MongoLab
- Create a hosting plan
- Create a database
- Store your API key in your script Properties.
Getting a handle
Like all other drivers it all starts with getting a handle. In this case, the MongoDB collection is ‘customers’, and the database I created is called ‘xliberation’. The property is the one you stored your API key against, and should like this
{“restAPIKey”:”your api key”}
1 2 3 4 5 6 7 8 9 10 11 12 |
var userStore = PropertiesService.getScriptProperties(); var handler = new cDataHandler.DataHandler ( 'customers', cDataHandler.dhConstants.DB.MONGOLAB, undefined, 'xliberation', JSON.parse(userStore.getProperty("mongoLabKeys")) ); if(!handler.isHappy()) { throw ( 'unable to get mongolab handler'); } |
The example above uses the cDataHandler. Nowadays it’s better to use the cDbAbstraction interface. An example is shown in the slides below.
Now you’re good to go. The syntax is the same for all back ends. See Some test cases for various backends for examples of various syntaxes, and see Comparing all back ends performance for how MongoLab performs. It’s superfast as a scriptDB replacement.
The Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 |
/** wrapper */ function createDriver (handler,siloId,driverSpecific,driverOb, accessToken) { return new DriverMongoLab(handler,siloId,driverSpecific,driverOb, accessToken); } function getLibraryInfo () { return { info: { name:'cDriverMongoLab', version:'2.2.0', key:'MPAHw_-cHNDxsYAg263J7Fai_d-phDA33', description:'mongolab driver for dbabstraction', share:'https://script.google.com/d/11N6camwOikILS28dwqvIlv44D1y0JMCTL9IeeUKkDV1amGvjWIeg-KbH/edit?usp=sharing' }, dependencies:[ ] }; } /** * DriverMongoLab * @param {cDataHandler} handler the datahandler thats calling me * @param {string} collection the name of the mongodb collection * @param {string} database the mongo database * @param {object} database the mongo credential object * @return {object} result with handle or some error */ var DriverMongoLab = function (handler,collection,database,credentials) { var siloId = collection; var self = this; var uniqueKey = database; var parentHandler = handler; var enums = parentHandler.getEnums(); var keyOb = credentials; var handleError, handleCode; var DRIVERFIELDS = ['_id']; // im not able to do transactions self.transactionCapable = false; // i need transaction locking self.lockingBypass = false; // i am aware of transactions and know about the locking i should do self.transactionAware = true; self.getDbId = function () { return uniqueKey; }; // create connection to mongo self.createHandle = function() { return uniqueKey; } var handle = self.createHandle(); self.getVersion = function () { var v = getLibraryInfo().info; return v.name + ':' + v.version; }; self.getDriveHandle = function () { return handle; }; self.getType = function () { return enums.DB.MONGOLAB; }; /** * DriverMongoLab.getTableName() * @return {string} table name or silo */ self.getTableName = function () { return siloId; }; self.getEndPoint = function (optExtras) { extras = optExtras ? "/" + optExtras : ""; return "https://api.mongolab.com/api/1/databases/" + self.getDbId() + "/collections/" + self.getTableName() + extras + "?apiKey=" + keyOb.restAPIKey; }; /** create the urlfetch options * @param {object} options any additional options to add * @return {object} the urlfetch options */ self.getOptions = function (options) { var options = options || {}; options.contentType = "application/json" ; options.muteHttpExceptions = true; return options; } self.execute = function (url,options) { handleCode = enums.CODE.OK; handleError =""; var result = parentHandler.rateLimitExpBackoff ( function () { var h = UrlFetchApp.fetch(url,options); if (h.getResponseCode() !== 201 && h.getResponseCode() !== 200 && h.getResponseCode() !== 204) { handleCode = enums.CODE.HTTP; handleError = h.getContentText() +"(http error code:" + h.getResponseCode()+ ")(url:" +url+")"; } var t = h.getContentText(); if (t) { var o = JSON.parse(t); if (o && o.message) { handleCode = enums.CODE.DRIVER; handleError = JSON.stringify(o.message); return null; } else { return o; } } else { return h.getResponseCode(); } }); return result; } /** * DriverMongoLab.save() * @param {Array.object} obs array of objects to write * @return {object} results from selected handler */ self.save = function (obs) { // save it after adding my own id fields var obd = obs.map(function(d) { var o = parentHandler.clone(d); o._id = parentHandler.generateUniqueString() ; return o; }); // lock the entire transaction var result = parentHandler.writeGuts ( 'save', function () { return self.execute (self.getEndPoint() , self.getOptions ({ method: "POST", payload: JSON.stringify(obd) })); // the result property of the lock protect is the result of the function that was protected }); return parentHandler.makeResults ( handleCode, handleError, obs , null , obd.map(function(d) { return getMixedId_(d); })); }; /** * DriverMongoLab.removeByIds() * @param {array.string} keys list of keys to delete * @return {object} results from selected handler */ self.removeByIds = function (keys) { var options = self.getOptions({ method: "DELETE" }); var r = parentHandler.writeGuts ( 'removeByIds', function () { var dr = keys.map( function (d) { return self.execute (self.getEndPoint(d) , options); }); return dr; }); r.keys = keys; return r; }; /** * DriverMongoLab.remove() * @param {object} queryOb some query object * @param {object} queryParams additional query parameters (if available) * @param {Array.object} optReplaceWith adding this makes it a replace * @return {object} results from selected handler */ self.remove = function (queryOb,queryParams,optReplaceWith) { var obs = optReplaceWith || []; var params = parentHandler.getQueryParams(parentHandler.clone(queryParams)); handleCode = params.handleCode; handleError = params.handleError; // lock the entire transaction if (handleCode === enums.CODE.OK) { var useParams = parentHandler.makeUseParams(params.data); var options = self.getOptions({ method: "PUT", payload: JSON.stringify(obs) }); var result = parentHandler.writeGuts ( 'remove', function () { return self.execute (self.getEndPoint() + makeQueryString_(queryOb) + makeParamString_(useParams) , options); }); } return parentHandler.makeResults ( handleCode, handleError, result); }; /** * DriverMongoLab.count() * @param {object} queryOb some query object * @param {object} queryParams additional query parameters (if available) * @return {object} results from selected handler */ self.count = function (queryOb,queryParams) { var params = parentHandler.getQueryParams(parentHandler.clone(queryParams)), result; handleCode = params.handleCode; handleError = params.handleError; if (handleCode === enums.CODE.OK) { var useParams = parentHandler.makeUseParams(params.data); try { var r = parentHandler.readGuts ( 'count', function () { return self.execute (self.getEndPoint() + makeQueryString_(queryOb) + makeParamString_(useParams) + "&c=true" , self.getOptions({ method: "GET", })); }); result = [{count:r}]; } catch(err) { handleError = JSON.stringify(err); handleCode = enums.CODE.DRIVER; } } return parentHandler.makeResults ( handleCode, handleError, result); }; //-------------------------- /** * DriverMongoLab.query() * @param {object} queryOb some query object * @param {object} queryParams additional query parameters (if available) * @param {boolean} keepIds whether or not to keep driver specifc ids in the results * @return {object} results from selected handler */ self.query = function (queryOb,queryParams,keepIds,optFlatten) { // take a copy of params so as not to disturb what's passed var exhausted = false; var driverIds = [], handleKeys = []; var queryString = makeQueryString_(queryOb,optFlatten); var params = parentHandler.getQueryParams(parentHandler.clone(queryParams)); handleCode = params.handleCode; handleError = params.handleError; try { if (handleCode === enums.CODE.OK) { var result = parentHandler.readGuts ( 'query', function () { // this is chunking to get over limits var useParams = parentHandler.makeUseParams(params.data); var skip = useParams.skip.skip , limit = useParams.limit.limit ,exhausted = false; var result = []; while (handleCode === enums.CODE.OK && (result.length < limit || limit ===0) && !exhausted) { useParams.skip.skip = skip + result.length; var paramString = makeParamString_(useParams); var w = self.execute ( self.getEndPoint() + queryString + paramString , self.getOptions ({ method: "GET" })); exhausted = !w || (w.length === 0 ); if (handleCode === enums.CODE.OK && !exhausted) { w.forEach (function(d) { if( result.length < limit || limit ===0) { var o ={}; driverId ={}; for (var k in d) { if (DRIVERFIELDS.indexOf(k) === -1) { o[k] = d[k]; } else { driverId[k] = d[k]; } } handleKeys.push(getMixedId_ (d) ); driverIds.push(driverId); result.push(o); } }); } } return result; }); } } catch(err) { handleError = err; handleCode = enums.CODE.DRIVER; } return parentHandler.makeResults (handleCode,handleError,result,keepIds ? driverIds :null,keepIds ? handleKeys:null); }; function getMixedId_ (ob) { return parentHandler.isObject(ob._id) ? ob._id["$oid"] : ob._id; } function makeParamString_(ps) { // fix with mongo api equivalents p=''; if (ps.sort) { p+= '&s=' + encodeURIComponent('{"' + ps.sort.sortKey + '":' + (ps.sort.sortDescending ? -1:1) +'}'); } if (ps.limit) { p+= '&l=' + ps.limit.limit; } if (ps.skip) { p+= '&sk=' + ps.skip.skip; } return p; } function makeQueryString_(queryOb, optFlatten) { // special case - we dont flatten $or var flatten = typeof optFlatten === 'undefined' ? true: optFlatten; var q=''; if (queryOb) { var qb = flatten ? parentHandler.flatten(queryOb,true) : queryOb; var qob = Object.keys(qb).reduce(function(p,c) { if (qb[c].hasOwnProperty (enums.SETTINGS.CONSTRAINT)) { p[c] = qb[c][enums.SETTINGS.CONSTRAINT].reduce( function (a,b) { a[b.constraint] = b.value; return a; },{}); } else { p[c]=qb[c]; } return p; },{}); return '&q=' + encodeURIComponent(JSON.stringify(qob)); } else { return ''; } }; /** * Driver.get() * @param {Array.string} keys the unique return in handleKeys for this object * @return {object} results from selected handler */ self.get = function (keys) { // this kind of sucks, since we have to to a separate update for each key if(!Array.isArray(keys)) keys = [keys]; handleCode=enums.CODE.OK; handleError=''; var result; try { result = parentHandler.readGuts ( 'get', function () { return keys.map (function(d) { var k = parentHandler.isObject(d) ? d.key : d; var r = self.execute (self.getEndPoint(k) , self.getOptions({ method: "GET" })); if (!r || r.length === 0) handleCode = enums.CODE.NOMATCH; return r; }); }); } catch(err) { handleError = err; handleCode = enums.CODE.DRIVER; } return self.splitKeys(parentHandler.makeResults (handleCode,handleError,result)); }; /** * DriverSheet.splitKeys() * take a result and remove special fields and move handlekeys * @param {object} qResult standard result * @return {object} modified standard result */ self.splitKeys = function (qResult) { if (qResult.handleCode >=0) { var s = parentHandler.dropFields ( DRIVERFIELDS , '_id' , qResult.data); qResult.data = s.obs; qResult.handleKeys = s.keys; } return qResult; }; /** * Driver.update() * @param {Array.string} keys the unique return in handleKeys for this object * @param {object} obs what to update it to * @return {object} results from selected handler */ self.update = function (keys,obs) { // this kind of sucks, since we have to to a separate update for each key if(!Array.isArray(keys)) keys = [keys]; if(!Array.isArray(obs)) obs = [obs]; if(keys.length !== obs.length && obs.length !== 1) { return parentHandler.makeResults (enums.CODE.KEYS_AND_OBJECTS,'objects- ' + obs.length + ' keys- ' + keys.length,result); } handleCode=enums.CODE.OK; handleError=''; var result; try { result = parentHandler.writeGuts ( 'update', function () { return keys.map (function(d,i) { var r = self.execute (self.getEndPoint(d) , self.getOptions({ method: "PUT", payload: JSON.stringify(obs.length === 1 ? obs[0] : obs[i]) })); if (!r || r.length === 0) handleCode = enums.CODE.NOMATCH; return r; }); }); } catch(err) { handleError = err; handleCode = enums.CODE.DRIVER; } return parentHandler.makeResults (handleCode,handleError,result); }; return self; } |
Here’s some libraries you’ll need or are used internally
library | key | comments |
cDataHandler | Mj61W-201_t_zC9fJg1IzYiz3TLx7pV4j | Abstracted interface to back end databases, and all known drivers |
cCacheHandler | M3reA5eBxtwxSqCEgPywb9ai_d-phDA33 | Manages caching of query results |
cNamedLock | Mpv7vUR0126U53sfSMXsAPai_d-phDA33 | Cross script locking of abstract resources |
cFlatten | MqxKdBrlw18FDd-X5zQLd7yz3TLx7pV4j | Flattens complex objects to 1 level dot syntax objects so they can be stored/queries in a 2 dimensional space |
See more like this in Database abstraction with google apps script
For help and more information join our forum,follow the blog or follow me on Twitter .