It is kind of strange because my code creates the node with the referenced user uid in node_field_data, but when I open this node the user reference isn't working. Then I navigated the database and found that, when I update the user reference field in the interface, it is also written as a new registry in the table node__field_user, so I guess I should insert it there too.
But, I don't know how to do this with the API, and I think making it with a SQL query probably means security issues and is probably much more complicated than however it can be done with the API.
This is my code:
$node = Node::create(['type' => 'nodetype']);
$node->set('title', $username );
$node->uid->entity = $userId;
$node->enforceIsNew();
$node->save();