RethinkDB: conditional upsert (only if particular fields are matched)?

Viewed 1550

I know rethinkDB's insert() has an upsert option. Eg, from the docs:

rethinkdb.table('marvel').insert(
  { superhero: 'Iron Man', superpower: 'Arc Reactor' },
  {upsert: true, return_vals: true}
).run(conn, callback)

But say there might be existing record for {superhero: 'Iron Man'} with an incorrect or out of date superpower, and I wanted to either insert { superhero: 'Iron Man', superpower: 'Arc Reactor' } or update any existing {superhero: 'Iron Man'} record?

In short: how can I upsert so that existing records are updated only if particular fields are matched?

Edit: Seems like this is done with .replace():

Here's the important bit from the replace() docs:

You can have new documents inserted if you do a point-replace on a key that isn't in the table

I'm not sure what 'point-replace' means - but I assume it just means replace.

var latestDoc = { superhero: 'Iron Man', superpower: 'Arc Reactor' }
var mergeOrCreate = function(existingDoc) {
  if ( existingDoc ) {
    return existingDoc.merge(latestDoc)
  } else {
    return latestDoc
  }
}
rethinkdb.table('marvel')
  .filter({ superhero: 'Iron Man'})
  .replace(mergeOrCreate),
).run(conn, callback)

However in testing, the 'mergeOrCreate' function is being given another function, rather than an actual doc or a cursor, as an argument.

1 Answers
Related