1

I am using dynamoDB with a node js express project, in which username and email address both shlould be unique, tried like below but didn't work:

const params = {
      TableName: "users",
      Item: {
        id: uuidv4(),
        username,
        email,
        password,
      },
      ConditionExpression: "attribute_not_exists(email) AND attribute_not_exists(SK)",
    };

    db.put(params, (err, data) => {
      if (err) {
        return res
          .status(409)
          .send({ success: false, message: `User already exist ${err}` });
      } else {
        return res.status(200).send({
          success: true,
          message: "User added succcessfully",
          data: data,
        });
      }
    });

any help please?

webcoder
  • 1,331
  • 1
  • 9
  • 27

1 Answers1

2

From comments, username is partition key and no sort key. Since there will always be just 1 record with given username, we just need to check if username exists or not.

const AWS = require("aws-sdk");
AWS.config.update({ region: "us-east-1" });
let docClient = new AWS.DynamoDB.DocumentClient();

const email = "test3@yahoo.com";
const username = "test1";
const name = "myfirst mylast";
docClient.put(
  {
    TableName: "test",
    Item: {
      email,
      username,
      name,
    },
    ConditionExpression: "attribute_not_exists(username)",
  },
  (err, res) => {
    if (err && err.code === "ConditionalCheckFailedException")
      console.log("User Already exists");
    else if (err) console.log("Insert Failed with some other reason", err);
    else console.log("Sucessfully inserted");
  }
);

With username as partition key and email as sort key, which means, only combination of two is unique.

const AWS = require("aws-sdk");
AWS.config.update({ region: "us-east-1" });
let docClient = new AWS.DynamoDB.DocumentClient();

const email = "test2@yahoo.com";
const username = "test1";
const name = "myfirst mylast";
docClient.put(
  {
    TableName: "test",
    Item: {
      email,
      username,
      name,
    },
    ConditionExpression:
      "attribute_not_exists(username) AND attribute_not_exists(email)",
  },
  (err, res) => {
    if (err && err.code === "ConditionalCheckFailedException")
      console.log("User Already exists");
    else if (err) console.log("Insert Failed with some other reason", err);
    else console.log("Sucessfully inserted");
  }
);
Balu Vyamajala
  • 9,287
  • 1
  • 20
  • 42
  • even though added username as partition key and email as sort key still doesn't work, when doing `ConditionExpression: "attribute_not_exists(username)"` or `ConditionExpression: "attribute_not_exists(email)"` it works but not with 2 conditions – webcoder Apr 27 '21 at 20:45
  • @webcoder I tested it out with both conditions as well, it is working as expected. can you confirm what the issue is? – Balu Vyamajala Apr 28 '21 at 12:37