You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS SDK v3 JavaScript PutCommand条件表达式失效问题排查

问题分析与修复

你的代码里有两个关键错误,导致无法阻止覆盖已存在的用户条目:

  • userId赋值错误:原代码中const userId = {newItemObject};是把传入的整个对象包装成了新对象,而非提取newItemObject里的userId属性。这会让后续表达式里的:userIdVal变成嵌套对象,完全不符合预期。正确写法应为:

    const userId = newItemObject.userId;
    
  • 条件表达式逻辑错误:原表达式ConditionExpression: "userId = :userIdVal"的逻辑是仅当已有条目的userId等于指定值时才允许写入,这会直接覆盖同userId的已有条目,和你“阻止覆盖”的需求完全相反。正确做法是使用DynamoDB的attribute_not_exists函数,判断当前主键(userId)对应的条目不存在时才允许写入:

    ConditionExpression: "attribute_not_exists(userId)"
    

    由于userId是主键,只要它不存在,就代表该用户条目未创建过,此时才执行Put操作。


修正后的完整代码

import { PutCommand } from "@aws-sdk/lib-dynamodb";
import { ddbDocClient } from "./ddbDocClient.js";

const putItem = async (newItemObject) => {
    // 提取userId属性
    const userId = newItemObject.userId;
    if(userId){
        console.log({userId});
        const params = {
            TableName: "portal-users",
            Item: newItemObject,
            // 仅当userId不存在时才允许写入
            ConditionExpression: "attribute_not_exists(userId)"
        };
        try {
            const data = await ddbDocClient.send(new PutCommand(params));
            console.log("Success - item added", data);
        } catch (err) {
            // userId已存在时会触发ConditionalCheckFailedException
            console.log("Error: 用户已存在或写入失败", err.stack);
        }
    } else {
        console.log('user id is undefined, please provide for new user id');
    }
};

const newUser = [
    {
        userId: 'user01',
        nameFirst: 'alison',
        nameLast: 'swift'
    }
];

// 确保异步操作全部完成
await Promise.all(newUser.map(x => putItem(x)));

补充说明:原代码用newUser.map(x => putItem(x))不会等待异步操作完成,建议改用Promise.all配合await,确保所有写入操作的状态都能被正确处理。


内容的提问来源于stack exchange,提问作者gfek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 15:52:17