如何使用node js express检查dynamoDB中是否存在用户名或电子邮件?

问题描述

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

有什么帮助吗?

解决方法

从评论来看,用户名是分区键,没有排序键。由于给定用户名总是只有 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",ConditionExpression:
      "attribute_not_exists(username) AND attribute_not_exists(email)",err);
    else console.log("Sucessfully inserted");
  }
);