How clusters, buckets, and collections work together
masterTo interact with Couchbase, you follow a hierarchical connection pattern:
- Cluster: Create a
Clusterinstance usingconnect()with a connection string (e.g.,couchbase://127.0.0.1) and authentication credentials (username,password). - Bucket: Access a specific bucket via
cluster.bucket('bucket_name'). - Collection: Access a collection within that bucket using
bucket.defaultCollection()or by specifying a named collection.
Operations (like upsert or get) are executed against the Collection instance. Most operations can be called immediately; they will be queued internally until the connection to the cluster is successfully established.
const couchbase = require('couchbase')
async function main() {
// 1. Connect to Cluster
const cluster = await couchbase.connect(
'couchbase://127.0.0.1',
{
username: 'username',
password: 'password',
})
// 2. Access Bucket
const bucket = cluster.bucket('default')
// 3. Access Collection
const coll = bucket.defaultCollection()
// 4. Perform Operations
await coll.upsert('testdoc', { foo: 'bar' })
const res = await coll.get('testdoc')
console.log(res.content)
}
main()