Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update if document exists, otherwise create a new document in faunadb

Tags:

faunadb

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.

like image 662
gm_ Avatar asked Dec 31 '22 19:12

gm_


1 Answers

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'))
  )
)
like image 79
cjol Avatar answered Jan 02 '23 08:01

cjol