DynamoDB PutItem in Node.js (AWS SDK v3)

PutItem writes a whole item, creating it or replacing any existing item with the same primary key. In AWS SDK v3 you send a PutItemCommand whose Item holds every attribute in low-level format ({ S: ... }, { N: ... }).

Code

import {DynamoDBClient, PutItemCommand} from '@aws-sdk/client-dynamodb';

const client = new DynamoDBClient({region: 'us-east-1'});

async function addSong() {
  const command = new PutItemCommand({
    TableName: 'Music',
    Item: {
      Artist: {S: 'Arturo Sandoval'},
      SongTitle: {S: 'Cubano Chant'},
      AlbumTitle: {S: 'Danzon'},
      Year: {N: '1994'},
      Awards: {N: '0'}
    },
    // Only write if no item with this key already exists
    ConditionExpression: 'attribute_not_exists(Artist) AND attribute_not_exists(SongTitle)'
  });

  try {
    await client.send(command);
    console.log('Song written');
  } catch (err) {
    if (err.name === 'ConditionalCheckFailedException') {
      console.log('A song with that key already exists — not overwritten');
    } else {
      throw err;
    }
  }
}

addSong();

Explanation

  • Item — must contain the table's full primary key, plus any other attributes. Numbers are strings under the N type ({ N: "1994" }).
  • Put replaces — without a condition, PutItem silently overwrites an existing item with the same key. Use UpdateItem to change a few attributes without clobbering the rest.
  • ConditionExpressionattribute_not_exists(<key>) makes the write a create-only insert; the write fails with ConditionalCheckFailedException if the item already exists. This is DynamoDB's optimistic-locking primitive.
  • To get the overwritten item back, add ReturnValues: "ALL_OLD".
  • Prefer the DynamoDBDocumentClient (@aws-sdk/lib-dynamodb) if you'd rather pass plain JS objects than typed attribute values.

Do it visually

Writing a conditional put by hand? The DynamoDB Expression Builder assembles the ConditionExpression and copies the code.

To add and edit items in a GUI — a form per attribute, type pickers, and copy-as-code — download DynoTable.

不必透過主控台就能操作 DynamoDB

DynoTable 是一款快速的 DynamoDB 桌面用戶端 — 瀏覽表格、執行 SQL 風格的查詢,並在本機編輯項目。