0

我正在将 dynamoDB 与 node js express 项目一起使用,其中用户名和电子邮件地址都应该是唯一的,尝试如下但没有用:

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,
        });
      }
    });

请问有什么帮助吗?

4

1 回答 1

0

从评论中,用户名是分区键,没有排序键。由于给定用户名总是只有 1 条记录,我们只需要检查用户名是否存在。

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");
  }
);

以用户名作为分区键,电子邮件作为排序键,这意味着只有两者的组合是唯一的。

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");
  }
);
于 2021-04-27T13:20:53.017 回答