3

How should we append an item to an array if the array exists, or create an array and insert to it.

I tried the merge command but that doesn't allow merging arrays, only replacing them.

r.db('testdb').table('users').get('27e55a4a-a6f8-4ec9-bd02-f55f206700ff').merge({ 'hobbies':['Reading'] })

I further tried passing a function but doesnt seem to work:

r.db('testdb').table('users').get('27e55a4a-a6f8-4ec9-bd02-f55f206700ff').merge(function(user) {
  return r.branch(user('hobbies').eq(null),
                  { 'hobbies' : ['Reading'] }
                 user('hobbies').append('Reading'))
});

Consider the below doc structure:

{
"email": email.123@gmail.com, »
"id":  "27e55a4a-a6f8-4ec9-bd02-f55f206700ff" ,
"image": https://lh4.googleusercontent.com/-O4ZXcLRpkHE/AAArAAAAAAAI/AdAAAAAAALMM/Fq968TTkd88Y/photo.jpg?sz=50, »
"name":  "John Doe" 
}

If I would like to add hobbies as an array how should I do it. The query has to work both if the hobby array exists or not.

aknuds1
  • 65,625
  • 67
  • 195
  • 317
anandaravindan
  • 2,401
  • 6
  • 25
  • 35

2 Answers2

4

The most idiomatic way would be .update(function(user) { return {hobbies: user('hobbies').default([]).append('reading')}; })

mlucy
  • 5,249
  • 1
  • 17
  • 21
0

Finally I have figured out myself.

r.db('testdb').table('users')
              .get("27e55a4a-a6f8-4ec9-bd02-f55f206700ff")
              .update(function(user){
                  return r.branch(user.hasFields('hobbies'), 
                       { hobbies: user('hobbies').append('reading')},
                       { hobbies : ['reading']}
                       )})
anandaravindan
  • 2,401
  • 6
  • 25
  • 35