Interested in connecting to a Capella cluster using Node.js?
In this quickstart blog post (and I do mean quick!) I will walk you through the short set of steps to connect to a cluster in Capella with the Couchbase Node.js SDK.
Configurar
Requisitos
To complete this tutorial, you must have the following:
- A Couchbase Capella account – free trials are available with a simple sign-up
- Capella Cluster desplegado y configured for access
- npm – Node.js package manager
Install latest long-term support (LTS) release of Node.
Download and install Node’s latest long-term support (LTS) release if you haven’t already.
If you’re installing Node for the first time, we recommend using the Node Version Manager (nvm) for getting started with Node.
- Follow the instructions for installing nvm
- Install the latest Node LTS release
1 |
$ nvm instale --lts |
Create a Node.JS Project
Creating a Node.js project is as easy as making a directory and initializing it with npm. The next two commands will do that for us. Open up a terminal and run the following command:
1 |
$ mkdir nodo-couchbase-proyecto && cd $_ |
The command above will make our directory and change our current working directory. The next command initializes the project directory:
1 |
$ npm init -y |
If a directory does not already have a paquete.json at its root, this means it is not initialized. The command above will accomplish this.
Note: We have used the -y flag to take the initialization defaults. To change any of these defaults, just open the paquete.json and manually make any changes.
1 2 3 4 5 6 7 8 9 10 11 12 |
{ "nombre": "node-couchbase-project", "version": "1.0.0", "descripción": "", "principal": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "autor": "", "licencia": "ISC" } |
Install the Couchbase Node.js SDK
The Couchbase Node.js SDK enables you to interact with a Couchbase Server cluster from the Node.js language. The Couchbase Node.js Client will run on any supported LTS version of Node.js.
To install the latest Couchbase Node.js SDK, run the following command:
1 |
$ npm instale couchbase --guardar |
Utiliza el –save option to have the Couchbase module added as a dependency to the project. This will help automate the installation of packages if you want to distribute your work in the future.
Connecting to Couchbase with built-in Node.js SDK
En installing the Couchbase SDK, the next step is to use the built-in SDK examples to connect to your cluster.
Find cluster connection settings
Go to the cluster’s Connect tab in the Couchbase Capella UI using these steps:
- Go to the Clusters tab in the main navigation
- Find and click on your cluster (docs-cluster13feb1 in the following screenshot). This opens the cluster with its Overview tab selected.
- Click the Connect tab in the left sidebar
In the Connection section, two endpoints are listed: One labeled Público and one labeled Private.
When connecting to the cluster over a wide area network—such as when you’re connecting to the cluster over the Internet from an application on your laptop—you will use the public endpoint.
When connecting to the cluster from within your cloud provider using a peering connection, you will use the private endpoint.
However, you will not need to copy the public endpoint for this post because it is automatically included in the built-in SDK examples we will use.
Open SDK examples
Click SDK Examples. This opens the SDK Examples fly-out menu, showing the options in this screenshot:
Each of the supported Couchbase SDK languages is represented by a tab. Under each tab, a snippet of the example code is provided. The example code is pre-populated with the cluster’s public endpoint and, with a few modifications, can quickly be used for connecting to the cluster.
Copy the example code.
Click on the tab for your desired SDK language, and copy the example code. If you’re following the examples in this guide, click the Node.js tab, and copy the example JavaScript code.
Paste the example code into a text editor and update your connection details.
The SDK example code automatically comes pre-populated with the cluster’s public endpoint and default bucket name.
Actualizar el nombre de usuario y contraseña connection settings to the database credentials you created when usted configured database access earlier.
Changing the bucket (optional)
En bucketName is the name of a bucket on the cluster you will connect to. The example code comes pre-populated with the name of the default bucket: couchbasecloudbucket. This bucket will suffice for this tutorial, but if you choose a create a new bucket for this exercise, you’ll need to specify the new bucket’s name in the example code.
Database credentials must allow access to any new bucket that you add. If you configured the database credential to have read/write permissions on all buckets (as recommended), you can specify any bucket when testing out the connection.
The following is an example of a completed Node.js configuration:
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 |
var couchbase = requiere(couchbase); // Update this to your cluster const punto final = '408f6eee-c52d-4d44-a155-691f9c511931.dataplane.couchbase.com' const nombre de usuario = 'admin' const contraseña = 'P@ssw0rd' const bucketName = 'couchbasecloudbucket' // User Input ends here. // Initialize the Connection var grupo = nuevo couchbase.Grupo('couchbases://' +punto final+'?ssl=no_verify&console_log_level=5', {nombre de usuario: nombre de usuario, contraseña: contraseña}); var cubo = grupo.cubo(bucketName); var colección = cubo.defaultCollection(); función iniciar(){ consola.registro('start'); devolver nuevo Promesa( (resolver, rechace) => { resolver(); }); } async función ejecute(){ // Create a N1QL Primary Index (but ignore if it exists) pruebe { await grupo.queryIndexes().createPrimaryIndex(bucketName, {ignoreExists: verdadero}); } captura (e) { } // Create and store a document pruebe { await colección.upsert('user:king_arthur', { nombre: 'Arthur', correo electrónico: 'kingarthur@couchbase.com', intereses: [Santo Grial, 'African Swallows'] }); } captura (e) { tirar(e); } // Load the Document and print it // Prints Content and Metadata of the stored Document pruebe { deje obtenerResultado = await colección .consiga('user:king_arthur'); consola.registro('Got: '); consola.registro(obtenerResultado); } captura (e) { consola.registro(e); tirar(e); } // Perform a N1QL Query const opciones = { parámetros: ['African Swallows'] }; pruebe { deje queryResult = await grupo.consulta('SELECT name FROM '+bucketName +' WHERE $1 in interests LIMIT 1', opciones); queryResult.filas.paraCada((fila) => { consola.registro('Query row: ', fila) }); } captura (e) { consola.registro(e); tirar(e); } } iniciar().entonces(ejecute).entonces(() => { consola.registro("closing..."); grupo.cerrar();}); |
Once you’ve finished updating the example code with your connection details, save it in your project directory. Be sure to use the appropriate file extension for the SDK language.
If you’re following the examples in this guide, save the file as connection-script.js en el node-couchbase-project directory that you created earlier when you installed the Couchbase Node.js SDK.
Connect to the cluster.
From the project directory, run the connection script using the following command:
1 |
nodo conexión-script.js |
The results you should expect are as follows:
1 2 3 4 5 6 7 8 9 10 |
Tengo: { cas: CbCas { '0': <Tampón 08 00 64 71 50 c3 25 16> }, valor: { nombre: 'Arthur', correo electrónico: 'kingarthur@couchbase.com', interests: [ Santo Grial, 'African Swallows' ] } } Consulta fila: { nombre: 'Arthur' } |
If you received the results above, the connection was successful, and a document was written to the bucket.
Congratulations on completing this quickstart guide! Be sure to try this out on Couchbase Capella to see how easy it can be.
Recursos
Capella
To learn more about Couchbase Capella, our database-as-a-service offering:
- Inscríbete en prueba gratuita de 30 días if you haven’t already
- Conecte su grupo de prueba al Playground or connect a project to test it out for yourself
- Eche un vistazo al Ruta de aprendizaje Capella!
Tutoriales
En Portal para desarrolladores de Couchbase tiene toneladas de tutoriales/guías de inicio rápido y vías de aprendizaje to help you get started, including:
Formación
We have several training options available depending on your need and level:
- Associate Node.js Developer course (free)
- Associate Architect course – language-agnostic
- All training options aquí
Consulte la documentación para obtener más información sobre los SDK de Couchbase.
____________________________________________________________________________
Thank you for reading this post. At this point, you should be able to easily interact with a Couchbase Capella cluster from a Node.js script. If you have any questions or comments, please connect with us on the Couchbase Forums.