Search code examples
rethinkdbmerging-data

rethinkdb merging two tables with only one record


I have two documents "Users" and "Roles" and i am merging these two tables records with following query

r.db('myDB').table('users').merge({
roles: r.db('myDB').table('Roles').getAll(r.args(r.row('roles')))('Name').coerceTo('ARRAY')

})

User Document:

{"id":  "1" ,"password":  "123" ,"roles":  "[1]" ,"userName":  "user1"} 
{"id":  "2" ,"password":  "123" ,"roles": ["1","2"] ,"userName":  "user2"}

its working fine when there is more than 1 Role against a user. But it return error if a user has only 1 Role the error is

"RqlRuntimeError: Expected type ARRAY but found STRING in:"


Solution

  • It seems like your roles maybe a string instead of an array. If that's the case, try this:

    r.db('myDB').table('users').merge({
      roles: r.db('myDB').table('roles').getAll(r.args(
        r.branch(r.row('roles').typeOf().eq('ARRAY'), r.row('roles'),[r.row('roles')]))
      )('Name').coerceTo('ARRAY')
    });