根据 id 从 DynamoDB 中检索项目

Retrieving an item from DynamoDB based on id

我使用 mern 堆栈创建了一个简单的 crud 应用程序。我可以将项目保存到 dynamodb 但无法通过 id 检索项目。该应用程序使用一个简单的前端来处理 save/edit/delete 项。

app.js

app.use('/api/event', event);

event.js

router.get('/:id', (req, res) => {
  const id = req.params.id;

  const params = {
    TableName: EVENTS_TABLE,
    Key: {
      id
    }
  };

  dynamoDb.get(params, (error, result) => {
    if (error) {
      res.status(400).json({ error: 'Error retrieving Event' });
    }
    if (result.Item) {
      res.json(result.Item);
    } else {
      res.status(404).json({ error: `Event with id: ${id} not found` });
    }
  });
});

Table 型号

{
    "TableName": "events",
    "KeySchema": [
      {
        "AttributeName": "id",
        "KeyType": "HASH"
      }
    ],
    "AttributeDefinitions": [
      {
        "AttributeName": "id",
        "AttributeType": "S"
      }
    ],
    "ProvisionedThroughput": {
      "ReadCapacityUnits": 1,
      "WriteCapacityUnits": 1
    }
}

错误:

id is undefined

我的代码: https://github.com/omarhassanhub/mern-event

Angular代码:所有活动链接

<tbody>
  {this.state.events.map(event =>
  <tr>
    <td>
      <Link to={`/show/${event._id}`}>{event.date} </Link> </td> <td>{event.time}</td>
    <td>{event.title}</td>
  </tr>
  )}
</tbody>

尝试通过 id:

获取 event
  componentDidMount() {
    axios.get('/api/event/'+this.props.match.params.id)
      .then(res => {
        this.setState({ event: res.data });
        console.log(this.state.event);
      });
  }

您必须定义请求键的列名。更改您的参数对象,使用列名的键表达式并尝试。

const params = {
    TableName: EVENTS_TABLE,
    Key: {
      'id':id
    }
  };

在这一行,您绑定了一个包含错误数据的列表

<Link to={`/show/${event._id}`}>{event.date} </Link> </td> <td>{event.time}</td>

你的 event 包含 id 字段而不是 _id (你 table 模型说的)

然后,当您尝试在 this.props.match.params.id (axios.get('/api/event/'+this.props.match.params.id)) 获取事件 ID 时,id 将是 undefined

要解决此问题,只需生成包含正确数据的事件列表:

<Link to={`/show/${event.id}`}>{event.date} </Link> </td> <td>{event.time}</td>