2

I'd like to append a value to an array in a record that looks similar to the following:

{
  _id: 'foo',
  cols: [
    'abc123',
    '123abc'
  ]
}

It's possible that this field doesn't exist and will need to be created prior to appending. I also don't want to append to the array if the value already exists in the array. So far I have the following which satisfies all but the last requirement of not adding duplicate entries.

r.table('users')
 .get(userId)
 .update({
   cols: r.row('cols').default([]).append(uuid)
 }) 

Any help appreciated, thanks!

hatch
  • 317
  • 1
  • 13
  • 2
    You can try using ```setInsert``` https://www.rethinkdb.com/api/javascript/set_insert/ Distinct as far as I know defines that there should be no duplicates – char May 06 '16 at 05:58

1 Answers1

3

You have several solutions.

r.table('users')
 .get(userId)
 .update({
   cols: r.branch(r.row('cols').default([]).contains(uuid),
                   r.row('cols'),
                   r.row('cols').default([]).append(uuid))
 }) 

Or we can use setInsert as @char suggestions

r.table('users')
 .get(userId)
 .update({
   cols: r.row('cols').default([]).setInsert(uuid))
 }) 

The issue with setInsert is it ensure returning a set. So if you have intentinally put duplicate elements in original cols, it will remove dup element.

kureikain
  • 2,304
  • 2
  • 14
  • 9
  • Thanks! I Ended up using the setInsert because that's the functionality I need. I'll have to investigate the `branch` method further. Do you know if one of these is more performant? – hatch May 06 '16 at 11:40
  • Just an FYI, you have an extra ) after the setInsert call. I tried to edit it myself, but for some strange reason stackoverflow won't allow edits of less than 6 characters. Also thanks for this answer, it was also just what I was looking for :) – Chris Nasr Mar 27 '19 at 15:06