Search code examples
rethinkdbrethinkdb-javascript

Updating/merging a document through nested array


Context: On the client, a field is modified and that change is propagated to the server as a keypath-value pair. I start out with a keypath, something like foo.bar.baz = cat, which I can convert to {foo: {bar: {baz: "cat"}}} and then merge into my document (which might look something like {foo: {bar: {baz: "dog"}}}).

So far, this has worked fine for all objects, however it breaks down when I need to do something with an array.


Suppose my document in RethinkDB looked like this: {name: "Me", pets: [{name: "Shadow"}]}. The user decides to update the pet's name, so the keypath looks something like pets[0].name = Sparky. As far as I can tell, this can't trivially (or non-trivially, for that matter) be converted into something I can pass to merge. Or can it? Thoughts?


Solution

  • You'd have to write something like .update(function(row) { return {pets: row('pets').changeAt(0, row('pets')(0).merge({name: 'Sparky'}))};}). I would recommend instead making pets a map from names to pets (or from "numbers converted to strings" to pets if you really want indexing).