Appending to an Array

Hi!

How can I append new data to an array?

  • I have a Create API Route that creates posts.
  • I would like the user to be able to append data to already existing Records.
  • I believe that I need to use Append, but I’m receiving an error: "Append function requires 2 argument(s) but 1 were given".

This is the structure of the Record in FaunaDB:

{
  miscFields: ""
  ...
  Posts: [
    {
      text: ""
      image: ""
    },
  ]
}

// I want to update Posts with a new post

The new post content is generated on the front-end and passing to a new API Route, which is described below:


// id refers to the record in question, and finds the correct record to be updated

const dbs = await client.query(
      q.Update(q.Ref(q.Collection('collection'), id), {
        data: {
          Posts: q.Append({
            text: postText,
            image: imageURL,
          })
        }
      })
    )
    ...
}

This was one of my attempts and throws an error because the data to be appended to isn’t specified, but I’m not sure how to exactly to describe it.

Any pointers would be much appreciated!

As the error message states, the Append function requires two arguments, the data you want to append, and the array that you want to append the data to. Your query only includes the data to append, and not the base array.

Try updating your query like this:

const dbs = await client.query(
      q.Update(q.Ref(q.Collection('collection'), id), {
        data: {
          Posts: q.Append(
            {
              text: postText,
              image: imageURL,
            },
            q.Select(
              ["data", "Posts"], 
              q.Get(q.Ref(q.Collection('collection'), id))
            )
          )
        }
      })
    )
    ...
}

The changes I made involve using Get to fetch the document being updated, and Select to fetch the Posts field from that document, so that Append can add the new post data to the array.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.