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

通过Lambda用PK和SK查询DynamoDB返回undefined,是哪里拼写错误?

问题原因

你混淆了 DynamoDB DocumentClient 两种查询接口的返回值结构:

  • docClient.query() 用于范围查询,返回结果的顶层属性是 Items(复数,数组格式),存储所有匹配条件的记录
  • 只有查询单条记录的 docClient.get() 接口,返回结果的顶层属性才是你代码里解构的 Item(单数,对象格式)

你当前代码用 query 执行查询,却试图解构不存在的 Item 属性,自然得到 undefined,后续访问 Item.PK 就触发了日志里的类型错误。

修复方案

有两种可选修复方式:

方案1:保留query调用,调整返回值读取逻辑

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();

async function getUserById(userId) {
    console.log('USERID:',userId);
    const params = {
        TableName:"Bol",
        KeyConditionExpression: 'PK = :hashKey and SK = :sortKey',
        ExpressionAttributeValues: {
            ':hashKey': userId,
            ':sortKey': 'USER'
        }
    };
    try {
        // 解构复数的Items数组
        const { Items } = await docClient.query(params).promise();
        const Item = Items[0]
        // 增加空判断,避免无匹配数据时报错
        if (!Item) {
            console.log('未查询到匹配用户')
            return null
        }
        console.log('BOL Data:',Item);
        return { id: Item.PK, name: Item.Data.displayName };
    } catch(err) {
        console.log("BOL Error: ", err);
    }
 }
 
 module.exports = getUserById;

方案2:更换为更适配单条主键查询的get接口

因为你已经传入了完整的分区键+排序键,只需要查询单条记录,用get接口性能更高、写法更简洁:

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();

async function getUserById(userId) {
    console.log('USERID:',userId);
    const params = {
        TableName:"Bol",
        Key: {
            PK: userId,
            SK: 'USER'
        }
    };
    try {
        const { Item } = await docClient.get(params).promise();
        if (!Item) {
            console.log('未查询到匹配用户')
            return null
        }
        console.log('BOL Data:',Item);
        return { id: Item.PK, name: Item.Data.displayName };
    } catch(err) {
        console.log("BOL Error: ", err);
    }
 }
 
 module.exports = getUserById;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:36:02