hatch
hatch

Reputation: 327

How to append to array only if it doesn't contain value with rethinkDB

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!

Upvotes: 2

Views: 433

Answers (1)

kureikain
kureikain

Reputation: 2314

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.

Upvotes: 3

Related Questions