Update
Jump to the Code block for a combined complete example.
Create a document record
The following example demonstrates reading a document record with a JSON helper library. In Aerospike, JSON documents are handled as a Collection Data Type (CDT). A JSON object is equivalent to a map, and a JSON array is equivalent to a list.
In this example, we create the following JSON document:
employees = [{"id": "09", "name": "Nitin", "department": "Finance"}, {"id": "10", "name": "Jonathan", "department": "Human Resources"}, {"id": "11", "name": "Caitlin", "department": "Engineering"}]
The JSON document is added to a bin called employees
which is of data
type list. There are some advantages
to holding an entire document in a single bin, rather than spreading out the document’s
fields over multiple bins. There is less metadata overhead when namespaces
contain fewer, larger bins.
Setup
Import the necessary helpers, create a client connection, and create a key.
import { readFile } from "node:fs/promises";
const Aerospike = await import("aerospike");const maps = Aerospike.maps;
// Set hosts to your server's address and portconst config = { hosts: "YOUR_HOST_ADDRESS:YOUR_PORT" };
// Create a keyconst key = new Aerospike.Key("test", "demo", 5001);
// Establishes a connection to the serverconst client = await Aerospike.connect(config);
Update
Update the newly created document.
// Update 'department' field from 'Engineering' to 'Support' in 3rd employee recordconst ops = [ maps .putItems("employees", { department: "Support" }) .withContext((ctx) => ctx.addListIndex(2)),];
Code block
Expand this section for a single code block to update a document record.
import { readFile } from "node:fs/promises";
const Aerospike = await import("aerospike");const maps = Aerospike.maps;
// Set hosts to your server's address and portconst config = { hosts: "YOUR_HOST_ADDRESS:YOUR_PORT" };
// Create a keyconst key = new Aerospike.Key("test", "demo", 5001);
// Establishes a connection to the serverconst client = await Aerospike.connect(config);
// Update 'department' field from 'Engineering' to 'Support' in 3rd employee recordconst ops = [ maps .putItems("employees", { department: "Support" }) .withContext((ctx) => ctx.addListIndex(2)),];
const result = await client.operate(key, ops);console.info("Name of 3rd employee: ", result.bins.employees);
await client.close();