ryanfitz/vogels

Create if not exists

Opened this issue · 3 comments

Hi,

I have a simple table:

const Query = vogels.define('Query', {
    hashKey: 'queryId',

    schema: {
        queryId: vogels.types.uuid(),
        name: Joi.string().required()
    },

    tableName: 'query'
});

How to avoid duplicated queries that contain the same 'name'?

I've tried the following code:

function saveQuery(query, cb) {
    var params = {};
    params.ConditionExpression = '#n <> :x';
    params.ExpressionAttributeNames = { '#n': 'name' };
    params.ExpressionAttributeValues = { ':x': query.name };


    queryModel.Query.create(query, params, function(err, res) {
        if (err) {
            console.log(err);
            cb(err);
        } else {
            cb(null, res);
        }
    });
}

But, duplicated queries have been created.
Is there a way to do it using 'create'?

Thanks

DynamoDB is not an SQL server. Please read some articles about the best approaches with DynamoDB.

Option 1: Set the name as HashKey
Option 2: Create Global Primary Key with hash name - the name of the query.
Option 3: Use the scan method ->

Query.scan().where("name").eq(yourQueryName).loadAll().exec()

Using the scan method will be vary ineffective on large tables. It will consume more read capacity.

Thanks,

I'll try the global primary key approach, 'name' was just an example, a have more fields to guarantee the uniqueness.

One more question, about attribute -> 'params' in:

Query.create(query, params, ...

What is it used for? The docs only say...use expressions api to do conditional writes That is why I tried to use 'params' to avoid duplicated rows.

Oh, just saw the pointed out example in the documentation with conditional create.
It could be a regression.

Just find out that there are no tests for this situation.