2017-10-19 253 views
0

在请求中,我可能会或可能不会有一个“电子邮件”字段。如何更新DynamoDB基于属性的关上的属性值?

在我的DynamoDB更新调用中,我想要构造一个UpdateExpression,使其根据请求的值更新“email”字段,但如果找不到,则使用该字段的前一个值。

它正确地更新,当我把“电子邮件”的要求,但如果我不这样做,它只是更新领域的文字串,userProfile.email,而不是路径,userProfile.email

controller.js:

async function updateUserProfile(ctx) { 
    if (ctx.params && ctx.params.userId) { 
    try { 
     const data = await db('update')({ 
     TableName: TABLE_NAMES.USERS, 
     Key: { 
      userId: ctx.params.userId, 
     }, 
     ExpressionAttributeValues: { 
      ':email': ctx.request.body.email || 'userProfile.email' || null, 
     }, 
     UpdateExpression: 
      'set userProfile.email = :email, 
     }); 
     ctx.status = 200; 
     ctx.body = data; 
    } catch (error) { 
     ctx.throw(400, error); 
    } 
    } 
} 

如果我的请求主体看起来是这样的:

{ "email": "newEmail" } 

然后将更新用户项目看起来就像是这样的:

{ "userProfile": { "email": "newEmail" } 

其目的,但如果我不包括在请求体“电子邮件”,更新后的用户项目看起来是这样的:

{ "userProfile": { "email": "userProfile.email" } 

看来UpdateExpression字面上采取串而不是将其转换为路径。我大概可以用ConditionExpression,但也有其他领域比“电子邮件”,他们也需要自己的ConditionExpression,我只能有一个处于通话状态。

如何让我看到它的价值作为路径,或有另一种方式,我可以与以前的属性值更新?

回答

1

及其与你的EMAIL

ExpressionAttributeValues: { 

':email': ctx.request.body.email || 'userProfile.email' || null, 
} 

当你不有ctx.request.body.email值设定值的方式问题,那么邮件设置为“userProfile.email”。对于你的代码工作,你应该先检查是否ctx.request.body.email!= null,则只有指定的电子邮件值。换句话说,你需要先构建动态的expressionattributes和组变量。

ExpressionAttributeValues:{'expressionattributevaluevriable'}