Your first code block is the answer to your first question. However, it assumes that superhero
is the primary key for your table.
You can set the primary key of a table when creating it:
r.tableCreate('marvel', {primaryKey: 'superhero'}).run(conn, cb)
Your second code block has two mistakes.
First, the mergeOrCreate function does not work because if
statements are evaluated client-side. You must use r.branch
to create the equivalent of an if
statements:
var mergeOrCreate = function(existingDoc) {
return r.branch(existingDoc, /* if */
existingDoc.merge(latestDoc), /* then */
latestDoc) /* else */
}
Second, get
does not support the same syntax as filter
. Its argument should be the value of the primary key. If the primary key is superhero
, then:
r.table('marvel')
.get('Iron Man')
Finally, if superhero
is not the primary key, you have to write a different kind of query. There could be zero, one or many documents with the same superhero
. Here is one way to write it:
r.table('marvel')
.insert(
r.table('marvel')
.filter({ superhero: 'Iron Man' })
.coerceTo('array')
.do(function(docs){
return r.branch(
docs,
docs.merge(latestDoc),
latestDoc)
}),
{ upsert: true })
.run(conn, cb);
Note that because this query depends on more than one document, it is not atomic.