简介
DynamoDB 是 AWS 提供的一个全托管的 NoSQL 数据库服务,它以高性能和高可扩展性著称。dynamodb-simple 是一个 npm 包,使用它可以方便地在 Node.js 环境下使用 DynamoDB。
本文将介绍如何使用 npm 包 dynamodb-simple 来操作 DynamoDB,并提供详细的示例代码。
安装
在命令行中,使用以下命令安装 dynamodb-simple:
npm install dynamodb-simple
连接 DynamoDB
在使用 dynamodb-simple 之前,必须先连接 DynamoDB。连接后,可以使用 dynamodb-simple 提供的函数来操作 DynamoDB。
以下是连接 DynamoDB 的示例代码:
var DynamoDB = require('dynamodb-simple'); var db = new DynamoDB({ accessKeyId: '[accessKeyId]', secretAccessKey: '[secretAccessKey]', region: '[region]' });
其中,accessKeyId
和 secretAccessKey
是 AWS IAM 凭证,region
是 DynamoDB 所在的区域。在实际使用时,请替换成自己的凭证和区域。
创建表
DynamoDB 是一个基于键值对的数据存储服务,要使用它存储数据,需要先创建表,并定义表的主键。
以下是创建表的示例代码:
-- -------------------- ---- ------- --------------------------- - ----- ----------- ---------- ------ ------------ --------- -- ------------- ------ - -- ----- - ------------------- - ---- - ------------------- - ---展开代码
其中,tableName
是表名,hash
是表的主键,它是一个数组,第一个元素是主键名,第二个元素是主键的类型。如果表的主键有 rangeKey,可以在第二个参数中加入 range 属性。
插入数据
使用 db.putItem(tableName, item, callback)
来往表 tableName
中插入 item
。以下是插入数据的示例代码:
db.putItem('tableName', { hashKey: 'hashKeyVal', rangeKey: 1, other: 'data' }, function(err, res) { if (err) { console.error(err); } else { console.log(res); } });
查询数据
使用 query
或 scan
来查询数据。
query
使用 db.query(tableName, options, callback)
来查询数据。以下是查询数据的示例代码:
-- -------------------- ---- ------- --------------------- - ----- - --- ---- ---- ------------ -- ------ - --- ---- ---- - - -- ------------- ---- - -- ----- - ------------------- - ---- - ----------------- - ---展开代码
其中,options
是一个对象,包含了查询参数。在上面的示例代码中,查询参数包含了两个条件:hashKey 等于 'hashKeyVal',rangeKey 大于 1。
scan
使用 db.scan(tableName, options, callback)
来扫描数据。以下是扫描数据的示例代码:
-- -------------------- ---- ------- -------------------- - ------- - ----- -------- --------- ---- ------ ------ - -- ------------- ---- - -- ----- - ------------------- - ---- - ----------------- - ---展开代码
其中,options
是一个对象,包含了扫描参数。在上面的示例代码中,扫描参数包含了过滤条件,只返回 other 等于 'data' 的数据。
更新数据
使用 db.updateItem(tableName, key, update, callback)
来更新数据。以下是更新数据的示例代码:
db.updateItem('tableName', { hashKey: 'hashKeyVal', rangeKey: 1 }, { other: 'newData' }, function(err, res) { if (err) { console.error(err); } else { console.log(res); } })
删除数据
使用 db.deleteItem(tableName, key, callback)
来删除数据。以下是删除数据的示例代码:
db.deleteItem('tableName', { hashKey: 'hashKeyVal', rangeKey: 1 }, function(err, res) { if (err) { console.error(err); } else { console.log(res); } });
结束连接
在程序退出之前,请使用 db.end(cb)
来关闭连接。以下是关闭连接的示例代码:
db.end(function() { console.log('connection closed'); });
总结
在本文中,我们介绍了如何使用 npm 包 dynamodb-simple 来连接 DynamoDB,并且提供了插入、查询、更新和删除数据的示例代码。希望本文能够帮助您更好地使用 DynamoDB。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/600562d581e8991b448e025d