I am trying to get the doc_ids in couchbase cordova to be in uuid format.
Currently, any doc that is inserted has _id
s like - -AexsV4lbjOoH-AdlN1Fi0W
, --mpIWIHza6CQEJEHRxPKba
etc.
My setup is of such nature that the _ids need to be uuids as the cordova app will save the local DB as a part of a universal MongoDB on the server. (So the DB on the server will have multiple local DBs stored). Hence, I need the _ids to be uuids
I did a quick research into how to create uuids in JS and found quite a few answers like -
/**
* Fast UUID generator, RFC4122 version 4 compliant.
* @author Jeff Ward (jcward.com).
* @license MIT license
* @link http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
**/
var UUID = (function() {
var self = {};
var lut = []; for (var i=0; i<256; i++) { lut[i] = (i<16?'0':'')+(i).toString(16); }
self.generate = function() {
var d0 = Math.random()*0xffffffff|0;
var d1 = Math.random()*0xffffffff|0;
var d2 = Math.random()*0xffffffff|0;
var d3 = Math.random()*0xffffffff|0;
return lut[d0&0xff]+lut[d0>>8&0xff]+lut[d0>>16&0xff]+lut[d0>>24&0xff]+'-'+
lut[d1&0xff]+lut[d1>>8&0xff]+'-'+lut[d1>>16&0x0f|0x40]+lut[d1>>24&0xff]+'-'+
lut[d2&0x3f|0x80]+lut[d2>>8&0xff]+'-'+lut[d2>>16&0xff]+lut[d2>>24&0xff]+
lut[d3&0xff]+lut[d3>>8&0xff]+lut[d3>>16&0xff]+lut[d3>>24&0xff];
}
return self;
})();
which generates uuids like d6414228-b07c-4bd2-9aa3-d1df8b548de6
So my question is - is there a direct way inside couchbase phonegap plugin to achieve this directly?
When writing a document to Couchbase Lite, you can either let the database pick a random ID (it will be unique) or specify one.
You can send a POST request to have the database generate the document ID.
curl -H 'Content-Type: application/json' \
-vX POST 'http://localhost:5984/app' \
-d '{"name": "john"}'
{"id":"-UwALc1GlcAcG60uag1oMf1","rev":"1-10dc5637dc2ccb55e007440cca73a415","ok":true}
Or a PUT request to specify one.
curl -H 'Content-Type: application/json' \
-vX PUT 'http://localhost:5984/app/john' \
-d '{"name": "john"}'
{"id":"john","rev":"1-10dc5637dc2ccb55e007440cca73a415","ok":true}
Note that from then on you must specify the revision number of the current revision to save updates on the document.
curl -H 'Content-Type: application/json' \
-vX PUT 'http://localhost:5984/app/john?rev=1-10dc5637dc2ccb55e007440cca73a415' \
-d '{"name": "johnny"}'