简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM