Search code examples
javascriptnode.jsexpressamazon-dynamodbamazon-dynamodb-local

how to check if username or email exist in dynamoDB using node js express?


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?


Solution

  • 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 = "[email protected]";
    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 = "[email protected]";
    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");
      }
    );