Create a node programmatically then reference an existing node to that node? I'm using Drupal 7 and trying to create a node programmatically. Once the node has been created I would like to reference it to an existing node

I'm creating a node programmatically like below

$node = new stdClass();
$node-&gt;type = $type;
$node-&gt;title = $title;
$node-&gt;uid = $user-&gt;uid;
node_object_prepare($node);
//set field values
node_save($node);


Which works.

I would then like to update an existing node to reference the newly-created node.
I basically load the existing node, get the node id from the newly created node and update the reference field, like below

$node2 = node_load($node2);

$node2-&gt;field_reference['und'][0] = array(
  'target_id' =&gt; $node,
  'target_type' =&gt; 'node',
);

node_save($node2);

drupal_goto("node/$node-&gt;nid");


I get two errors when I add the second part to the code 
Notice: Undefined property: stdClass::$nid in node_tokens()
Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase->execute() 

The first part works, the second does not. I'm getting the id of $node2 through tokens.

How can I make this work?
As for the second part, you need to pass node ID or array of node IDs to node_load function first argument.

Your code should look like the following:

$node2 = node_load($nid); // pass integer node ID or array of integers 

$node2-&gt;field_reference['und'][0] = array(
  'target_id' =&gt; $node-&gt;nid, // pass integer node ID not node object
);

node_save($node2);

drupal_goto("node/{$node-&gt;nid}");