Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将项目添加到列表中?_Javascript_Database_Amazon Dynamodb_Graphql_Aws Appsync - Fatal编程技术网

Javascript 如何将项目添加到列表中?

Javascript 如何将项目添加到列表中?,javascript,database,amazon-dynamodb,graphql,aws-appsync,Javascript,Database,Amazon Dynamodb,Graphql,Aws Appsync,我想在“我的用户”表中的listOfVideosRated[]列表中添加一个字符串。如果您可以发布您的模式/解析器映射模板,我可以提供更具体的建议,但我会尽我所能用您目前发布的内容回答这个问题 简单方法 如果你已经有了现有的项目,一种方法是更新现有的项目对并将其传递给你现有的项目 const existingItem = { id: "e5eb02ae-04d5-4331-91e6-11efaaf12ea5", Pairs: [['a', 'b'],['c', 'd'],['e', 'f

我想在“我的用户”表中的
listOfVideosRated[]
列表中添加一个字符串。

如果您可以发布您的模式/解析器映射模板,我可以提供更具体的建议,但我会尽我所能用您目前发布的内容回答这个问题

简单方法 如果你已经有了现有的项目,一种方法是更新现有的项目对并将其传递给你现有的项目

const existingItem = {
  id: "e5eb02ae-04d5-4331-91e6-11efaaf12ea5",
  Pairs: [['a', 'b'],['c', 'd'],['e', 'f']]
}

const newPairs = {
  number1: "g",
  number2: "h"
}

const updateinfo = {
  id: existingItem.id,
  // Note that if existingItem.Pairs is always defined this can be simplified to
  // Pairs: [...existingItem.Pairs, [newPairs.number1, newPairs.number2]]
  Pairs: existingItem.Pairs ?
      [...existingItem.Pairs, [newPairs.number1, newPairs.number2]] : 
      [[newPairs.number1, newPairs.number2]]
}

try {
  await API.graphql(graphqlOperation (UpdateInfo, { input: updateinfo }))  
  //mutation
  console.log('success')
} 
catch (err) {
  console.log(err)
}
使用DynamoDB函数 如果您没有现有项目,或者如果
可能相当大,则可以使用AWS DynamoDB的
列表_append
功能

列表附加(操作数,操作数)

此函数的计算结果为添加新元素的列表。通过颠倒操作数的顺序,可以将新元素追加到列表的开头或结尾

下面是一个使用它的特定突变的例子

### SDL
type Item {
    id: ID!
    Pairs: [[String]]
}

input AddPairInput {
    id: ID!
    number1: String!
    number2: String!
}

type Mutation {
    addPairToItem(input: AddPairInput!): Item!
}

...rest of schema omitted for brevity 

### Resolver Request Mapping Template
{
    "version": "2017-02-28",
    "operation": "UpdateItem",
    "key": {
        "id": { "S": "$ctx.args.input.id"}
    },
    "update": {
        ### Note: we also use if_not_exists here so this works if Pairs is not yet defined on the item.
        "expression":"SET Pairs = list_append(if_not_exists(Pairs, :emptyList), :newPair)",
        "expressionValues": 
          { 
            ":newPair":{"L": [{"L":[{"S":"$ctx.args.input.number1"},
                                    {"S":"$ctx.args.input.number2"}]}]},
            ":emptyList":{"L": []}
          }
        }
}

### Resolver Response Mapping Template
$util.toJson($ctx.result)
这种方式也很好,因为如果其他人更新了配对,您就不会覆盖他们的更新。您还可以通过将参数的顺序反转到
list\u append
函数,将新的参数对添加到列表的开头

带AWS放大的DynamoDB功能 如果您的项目是由AWS Amplify生成的,则需要添加

步骤1:向模式中添加新的变体 其他示例 请记住使用添加的任何新解析器更新CustomResources.json文件

向标量值列表中添加单个项 从标量值列表中删除项 从DynamoDB中的列表中删除元素是一个非常困难的问题。必须将非负索引指定为更新表达式的一部分。如果该项上不存在索引,则您的请求不会失败(例如,没有索引越界异常)

type Item@model{
id:id!
单词:[字符串]
}
输入RemoveWordInput{
id:id!
单词索引:Int!
}
类型突变{
removeWordFromItem(输入:RemoveWordInput!):项目!
}
###./amplify/backend/api//resolvers/Mutation.removeWordFromItem.req.vtl
{
“版本”:“2017-02-28”,
“操作”:“UpdateItem”,
“关键”:{
“id”:{“S”:“$ctx.args.input.id”}
},
“更新”:{
“表达式”:“删除单词[$ctx.args.input.wordIndex]”
}
}
###./amplify/backend/api//resolvers/Mutation.removeWordFromItem.res.vtl
$util.toJson($ctx.result)
###用法
从“aws Amplify”导入Amplify,{API,graphqlOperation};
导入*作为来自“./graphql/translations”的突变;
//突变
常量removeWord={
id:'1',
//索引基于0,因此wordIndex:0
//将删除第一项,
//wordIndex:1删除第二个,以此类推。
关键词索引:1
};
const newItem=await API.graphql(graphqlOperation(mutations.removeWordFromItem,{input:removeWord}));

我认为您需要先获取记录,然后更新记录并推送。dynamo中的记录存储为json对象,我认为不能修改对象键,只需替换它们即可。我可能是wrong@NathanQuinn如何删除?还有,我们如何从列表中删除单个项目?list\u append仅连接两个列表,但没有关于如何从列表中删除项目的文档。@chai86您的意思是仅仅一个标量值列表吗?(例如[a”,“b”,“c])@Babu当你说delete时,你的意思是完全从一个项目中删除一个属性吗?当你问从列表中删除一个项目时,我理解你的意思,但我想了解你的第一个用例。我将发布一些使用其他DynamoDB函数的附加示例。@chai86我添加了一个添加单个标量值和多个sca的示例lar值到一个列表。这个答案现在越来越长了。我将制作一个包含更多内容的GitHub回购。绝对精彩的答案,非常有用。希望我能投更多的票!
### ./amplify/backend/api/<api_name>/schema.graphql
type Item @model {
  id: ID!
  Pairs: [[String]]
}

type Mutation {
  addPairToItem(input: AddPairToItemInput!): Item!
}

input AddPairToItemInput {
  id: ID!
  number1: String!
  number2: String!
}
### ./amplify/backend/api/<api_name>/resolvers/Mutation.addPairToItem.req.vtl
{
    "version": "2017-02-28",
    "operation": "UpdateItem",
    "key": {
        "id": { "S": "$ctx.args.input.id"}
    },
    "update": {
        "expression":"SET Pairs = list_append(if_not_exists(Pairs, :emptyList), :newPair)",
        "expressionValues":
          {
            ":newPair":{"L": [{"L":[{"S":"$ctx.args.input.number1"},{"S":"$ctx.args.input.number2"}]}]},
            ":emptyList":{"L": []}
          }
        }
}
### ./amplify/backend/api/<api_name>/resolvers/Mutation.addPairToItem.res.vtl
$util.toJson($ctx.result)
### ./amplify/backend/api/<api_name>/stacks/CustomResources.json
    "Resources": {
        // ...other resources may exist here
        "AddPairToItemResolver": {
            "Type": "AWS::AppSync::Resolver",
            "Properties": {
                "ApiId": {
                    "Ref": "AppSyncApiId"
                },
                "DataSourceName": "ItemTable",
                "TypeName": "Mutation",
                "FieldName": "addPairToItem",
                "RequestMappingTemplateS3Location": {
                    "Fn::Sub": [
                        "s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Mutation.addPairToItem.req.vtl",
                        {
                            "S3DeploymentBucket": {
                                "Ref": "S3DeploymentBucket"
                            },
                            "S3DeploymentRootKey": {
                                "Ref": "S3DeploymentRootKey"
                            }
                        }
                    ]
                },
                "ResponseMappingTemplateS3Location": {
                    "Fn::Sub": [
                        "s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Mutation.addPairToItem.res.vtl",
                        {
                            "S3DeploymentBucket": {
                                "Ref": "S3DeploymentBucket"
                            },
                            "S3DeploymentRootKey": {
                                "Ref": "S3DeploymentRootKey"
                            }
                        }
                    ]
                }
            }
        }
    },
import Amplify, { API, graphqlOperation } from "aws-amplify";
import * as mutations from './graphql/mutations';

// Mutation
const addPairToItem = {
    id: '1',
    number1: 'a',
    number2: 'b'
};

const newItem = await API.graphql(graphqlOperation(mutations.addPairToItem, {input: addPairToItem}));
### ./amplify/backend/api/<api_name>/schema.graphql
type Item @model {
    id: ID!
    words: [String]
}

input AddWordInput {
    id: ID!
    word: String!
}

type Mutation {
    addWordToItem(input: AddWordInput!): Item!
}

### ./amplify/backend/api/<api_name>/resolvers/Mutation.addWordToItem.req.vtl
{
    "version": "2017-02-28",
    "operation": "UpdateItem",
    "key": {
        "id": { "S": "$ctx.args.input.id"}
    },
    "update": {
        "expression":"SET words = list_append(if_not_exists(words, :emptyList), :newWord)",
        "expressionValues":
          {
            ":newWord":{"L": [{"S":"$ctx.args.input.word"}]},
            ":emptyList":{"L": []}
          }
        }
}

### ./amplify/backend/api/<api_name>/resolvers/Mutation.addWordToItem.res.vtl
$util.toJson($ctx.result)


### Usage
import Amplify, { API, graphqlOperation } from "aws-amplify";
import * as mutations from './graphql/mutations';

// Mutation
const newWord = {
    id: '1',
    word: 'foo'
};

const newItem = await API.graphql(graphqlOperation(mutations.addWordToItem, {input: newWord}));
### ./amplify/backend/api/<api_name>/schema.graphql
type Item @model {
    id: ID!
    words: [String]
}

input AddWordsInput {
  id: ID!
  words: [String!]!
}

type Mutation {
  addWordsToItem(input: AddWordsInput!): Item!
}

### ./amplify/backend/api/<api_name>/resolvers/Mutation.addWordsToItem.req.vtl
{
    "version": "2017-02-28",
    "operation": "UpdateItem",
    "key": {
        "id": { "S": "$ctx.args.input.id"}
    },
    "update": {
        "expression":"SET words = list_append(if_not_exists(words, :emptyList), :newWords)",
        "expressionValues":
          {
            ":newWords": $util.dynamodb.toDynamoDBJson($ctx.args.input.words),
            ":emptyList": $util.dynamodb.toDynamoDBJson([])
          }
        }
}

### ./amplify/backend/api/<api_name>/resolvers/Mutation.addWordsToItem.res.vtl
$util.toJson($ctx.result)


### Usage
import Amplify, { API, graphqlOperation } from "aws-amplify";
import * as mutations from './graphql/mutations';

// Mutation
const newWords = {
    id: '1',
    words: ["bar","xyz","bar"]
};

const newItem = await API.graphql(graphqlOperation(mutations.addWordsToItem, {input: newWords}));
type Item @model {
    id: ID!
    words: [String]
}

input RemoveWordInput {
  id: ID!
  wordIndex: Int!
}

type Mutation {
    removeWordFromItem(input: RemoveWordInput!): Item!
}

### ./amplify/backend/api/<api_name>/resolvers/Mutation.removeWordFromItem.req.vtl
{
    "version": "2017-02-28",
    "operation": "UpdateItem",
    "key": {
        "id": { "S": "$ctx.args.input.id"}
    },
    "update": {
        "expression":"REMOVE words[$ctx.args.input.wordIndex]"
    }
}

### ./amplify/backend/api/<api_name>/resolvers/Mutation.removeWordFromItem.res.vtl
$util.toJson($ctx.result)


### Usage
import Amplify, { API, graphqlOperation } from "aws-amplify";
import * as mutations from './graphql/mutations';

// Mutation
const removeWord = {
    id: '1',
    // The index is 0 based so wordIndex: 0
    // would delete the first item,
    // wordIndex: 1 deletes the second, etc.
    wordIndex: 1 
};

const newItem = await API.graphql(graphqlOperation(mutations.removeWordFromItem, {input: removeWord}));