How to update-or-create a field within a document?

If during an Update, the targeted field doesn’t exist yet, how to alternatively supply a new value for it?

I think in this case the problem is where during the enclosing Let I’m referring to the not-yet-existing field, to use its current value as one input to its next value.

      q.Let(
        {
          doc: q.Get(q.Match(q.Index('user_email'), email)),
          my: q.Select(['data', 'my'], q.Var('doc')),
          myNext: q.Append([{kind, id}], q.Var('my')), // ★
          ref: q.Select(['ref'], q.Var('doc')),
        },
        q.Update(
          q.Var('ref'),
          { data: { my: q.Var('myNext') } }
        )
      )

line marked with should be, in pseudocode,

  myNext: q.Var('my')
      ? q.Append([{kind, id}], q.Var('my'))
      : [{kind, id}],

The following also results in value not found:

  myNext: q.If(
    q.Var('my'),
    q.Append([{kind, id}], q.Var('my')),
    [{kind, id}]
  )

A default can be added as an optional parameter to q.Select. The example can be fixed as follows,

      q.Let(
        {
          doc: q.Get(q.Match(q.Index('user_email'), email)),
          my: q.Select(['data', 'my'], q.Var('doc'), []), // ←
          myNext: q.Append([{kind, id}], q.Var('my')),
          ref: q.Select(['ref'], q.Var('doc')),
        },
        q.Update(
          q.Var('ref'),
          { data: { my: q.Var('myNext') } }
        )
      )
2 Likes