的直接回答你的問題是,你需要使用result.Table.ItemCount而不是result.ItemCount在回調函數。但請注意,此計數並未實時更新,可能並不反映最近對錶格的插入或刪除。如果您想要當前項目數量,則需要掃描該表格並使用Count屬性來獲取掃描項目的數量。這樣的掃描可能會消耗表的所有預配置容量,因此如果這是一項要求,請確保將最近的項目計數需求與可能同時在表上運行的其他操作進行平衡。
以下是返回項目計數的掃描的node.js示例。由於掃描是迭代調用的,直到讀取所有行,我正在使用async模塊在發佈下一個循環之前等待結果。
var async = require('async');
var AWS = require('aws-sdk');
AWS.config.update({accessKeyId: 'AKID',
secretAccessKey: 'secret',
region: 'us-east-1'});
var svc = new AWS.DynamoDB();
var scanComplete = false,
itemCountTotal = 0,
consumedCapacityUnitsTotal = 0;
var scanParams = { TableName : 'usertable',
Count : 'true' };
// scan is called iteratively until all rows have been scanned
// this uses the asyc module to wait for each call to complete
// before issuing the next.
async.until(function() { return scanComplete; },
function (callback) {
svc.scan(scanParams, function (err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
if (typeof (result.LastEvaluatedKey) === 'undefined') {
scanComplete = true;
} else {
// set the start key for the next scan to our last key
scanParams.ExclusiveStartKey = result.LastEvaluatedKey;
}
itemCountTotal += result.Count;
consumedCapacityUnitsTotal += result.ConsumedCapacityUnits;
if (!scanComplete) {
console.log("cumulative itemCount " + itemCountTotal);
console.log("cumulative capacity units " + consumedCapacityUnitsTotal);
}
}
callback(err);
});
},
// this runs when the loop is complete or returns an error
function (err) {
if (err) {
console.log('error in processing scan ');
console.log(err);
} else {
console.log('scan complete')
console.log('Total items: ' + itemCountTotal);
console.log('Total capacity units consumed: ' + consumedCapacityUnitsTotal);
}
}
);