Insert a document (TypeScript)

Inserts a single document into a collection.

Documents are stored in collections. They represent a single row or record of data in Hyper-Converged Database (HCD) databases. For more information, see About collections with the Data API (TypeScript).

If the collection is vector-enabled, pregenerated vector embeddings can be included by using the reserved $vector field. You can later use the $vector field to perform a vector search.

Ready to write code? See the examples for this method to get started. If you are new to the Data API, check out the quickstart.

Result

Inserts the specified document and returns a promise that resolves to a CollectionInsertOneResult<Schema> object that includes the ID of the inserted document.

The ID value depends on the ID type. For more information, see Document IDs (TypeScript).

Example response:

{ insertedId: '92b3c4f4-db44-4440-b4c4-f4db54e440b8' }

Parameters

Use the insertOne method, which belongs to the Collection class.

Method signature
async insertOne(
  document: MaybeId<Schema>,
  options?: {
    timeout?: number | TimeoutDescriptor,
  },
): CollectionInsertOneResult<Schema>
Name Type Summary

document

MaybeId<Schema>

An object describing the document to insert.

A document can contain user-defined and reserved fields.

User-defined field names can be any non-empty sequence of Unicode characters, with the following exceptions:

  • Field names cannot start with $.

  • Field names cannot be exactly *.

  • If a field name includes & or ., you must escape those characters when you use the field in a filter, sort, projection, or update. For more information, see Work with . and & in field names (TypeScript).

Reserved fields are tied to specific functionality. Include the following reserved fields in your documents, if applicable:

  • _id: An optional unique identifier for the document. If _id is omitted, it is created automatically based on the collection’s ID type. For more information, see Document IDs (TypeScript).

  • $vector: An optional array of numbers representing a vector embedding for vector search. The $vector field is only supported for vector-enabled collections.

For examples, see Examples.

options

CollectionInsertOneOptions

Optional. The options for this operation. See Properties of options for more details.

Properties of options
Name Type Summary

timeout

number | TimeoutDescriptor

Optional.

The timeout(s) to apply to this method. You can specify requestTimeoutMs and generalMethodTimeoutMs. Since this method issues a single HTTP request, these timeouts are equivalent. If you specify both, the minimum of the two will be used.

For more information about the TimeoutDescriptor, see TypeScript client internals: TimeoutDescriptor. If you specify a number instead of a TimeoutDescriptor object, that number will be applied to both requestTimeoutMs and generalMethodTimeoutMs.

Examples

The following examples demonstrate how to insert a document into a collection.

Insert a document

import {
  DataAPIClient,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");

// Insert a document into the collection
(async function () {
  const result = await collection.insertOne({
    title: "Hidden Shadows of the Past",
    genres: ["Biography", "Graphic Novel", "Dystopian", "Drama"],
    metadata: {
      isbn: "978-1-905585-40-3",
      language: "French",
      edition: "Anniversary Edition",
    },
    number_of_pages: 245,
  });
})();

Insert a document with vector embeddings

Use the reserved $vector field to insert a document with pregenerated vector embeddings.

You can later use this field to perform a vector search.

All embeddings in the collection should use the same provider, model, and dimensions. Mismatched embeddings can cause inaccurate vector searches.

The $vector field is only supported for vector-enabled collections. For more information, see Create a collection that can store vector embeddings and $vector in collections (TypeScript).

import {
  DataAPIClient,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");

// Insert a document into the collection
(async function () {
  const result = await collection.insertOne({
    name: "Jane Doe",
    $vector: [0.08, -0.62, 0.39],
  });
})();

Insert a document and specify the ID

The TypeScript client provides the UUID and ObjectId classes to use and generate identifiers. These are not the same as those exported from the uuid or bson libraries.

To generate new identifiers, you can use UUID.v1(), UUID.v4(), UUID.v6(), UUID.v7(), or new ObjectId(). UUIDs can also be constructed from a string representation of the IDs. You can also use the uuid and oid shorthand methods. You can also directly specify a value.

All UUID methods return an instance of the same class, which exposes a version property.

Example using new UUID.v7():

import {
  DataAPIClient,
  UUID,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");

// Insert a document into the collection
(async function () {
  const result = await collection.insertOne({
    _id: UUID.v7(),
    name: "Jane Doe",
  });
})();

Example using new ObjectId() with input:

import {
  DataAPIClient,
  ObjectId,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");

// Insert a document into the collection
(async function () {
  const result = await collection.insertOne({
    _id: new ObjectId("6672e1cbd7fabb4e5493916f"),
    name: "Jane Doe",
  });
})();

Example specifying the ID without UUID or ObjectId:

import {
  DataAPIClient,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");

// Insert a document into the collection
(async function () {
  const result = await collection.insertOne({
    _id: 1,
    name: "Jane Doe",
  });
})();

Insert a document with a binary field

You can insert binary data as a Base64-encoded string with $binary.

You can also also use the CollectionCodecs class to write a custom code. CollectionCodecs is currently in beta.

The DataAPIBlob class is not supported by default for collections.

import {
  DataAPIClient,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");

// Insert a document with a binary field
(async function () {
  const result = await collection.insertOne({
    exampleBinary: { $binary: "PfvnbT7peNU/Sfvn" },
  });
})();

Insert a document with nested fields

Although you can use dot notation in a filter to find a document, you cannot use dot notation to insert a document. To specify nested fields in the inserted document, you must build a map, list, or set.

import {
  DataAPIClient,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

// Get an existing collection
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
  token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
  keyspace: "KEYSPACE_NAME",
});
const collection = database.collection("COLLECTION_NAME");

// Insert a document into the collection
(async function () {
  const result = await collection.insertOne({
    title: "Hidden Shadows of the Past",
    genres: ["Biography", "Graphic Novel", "Dystopian", "Drama"],
    metadata: {
      isbn: "978-1-905585-40-3",
      language: "French",
      edition: "Anniversary Edition",
    },
  });
})();

Client reference

For more information, see the client reference.

Was this helpful?

Give Feedback

How can we improve the documentation?

© Copyright IBM Corporation 2026 | Privacy policy | Terms of use Manage Privacy Choices

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: Contact IBM