My DynamoDB table has a primary key as id. The same id will be used to query a record.
Now I want to insert a record with id and originalURL as attributes, I want to insert this record if and only if the id and originalURL doesn't exist in the table.
Update :- ConditionExpression: "attribute_not_exists(id) AND attribute_not_exists(originalURL)" will only works in the context of primary key,according to docs(You can perform a conditional put operation (add a new item if one with the specified primary key doesn't exist) ,so attribute_not_exists(originalURL) is there or not it doesn't make a difference.so i need either a solution where both the conditions work or originalURL also act as a key
router.post('/', async function (req, res, next) {
urlId = await nanoid(8);
//const hashids = new Hashids('this is my salt')
//urlId=hashids.encode(1)
console.log('jatin', urlId);
// urlId=uuidv4();
const { longURL } = req.body
const params = {
TableName: 'url',
Item: {
"id": urlId,
"originalURL": longURL
},
UpdateExpression: "set originalURL = :y",
ConditionExpression: "attribute_not_exists(id) AND attribute_not_exists(originalURL)"
}
dynamoDb.put(params, (error, data) => {
if (error) {
console.log(error);
res.status(400).json({ error: error });
} else if (Object.keys(data).length === 0 && data.constructor === Object) {
res.status(200).json(
{
urlId,
longURL,
status: 'success'
})
}
else {
res.status(400).json({ error: 'Please try again' });
}
})
});
as of now even if i try to send a request with sam original URL which is already present it successfully adds the record which I don't want.