Skip to content

Instantly share code, notes, and snippets.

@brandongoode
Created August 11, 2016 13:16
Show Gist options
  • Save brandongoode/ab22d81e8e13387048217d08804d15e0 to your computer and use it in GitHub Desktop.
Save brandongoode/ab22d81e8e13387048217d08804d15e0 to your computer and use it in GitHub Desktop.
Dynamoose range and hash key example
var commentSchema = new Schema({
postId: {
type: String,
hashKey: true
},
id: {
type: String,
rangeKey: true,
default: shortId.generate
},
timestamp: Date
commenterId: {
type: String,
required: true,
index: {
global: true,
rangeKey: 'timestamp',
}
},
text: String,
likes: Number
});
var Comment = dynamoose.model('Comment', commentSchema);
// Get a single comment using the table key
Comment.get(
{postId: postId, id: commentId}, // this is the table key (hash and range)
function (err, comment) {...}
);
// Get all comments for a post
Comment
.query('postId').eq(postId) // only table hash key is used
.exec(function (err, allCommentsForPost) {...});
// Get all comments for a commenter
Comment
.query('commenterId').eq(commenterId) // hash key for index
.exec(function (err, allCommentsForCommenter) {...});
// Get all comments for a commenter within last 10 days (uses range key)
Comment
.query('commenterId').eq(commenterId)
.where('timestamp').ge(Date.now() - 8.64e+8) // use .where for range keys
.exec(function (err, commentsForCommenterWithin10Days) {...});
// Get all comments for a commenter with likes (uses filters - slower than range)
Comment
.query('commenterId').eq(commenterId)
.filter('likes').gt(0) // use filter when not a range key
.exec(function (err, commentsForCommenterWithLikes) {...});
@rawsh
Copy link

rawsh commented Apr 28, 2018

What is shortId.generate here? UUID?

@krlozadan
Copy link

I'm trying to do something like:

Comment
  .query('commenterId').eq(commenterId)
  .where('timestamp').ge(Date.now() - 8.64e+8)
  .filter('likes').ge(2)
  .exec(function (err, commentsForCommenterWithin10Days) {...});

And it gives me back: Cannot read property 'type' of undefined

Is there something I'm doing wrong?

@brandongoode
Copy link
Author

@krlozadan - Just quickly looking, I don't see anything wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment