7

Trying to update a document if it exists, otherwise create a document with the same data. I need to do this using an Index rather than a direct Ref as well.

Using this to update in cases where I know for certain it already exists. But in this case, since it cannot be know for sure if the Ref exists, it throws an error. Tried checking if the Ref exists, but that doesn't work because the Get fails.

q.Update(
  q.Select(["ref"], q.Get(q.Match(q.Index("fromUUID"), request.UUID))),
  {
    data: request
  }
)

Any help would be greatly appreciated. Thanks.

gm_
  • 598
  • 6
  • 22

2 Answers2

11

Checking if the Ref exists is the right approach, but you should use q.Exists instead of Get (which will fail as you have discovered. You can also use q.Let to avoid some repetition. Something like the below:

q.Let({
    match: q.Match(q.Index('fromUUID'), request.UUID),
    data: { data: request }
  },
  q.If(
    q.Exists(q.Var('match')),
    q.Update(q.Select('ref', q.Get(q.Var('match'))), q.Var('data')),
    q.Create(q.Collection('Foos'), q.Var('data'))
  )
)
cjol
  • 1,485
  • 11
  • 26
2

you can implement the upsert that way:

Let(
  {
    UUID: '611c798e-24c8-11eb-adc1-0242ac120002',
    doc: Match('fromUUID',Var('UUID')),
    upsert: If(Exists(Var('doc')),Update(Select(['ref'],Get(Var('doc'))),{data:{val1:10,val2:20}}),Create(Collection('stackoverflow'),{data:{val1:1,val2:2,uuid:Var('UUID')}}))
  },
  Var('upsert')
)

The index search for an UUID in the collection, if exists, update the document. If not, create a new document with the UUID plus any field/value pairs.

Let me know if this is what you are looking for.

Luigi