What is the problem with returning a structure from a code node?

As I am learning n8n (I just started) I wanted to make some simple code to transform data received from an API. Below is a screenshot of my problem, followed by the code:

const r = $("Get Documents").item.json.data.results
return {
  id: r.id,
  title: r.title, 
  created: r.created, 
  download_url: `http://paperless:8000/api/documents/${r.id}/download/`
}

I am interested in getting the array below the red line, and transform it to retrieve a few elements that I will pass further. As you can see, this does not work for several reasons.

For one, r.id and other properties are not known, despite being hinted at when I hover above r.

Then when I look at the result of this code, I get:

[
  {
    "download_url": "http://paperless:8000/api/documents/undefined/download/"
  }
]

Where are the rest of the properties in the structure? (and you can see that r.id is undefined

Is this the correct way to pass data from a node to another?


Following @liam 's advice, I will look at the core nodes to try to do what I attempted with my code. Nevertheless, I would like to understand what was wrong in it for the future.

Hey @wpq hope all is well.

It is not working because you set r to be an array and then you attempt to get a property id of an array (instead of an element).

What output are you looking for - 1 item with all elements or many items each being a separate element of the array?

You probably do not need code here to begin with. If you wish to split them out - use split out node and split elements by data.elements, you will end up with many output items.

If you specify the output you desire, we can think of ways you can achieve that.

In case you aren’t following what @jabbson is saying about the reference to the entire array instead of a single array element… your code should work if you add a subscript after ...data.results so you’re not referencing the entire array, but just one element OF the array (results[0]) like this:

const r = $("Get Documents").item.json.data.results[0]
return {
  id: r.id,
  title: r.title, 
  created: r.created, 
  download_url: `http://paperless:8000/api/documents/${r.id}/download/`
}

It might help you see it a bit more clearly if you switch the input view from Schema to JSON.

If you just need a refresher on how to work with arrays in Javascript, read this.

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