Question

I want to insert new document on update fail - is there any way to do this? Now RethinkDB allows me only to update document on insert fail via {upsert: true} in insert command.

Was it helpful?

Solution

You can use replace with a branch and an explicit merge.

replace is like update, except it completely replaces a document rather than merging with it. The following are equivalent (in Ruby code):

table.get(id).update{|row| {a: row['a']+1}}
table.get(id).replace{|row| row.merge({a: row['a']+1})}

So if you want to do an "update", or else insert a row if there is no row, you could do this:

table.get(id).replace {|row|
  r.branch(
    row.eq(nil),
    INSERT_OBJECT,
    row.merge(UPDATE_OBJECT))
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top