title: Using vapor-fluent to upsert models
body: <p>I am currently struggling with doing an upsert with vapor/fluent. I have a model something like this:</p>
  
  <pre class="lang-swift prettyprint-override"><code>struct DeviceToken: PostgreSQLModel {
      var id: Int?
      var token: String
      var updatedAt: Date = Date()
  
      init(id: Int? = nil, token: String, updatedAt: Date = Date()) {
          self.id = id
          self.token = token
          self.updatedAt = updatedAt
      }
  }
  
  struct Account: PostgreSQLModel {
      var id: Int?
      let username: String
      let service: String
      ...
      let deviceTokenId: DeviceToken.ID
  
      init(id: Int? = nil, service: String, username: String, ..., deviceTokenId: DeviceToken.ID) {
          self.id = id
          self.username = username
          ....
          self.deviceTokenId = deviceTokenId
      }
  }
  </code></pre>
  
  <p>From the client something like</p>
  
  <pre><code>{
      "deviceToken": {
          "token": "ab123",
          "updatedAt": "01-01-2019 10:10:10"
      },
      "account": {
          "username": "user1",
          "service": "some service"
      }
  }
  </code></pre>
  
  <p>is send.</p>
  
  <p>What I'd like to do is to insert the new models if they do not exist else update them. I saw the <code>create(orUpdate:)</code> method however this will only update if the id is the same (in my understanding). Since the client does not send the id i am not quite sure how to handle this. </p>
  
  <p>Also I can't decode the model since the account is send without the <code>deviceTokenId</code> and therefore the decoding will fail. I guess I can address the latter problem by overriding <code>NodeCovertible</code> or by using two different models (one for decoding the json without the id and the actual model from above). However the first problem still remains. </p>
  
  <p>What I exactly want to do is:</p>
  
  <ol>
  <li><p>Update a DeviceToken if an entry with token already exists else create it</p></li>
  <li><p>If an account with the combination of username and service already exists update its username, service and deviceTokenId else create it. DeviceTokenId is the id returned from 1.</p></li>
  </ol>
  
  <p>Any chance you can help me out here ? </p>