Creating a view on the fly from code using Node.JS

The Code :

// load the Couchbase driver and connect to the cluster
 var couchbase = require('couchbase');
 var cluster = new couchbase.Cluster('localhost:8091');
//it is important to make this async call as otherwise you will try create the //view before the connection is established resulting in a failure
 var bsbucket = cluster.openBucket('beer-sample',function(err){
 if(err){
 console.log('error:',err);
 }
 else{
 console.log('connected');
 }
 });
//Am I connected, if so create the view 
 bsbucket.on('connect', function(err) {
 if(err) {
 console.error("Failed to connect to cluster: " + err);
 process.exit(1);
 }
 else
 {
 console.log('Couchbase Connected');
var bmanager = bsbucket.manager('Administrator', 'password');
// Update the beer view, to index beers 'by_name'.
 bmanager.insertDesignDocument( 'beer', {
 views: {
 'beer_by_name' : {
 map: function (doc, meta) {
 if (doc.type && doc.type == "beer") {
 emit(doc.name, null);
 }
 }
 }
 }
 }, function(err){
//Tell me the error and exit 
 if(err) {
 console.log('ERROR', err);
 process.exit(0);
 }else{
//All good, exit 
 console.log('Done!');
 process.exit(0);
 }
 }
 );
 }
});

Now the big question is why would you want to create views on the fly like this. Remember if you are creating views in normal daily running of code and you have large datasets it will take a long time to process the view. This id because the index needs to be built and this takes time, the more data the more time it takes. This would not lead to a good experience for your end users.

Where I see this kind of thing being useful is in application initialisation.
The first time your application runs it can create all the views in needs, as these should be empty or hold minimal data they should process fast.

  • Ask Question