Couchbase – Big OFFSETs can be a big problem
December 13, 2018Using Postman Environment Variables to Help Make Ease of API Development
February 13, 2019There are many things we do to speed up the process of onboarding a developer. Recently, I have been working on a project where there are loads of View Queries that need to be set up in Couchbase before you’re able to start development work. Thankfully, the Couchbase SDK has a method available in the bucket manager called “insertDesignDocument”.
The insertDesignDocument method is super handy for getting those View Queries set up quickly. The method accepts name, value, and callback. The name is your Design Document Name and value is the ddoc that you will be adding. Below I have shown an example of the ddoc format.
{
views: {
exampleViewName: {
map: '\nfunction (doc, meta) {\n emit(meta.id, null);\n }'
}
}
}
Once I had all of my ddocs, I put them in an array in a .js file. I then required that file and looped over the array, making a call to Couchbase in each iteration to insert the design documents. If it failed, I used the upsertDesignDocument method to try to update. I could have handled the error differently, but in most cases it would error because the view already existed, but if I do an upsert it will update to ensure the view is up to date. Below is a snippet of the process I used.
var Couchbase = require("couchbase");
var docIDs = ["user::user1@compknowhow.com","user::user2@compknowhow.com","user::user3@compknowhow.com"];
var cluster = new Couchbase.Cluster("couchbase://localhost:8091:8091");
cluster.authenticate("Administrator", "admin");
var bucket = cluster.openBucket("default", "");
function getDocs(docIDs, callback) { //callback: (error, data)
bucket.getMulti(docIDs, (getError, docs) => {
if(getError) {
return callback(getError, null);
} else {
return docs;
}
});
}
If you have multiple views to set up, this is something that should not be overlooked. It is well worth the time setting up a service to import all of your views automatically. It will save both yourself and others the pain of manually adding views in Couchbase!