简体   繁体   中英

How to get all DynamoDB attributes without typing all of them

I'm currently trying to return all the attributes of an entry based off the primary key in Lambda, but I don't want to type out every single attribute to get. Is there an optimized way to do this instead of typing out every single one?

Here is my lambda function:

exports.handler = async function(event, ctx, callback) {
  var data;
  var params = {
    Key: {
      key: event.key
    },
    TableName : 'app',
    AttributesToGet: [
      'email', 
      'lastName',
      'firstName',
      '...nextAttribute',
      '...nextAttribute'
    ],
  };

  try {
    data = await dynamoDb.get(params).promise()
    console.log(data);
  } 
  catch (err) {
    console.log(err);
  }
  return data.Item;
}

So in this example, instead of return ...nextAttribute is there a way to return all the attributes?

You do not have to specify AttributsToGet . If you omit it, you will get all attributes by default, eg

exports.handler = async function(event, ctx, callback) {
  const params = {
    Key: {
      key: event.key
    },
    TableName : 'app',
  };

  try {
    const data = await dynamoDb.get(params).promise();
    console.log(data);
    return data.Item;
  } 
  catch (err) {
    console.log(err);
    return undefined;
  }
}

See details in the AWS JavaScript API, specifically the getItem() function of DynamoDB.


Alternatively, you may find the DynamoDB DocumentClient interesting. Copied from the get() documentation:

var params = {
  TableName : 'Table',
  Key: {
    HashKey: 'hashkey'
  }
};

var documentClient = new AWS.DynamoDB.DocumentClient();

documentClient.get(params, function(err, data) {
  if (err) console.log(err);
  else console.log(data);
});

Side note, AttributesToGet is a legacy parameter according to the documentation. Consider using ProjectionExpression instead if you change your mind and would like to be explicit about which attributes to fetch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM