Incrementing Node Value Using Custom Scripts

Hi, I have a question. Currently, I have a node that performs a number increment. I am setting this node with an initial value of 0 and want to increment a number in it.

My node component:

Example of my code:
Previously, I used the following, and it worked perfectly:
$item(0).$node["Set counter"].json["counter"]

I’ve tried other ways, such as:
$('Set counter').first().json.counter += 1 // Increment counter

But it didn’t work.
The value is changed, but the state is not maintained. Instead of being altered, it remains at only the value of 1

For the workflow I am working on, this seems to be the only solution. I tried a few others, but they didn’t work. I need to change the value of the node directly using custom node scripts

Information on your n8n setup

  • **n8n version: 0.224.2
  • **Database (default: SQLite): postgres
  • **n8n EXECUTIONS_PROCESS setting (default: own, main): default
  • **Running n8n via (Docker, npm, n8n cloud, desktop app): docker
  • **Operating system: Ubuntu Server / docker container

It looks like your topic is missing some important information. Could you provide the following if applicable.

  • n8n version:
  • Database (default: SQLite):
  • n8n EXECUTIONS_PROCESS setting (default: own, main):
  • Running n8n via (Docker, npm, n8n cloud, desktop app):
  • Operating system:

My old code worked, after the update n8n version it didn’t work:


items[0].json.lastNode = false;

// Increment counter
$item(0).$node["Set counter"].json["counter"] += 1;

// Check if the current node is the last node
const lastNode = $items("calculate-voucher-quantity", 0, 0).length <= $item(0).$node["Set counter"].json["counter"];

// If it's the last node, set lastNode to true
if (lastNode) {
  items[0].json.lastNode = true;
}

// Return the items array
return items;

I was able to solve it. :raised_hands::sweat_smile:
I used the variable $runIndex, and the code looked like this:

const isLastNode = $items("node_name_here", 0, 0).length <= $runIndex + 1

items[0].json.lastNode = isLastNode

return items;

Workflow example:

2 Likes

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