Mister_L
Mister_L

Reputation: 2611

DynamoDB - Get is not working

I'm using a library called dynamoose to access dynamoDB.

https://github.com/automategreen/dynamoose

I have defined a model:

var App = dynamoose.model('AppTest', new dynamoose.Schema ({
   appID: { type: String, hashkey: true },
   email: String,
   isMaster: Boolean,
   password: String
}));

When I do a save operation, everything works fine and data is saved to db.

    var app = new App({ 
       appID: user.appID, 
       email: user.email,     
       isMaster: false, 
       password: user.pwd 
    });

    app.save(function (err) {
       // Data is saved, and no error here
    });

Then when I try to get the data I saved, there's also no error, but user is undefined, although it exists in the db:

    App.get({ email: 'some_existing_email' }, function (err, user) {
       // err = null, user = undefined

    });

Upvotes: 1

Views: 2091

Answers (2)

Brandon Goode
Brandon Goode

Reputation: 21

The issue is around how you access a record in DynamoDB.

‘get’ can only be used on the main table key. In this case appID.

App.get({appID: 'abc'})

For you case, since emails just a normal field, you would have to use ‘scan’.

App.scan('email').eq('[email protected]').exec()

If you defined email as a the range key, you could use ‘get’ with the appID and email

var App = dynamoose.model('AppTest', new dynamoose.Schema ({
   appID: { type: String, hashkey: true },
   email: { type: String, rangeKey: true },
   isMaster: Boolean,
   password: String
}));

App.get({appID: 'abc', email: '[email protected]'})

If email was defined as a global index, you could use ‘query’.

var App = dynamoose.model('AppTest', new dynamoose.Schema ({
   appID: { type: String, hashkey: true },
   email: { type: String, index: { global: true }},
   isMaster: Boolean,
   password: String
}));

App.query('email').eq('[email protected]').exec()

As a note, both query and scan return arrays.

Upvotes: 2

Ryan Fitzgerald
Ryan Fitzgerald

Reputation: 829

In DynamoDB you get items by its primary key. In your example, the primary key is appId. You are attempting to get the data using the email address. You need to change this getting the item using the appId.

If you need to get items by email then you should create a secondary index which uses email address as the hash key. Then you can fetch data by email address by querying the secondary index.

Upvotes: 0

Related Questions