3

I have an array of existing documents in Rethink. They all have an ID field. What I want to do is basically this (in javascript):

r.table('my_table').replace(myArrayOfDocuments);

When I try that I get an error saying: Inserted value must be an OBJECT (got ARRAY)

Any ideas?

haggy
  • 733
  • 6
  • 11

1 Answers1

8

If you have a list of objects you want to replace, something like this should work:

r.expr(myArrayOfDocuments)
 .forEach(function(row) { return r.table('my_table').get(row('id'))
                                                    .replace(row); })
 .run(conn, callback);

This assumes your primary key is id, but if you want a more generic solution, you can replace id with r.table('my_table').info()('primary_key').

The reason the query you posted doesn't work is that r.table('my_table').replace(...) is trying to replace every row in your table with the argument you gave it - in this case, an array rather than the expected dict. Normally r.table('my_table').replace(...) should be given a function to generate the new row based on the old row. See the documentation for replace for more details or examples.

Tryneus
  • 371
  • 2
  • 4
  • Thanks Tryneus! This looks like exactly what I needed. I don't have enough rep to upvote you but I did mark as accepted. Thanks again! – haggy Jan 30 '15 at 19:24