user3648673
user3648673

Reputation: 65

A few using DynamoDB with node.js questions

I'm trying to learn node.js and do some stuff with DynamoDB and I have run into a few issues that i havent found any examples of that work. I have a table set up with 2 columns, username and score. Username is the primary key, score is the sort key.

Problem 1: I want to query a specific list of user's scores (WHERE score IN list). My test case is "username":["usr1","usr2,"usr3"]. Below is my code.

'use strict';

const AWS = require('aws-sdk');
const doClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-2'});

exports.handler = (event,context,callback) => {

let params = {
    TableName: 'highscores',
    KeyConditionExpression: "#u = :val",
    ExpressionAttributeNames:{
    "#u": "username"
    },
    ExpressionAttributeValues: {
        ":val":event.username
    }
    //AttributesToGet: [ "username","score" ],
};

doClient.query(params, function(err,data){
    if(err){
        callback(err,null);
    }else{
        callback(null,data);
    }
});
};

Problem 2: I want to update a score on the table. When trying this, it error's out and says "The provided key element does not match the schema". If I put score in the key, it will only replace the record where the username and the score match. Test case is "username": "usr", "score": 998. below is that code.

'use strict';

const AWS = require('aws-sdk');
const doClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-2'});

exports.handler = (event,context,callback) => {
let params = {
    Key: {
        username: event.username,
    },
    UpdateExpression: "set score = :s",
    ExpressionAttributeValues:{
    ":s":event.score
},
    TableName: 'highscores'
};

doClient.update(params, function(err,data){
    if(err){
        callback(err,null);
    }else{
        callback(null,data);
    }
});
};

Any help is appreciated, thanks:)

Upvotes: 1

Views: 86

Answers (1)

shalvah
shalvah

Reputation: 895

For your first problem, I suggest you use batchGet.

let params = {
  RequestItems: {
    TableName: 'highscores',
    Keys: [
      {username: 'usr1'},
      {username: 'usr2'},
      {username: 'usr3'},
    ],
    AttributesToGet: [ "username","score" ],
};

doClient.batchGet(params, function(err,data){
    if(err){
        callback(err,null);
    }else{
        callback(null,data);
    }
});

Your second issue is due to your table schema. The username is apparently your partition key. Your primary key is made up of a partition key and a sort key, so you need to supply both for updates.

Upvotes: 1

Related Questions