猿问

根据 id 从 DynamoDB 中检索项目

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


应用程序.js


app.use('/api/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` });

    }

  });

});

表模型


{

    "TableName": "events",

    "KeySchema": [

      {

        "AttributeName": "id",

        "KeyType": "HASH"

      }

    ],

    "AttributeDefinitions": [

      {

        "AttributeName": "id",

        "AttributeType": "S"

      }

    ],

    "ProvisionedThroughput": {

      "ReadCapacityUnits": 1,

      "WriteCapacityUnits": 1

    }

}

错误:


id 未定义


我的代码: 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>

尝试event通过 id 获取:


  componentDidMount() {

    axios.get('/api/event/'+this.props.match.params.id)

      .then(res => {

        this.setState({ event: res.data });

        console.log(this.state.event);

      });

  }


互换的青春
浏览 333回答 2
2回答

呼唤远方

在这一行,您绑定了一个包含错误数据的列表<Link&nbsp;to={`/show/${event._id}`}>{event.date}&nbsp;</Link>&nbsp;</td>&nbsp;<td>{event.time}</td>你的event包含id字段而不是_id(你的表模型说)然后,当您尝试在this.props.match.params.id&nbsp;(&nbsp;axios.get('/api/event/'+this.props.match.params.id)) 处获取事件 ID 时,id将是undefined.要解决此问题,只需生成具有正确数据的事件列表:<Link&nbsp;to={`/show/${event.id}`}>{event.date}&nbsp;</Link>&nbsp;</td>&nbsp;<td>{event.time}</td>

慕桂英546537

您必须定义请求键的列名。更改您的参数对象,使用列名的键表达式并尝试。const params = {&nbsp; &nbsp; TableName: EVENTS_TABLE,&nbsp; &nbsp; Key: {&nbsp; &nbsp; &nbsp; 'id':id&nbsp; &nbsp; }&nbsp; };
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答