dynobase-icon
Dynobase

DynamoDBDocumentClient in AWS SDK for JavaScript v3

Rafal Wilinski

Written by Rafal Wilinski

Published: November 20th, 2026

Writing DynamoDB code by hand? Dynobase turns supported data operations into application code or scripts, and generates CDK, CloudFormation or Terraform for an existing table. Code generation in Dynobase

DynamoDBDocumentClient is the AWS SDK for JavaScript v3 client for reading and writing DynamoDB items as native JavaScript values. Install @aws-sdk/lib-dynamodb and @aws-sdk/client-dynamodb, wrap a DynamoDBClient with DynamoDBDocumentClient.from(), and pass document commands to client.send(). The client translates fields such as keys, items, and expression values between plain JavaScript and DynamoDB's typed attribute format.

Install and configure the document client

Save this as client.mjs. Set DYNAMODB_LOCAL=1 for the test setup below. For AWS, the base client resolves its Region and Node.js credentials from the environment or shared AWS configuration. Pass connection settings to DynamoDBClient and translation settings as the second argument to DynamoDBDocumentClient.from().

The examples share this module and an Orders table with String keys pk and sk. Create the table using the Local setup below and start with the Put/Get example. For a broader SDK walkthrough, see DynamoDB with Node.js.

Marshalling and unmarshalling options

Marshalling converts JavaScript inputs to DynamoDB attribute values. Unmarshalling converts response attributes back. The AWS package reference lists these options.

OptionDefault on the document clientEffect
marshallOptions.removeUndefinedValuesfalseWith true, omits undefined object properties and removes undefined entries from lists and sets. This can shift list indexes. JavaScript null is stored as DynamoDB NULL.
marshallOptions.convertEmptyValuesfalseWith true, turns empty strings, binary values, and sets into NULL. DynamoDB accepts empty strings and binary values in non-key attributes and rejects empty sets.
marshallOptions.convertClassInstanceToMapfalseWith true, marshals a class instance's enumerable properties as a map. Reads return plain objects.
marshallOptions.convertTopLevelContainertrueEmits the enclosing M or L attribute wrapper for a top-level value passed to the marshaller. Standalone marshall() defaults to false. Keep the document client default.
marshallOptions.allowImpreciseNumbersfalseWith true, accepts JavaScript numbers beyond the safe integer bounds, which may have already lost precision.
unmarshallOptions.wrapNumbersfalseWith true, returns DynamoDB numbers as NumberValue instances. A function receives each numeric value as a string so you can supply your own conversion.
unmarshallOptions.convertWithoutMapWrappertrueSkips the implicit M wrapper used by standalone unmarshall(). Keep the document client default.

An omitted value leaves the attribute absent, while NULL is a stored value. Use the DynamoDB data type rules when deciding how to store empty values. For example, turning an empty key into NULL still gives DynamoDB an invalid key.

Preserve large numbers with NumberValue

Give NumberValue.from() a string to preserve digits that a JavaScript number would round. Use bigint for exact integer writes. With the default read conversion, ordinary values become JavaScript numbers and sufficiently large integer values can come back as bigint. Choose wrapNumbers: true if you need exact decimals on reads too.

Run this snippet after creating the order in the PutCommand example. The shared client enables wrapNumbers so subsequent reads also preserve the decimal. That setting applies to every numeric attribute the client reads.

For arithmetic, pass NumberValue.toString() to a decimal library or use BigInt for an integer string. The wrapper preserves the numeric representation for transport. DynamoDB still enforces its number precision and range.

Document client commands

PutCommand and GetCommand

PutCommand replaces an item with the same primary key unless a condition prevents it. Here, attribute_not_exists(pk) checks the specific item identified by both key fields. GetCommand uses the full primary key and returns an absent Item if the key does not exist. Use ConsistentRead: true when the read must reflect a successful write that preceded it.

UpdateCommand

UpdateCommand can create a missing item. Add an existence check when you intend to update only an existing order. ExpressionAttributeNames aliases attribute names, including reserved words such as status. ExpressionAttributeValues supplies native JavaScript values, and ReturnValues: "ALL_NEW" returns the updated item in Attributes. See the update expression guide for nested fields and other update actions.

QueryCommand and ScanCommand

QueryCommand uses partition-key equality and can narrow the result by sort key. ScanCommand walks a table or index. It applies a filter after reading items, so filtering does not reduce the read capacity consumed by the scan. These calls each fetch one page.

BatchGetCommand and BatchWriteCommand

BatchGetCommand accepts up to 100 keys per call. Responses can arrive in any order and omit missing items. Identify results by their primary keys and retry only UnprocessedKeys. BatchWriteCommand accepts up to 25 puts or deletes per call. Puts overwrite existing items, and the batch has no per-item conditions or atomic commit. Retry only UnprocessedItems with backoff.

The example batches use one table. If a response still contains pending work after the last retry, the thrown error carries it in cause. For reads it also carries the items already collected.

TransactWriteCommand

TransactWriteCommand makes changes to distinct items atomically. This order can ship only while it is paid, and the shipment marker must be new. Place the status check on the update itself because a transaction can target a particular item only once. The transactions guide covers when to use transactional reads and writes.

ExecuteStatementCommand with PartiQL

Import ExecuteStatementCommand from @aws-sdk/lib-dynamodb to pass JavaScript values in Parameters. Bind values with ? and include partition-key equality in the SELECT statement to avoid a full table scan. Follow NextToken when the response supplies it. See the PartiQL guide for other statements.

DeleteCommand

DeleteCommand deletes one item by primary key. ReturnValues: "ALL_OLD" returns its pre-delete attributes if it existed. This example deletes the second order created by the batch write.

Paginate with paginateQuery and paginateScan

Both SDK paginators return async iterators over pages. They pass each LastEvaluatedKey as the next request's ExclusiveStartKey. A filtered page can contain zero matches and still have a continuation key. pageSize limits evaluated items per request, so it does not guarantee that many matches. See DynamoDB pagination for manual cursors.

Sets, binary, dates, and conversion boundaries

  • Sets. Use new Set(["online", "priority"]) for a String Set. Arrays become lists. Keep set members of the same DynamoDB scalar type and treat the returned set as unordered.
  • Binary. Pass Uint8Array or Node.js Buffer for binary data, or a set of byte arrays for a Binary Set. Decode a base64 string to bytes before passing it in if the attribute should have DynamoDB type B.
  • Dates. Store date.toISOString() for a readable timestamp or a number for epoch time. Reconstruct the Date in your application. DynamoDB has no Date type.
  • Typed maps and expressions. Supply { pk: "CUSTOMER#42" } as a document key. The low-level client expects { pk: { S: "CUSTOMER#42" } }. Passing the second form to a document command marshals the nested object as a map. Expression text and name aliases are passed through, so write the expressions and supply the matching values yourself.

See the AWS SDK type mappings and DynamoDB data types for the supported representations.

Migrate from AWS.DynamoDB.DocumentClient v2

Replace await v2.get(params).promise() with await docClient.send(new GetCommand(params)). The v2 methods returned request objects. The v3 send call already returns a promise.

v2 DocumentClient methodv3 command passed to send()
get(params)GetCommand
put(params)PutCommand
update(params)UpdateCommand
delete(params)DeleteCommand
query(params)QueryCommand
scan(params)ScanCommand
batchGet(params)BatchGetCommand
batchWrite(params)BatchWriteCommand
transactGet(params)TransactGetCommand
transactWrite(params)TransactWriteCommand

Use native Set in place of v2's createSet(). Set marshallOptions.removeUndefinedValues: true to preserve v2's omission of undefined values. Recheck any code that reads numeric wrappers or serializes sets to JSON. AWS's DocumentClient migration notes explain the undefined-value change.

TypeScript typing tips

Import command input and output types from @aws-sdk/lib-dynamodb. The SDK's GetCommand types describe supported attribute values and leave Item optional. Validate the fields your application needs before treating a stored item as an application type. This matters when older items or projections may be missing fields.

If you enable wrapNumbers, model numeric fields as NumberValue or validate the output of your custom wrapper. A type assertion cannot change the SDK's runtime conversion.

Common errors

Constructor error reference for SDK v2

  • DocumentClient is not a constructor. Import DynamoDBDocumentClient from @aws-sdk/lib-dynamodb and call .from(baseClient). The new AWS.DynamoDB.DocumentClient() spelling belongs to SDK v2.
  • The provided key element does not match the schema. Check the key names and types and include both components of a composite primary key. Use native values with document commands.
  • ConditionalCheckFailedException. The write's condition evaluated to false. A second run of the conditional put above gives this error for the existing order. Handle it as a conflict and check the current item state before deciding whether to retry. See condition failure troubleshooting and the AWS PutItem error reference.
  • Marshalling fails on undefined or a large number. Omit undefined fields or opt into removeUndefinedValues. Use an exact string with NumberValue.from() if a numeric input exceeds JavaScript's safe precision. Use REMOVE in an update expression to delete a stored attribute explicitly. See the SDK conversion options and DynamoDB update expressions.

Test against DynamoDB Local

Start DynamoDB Local in Docker and publish its port on the loopback interface. The in-memory database is reset when the container stops.

Save this as create-table.mjs. CreateTableCommand belongs to the base client because it manages table definitions.

Save each JavaScript example in its own .mjs file alongside client.mjs and run it with Node.js in the same shell. Begin with Put/Get, then run the precision example. Verify that Update returns PAID, the transaction changes it to SHIPPED, and the delete returns the second order. For a multi-page query, run the paginator after the batch write and before deleting the second order. Local usage notes explain that the emulator ignores provisioned throughput. Test pending-work handling with a stub response that contains UnprocessedItems or UnprocessedKeys.

Stop the disposable local database with docker stop dynamodb-local.

Frequently Asked Questions

Which package exports DynamoDBDocumentClient?

Import DynamoDBDocumentClient and document commands from @aws-sdk/lib-dynamodb. Import the base DynamoDBClient from @aws-sdk/client-dynamodb.

Does DynamoDBDocumentClient skip undefined values?

Set removeUndefinedValues to true in marshallOptions to omit undefined values from objects, lists, and sets. Null is stored as a DynamoDB NULL attribute.

How do I read a DynamoDB number without losing precision?

Set wrapNumbers to true in unmarshallOptions and call toString on the resulting NumberValue. For writes, pass the original numeric string to NumberValue.from before any JavaScript number conversion.

How do I fetch every page with DynamoDBDocumentClient?

Use paginateQuery or paginateScan from @aws-sdk/lib-dynamodb with a for await loop. A filtered page can be empty while there are more pages to evaluate.

Can DynamoDBDocumentClient connect to DynamoDB Local?

Yes. Configure the base DynamoDBClient with the local endpoint, a Region, and dummy credentials, then wrap it with DynamoDBDocumentClient.from.

Dynobase is a Professional GUI Client for DynamoDB

Start your 7-day free trial today

Product Features

Download
/
Changelog
/
Pricing
/
Member Portal
/
Privacy
/
EULA
/
Twitter
© 2026 Dynobase