How to set a value programatically only when a content type is saved for the first time? I'm trying to record the user agent string into a text field (field_useragent) the first time a content type is saved.  This is what I tried:

/*
 * Implements hook_ENTITY_TYPE_insert()
 */
function mymodule_node_insert(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity-&gt;getType() == 'my_content_type') {
    // Log the user agent.
    $entity-&gt;set("field_useragent", $_SERVER['HTTP_USER_AGENT']);
  }
}


But, this doesn't save the user agent string.  So I tried using this code:

/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity-&gt;getType() == 'my_content_type') {
    // Log the user agent.
    $entity-&gt;set("field_useragent", $_SERVER['HTTP_USER_AGENT']);  }
}


This saves the user agent string, but it does so every time the node is edited.  How can I save it only upon insertion?
As per @Ivan Jaros comment:

/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity-&gt;getType() == 'my_content_type') {
    /// Log the user agent if the account is being created.
    if ($entity-&gt;isNew()) {
      $entity-&gt;set("field_useragent", $_SERVER['HTTP_USER_AGENT']);
    }
  }
}