Rql get numerous documents from rethinkdb key list in javascript

So, I have a "person" data table that has a unique id key. I have a list of id that I want to get for data for which I will send as a JSON array from client to server. The service receives the data as a JSON array.

Now is there a way to run a query that will receive documents for each of these identifiers?

Or my only option is to independently analyze the identifiers and build an array of results, and then send this array.

So far I have been trying to use ...

  • getAll - but I cannot get this to work because it takes a dynamic number of parameters, and I don't know how to change my array of values ​​to a dynamic number of parameters.

    (example ... I want to be able to do what is shown below, but I cannot)

    r.db('vp').table('user').getAll(["0", "0", "99"]) 

    I can only do this ...

     r.db('vp').table('user').getAll("0", "0", "99") 
  • expr and forEach are as shown below, but I don't think this might work.

     var arr = []; r.expr(["0", "0", "99"]).forEach(function(id) { }) 
+7
javascript dynamic rethinkdb
source share
4 answers

short answer:

 r.expr([id1, id2, id3]).eqJoin(function(doc) { return doc; }, r.table("person")) 

Longer answer:

There are several ways to do this. Above was what I would call the canonical path. Let what happens is broken down:

First r.expr([id1, id2, id3]) we collect an array to send it to the server.

Then we call eqJoin what it does is take a stream of values ​​and send and index get for each of them. function(doc) { return doc; } function(doc) { return doc; } is a slightly ugly hack because eqJoin requires a display function.

Thus, the above code becomes equivalent:

 [r.table("person").get(id1), r.table("person").get(id2), r.table("person).get(id3)] 
+6
source share

You can also use getAll with a dynamic array. You must resort to apply

 var ids = [1,2,3]; var table = r.table("person"); table.getAll.apply(table, ids).run( connection, callback); 

Please note that now, starting from 1.12, you can simply do

 var ids = [1,2,3]; r.table("person").getAll(r.args(ids)).run(connection, callback) 
+18
source share

Update for 2017. Use the ES6 distribution operator '...'

 r.db('vp').table('user').getAll(...["0", "0", "99"]) 
+1
source share

You can use .expr with .map for a cleaner alternative to .eqJoin

 r.expr(array).map(function(id) { return r.table('user').get(id); }); 
0
source share

All Articles