I want to create putItem function, where it prevents overwriting previous item if ‘userId’ already existed. Upon searching, I figured that one can use condition expression in the params object before passing to putcommand from aws-sdk. But the problem is, it still update the item, even though the userId has existed. Need your help if anyone can review my code and tell me where I did wrong. Thank you.
import { PutCommand } from "@aws-sdk/lib-dynamodb";
import { ddbDocClient } from "./ddbDocClient.js";
const putItem = async (newItemObject) => {
//check for userId
const userId = {newItemObject};
if(userId){
console.log({userId});
// Set the parameters.
const params = {
TableName: "portal-users",
Item: newItemObject,
ConditionExpression: "userId = :userIdVal",
ExpressionAttributeValues: {
":userIdVal" : userId,
}
};
try {
const data = await ddbDocClient.send(new PutCommand(params));
console.log("Success - item added or updated", data);
} catch (err) {
console.log("Error", err.stack);
}
} else {
console.log('user id is undefined, please provide for new user id');
}
};
const newUser = [
{
userId: 'user01',
nameFirst: 'alison',
nameLast: 'swift'
}
]
newUser.map(x => putItem(x));