0

I need to iterate through a primary table and add new documents to a different table each with id: and name: entries that match documents in the primary table.

I have read the relevant documentation, which is shamefully sparse, and I found this SO post about iterating over object properties inside of the same table, but this doesnt apply since I want to iterate over objects over a table, not properties in an object, and apply the results to a NEW table (rather than the same table).

Can I iterate through the length of the table and create documents matching certain fields in a new table?

More specifically: Documents in my DB's primary_table have fields id: and name. How do I migrate these id's and corresponding names to a table that details payment_history using one or a combination of forEach , toArray, and next?

My attempt:

r.db('client').table('basic_info').forEach(
  function(id){
    return r.db('client')table('payment_history').insert(
      {
       id: r.db('client').table('basic_info').get(id).getField('id'),  
       name: r.db('client').table('basic_info').get(id).getField('name')
       }  
      );
  }
);

Thanks in advance

Community
  • 1
  • 1
Andrew
  • 737
  • 2
  • 8
  • 24

1 Answers1

1

You could write the forEach like this:

r.db('client').table('basic_info').forEach(function(row) {
  return r.db('client').table('payment_history').insert(
    {id: row('id'), name: row('name')});})

But it would probably be better to write it like this:

r.db('client').table('payment_history').insert(
  r.db('client').table('basic_info').pluck('id', 'name'))
mlucy
  • 5,249
  • 1
  • 17
  • 21
  • Thanks a bunch! Your first suggestion helped me understand the mechanics of forEach. One thing: your answer is missing a quote! – Andrew Jun 22 '16 at 15:22
  • Also: will the second solution iterate through all of the id's in the basic_info table? – Andrew Jun 22 '16 at 15:22
  • 1
    Kind of. What it does is it takes the `basic_info` table (as a lazy stream), strips every document in it down to just the two fields you want, and then lazily inserts that stream into `payment_history`. It should perform better than the `forEach` version because it can take advantage of batching in the inserts. – mlucy Jun 22 '16 at 20:02
  • You said it's a stream. So does that mean that it syncs payment_history with thr entries in basic_ info? – Andrew Jun 22 '16 at 22:57
  • 1
    No, it won't do any sort of synchronization, it will just insert the documents once. A stream just means that you don't have to load all the data into memory at once. – mlucy Jun 23 '16 at 06:35