0

I would like to insert a document if it doesn't exist (client_nr not found). If this exists, replace the whole document with new values. The only other this is, that the client_nr is not the primary key. The primary key is the default id created by rethinkdb database.

I tried the below code in node js, but nothing happened. The data is in the variable jsonArray. I use the for loop to go through the whole jsonArray.

Any idea how to solve this problem?

Thanks!!!

for(var Ticker in jsonArray){
    r.db(db).table('trades').filter({client_nr: jsonArray[Ticker].client_nr}).forEach(function(post) {
    return r.branch(
    post.eq(null),
    r.db(db).table('log').insert(jsonArray[Ticker]),
    r.db(db).table('log').replace(jsonArray[Ticker])
     )
    }).run()
}
Big Skinny
  • 53
  • 7

1 Answers1

0

This is much easier to do if client_nr is your primary key. I'd consider doing that instead of using the autogenerated IDs. That will also enforce uniqueness on the field, which is probably what you want.

I was also a little confused by your example because your description made it sound like you wanted to be inserting/replacing into the same table that you're filtering on, but your example is referencing two different tables.

Assuming you want to be using a single table, something like this should do it:

TABLE.filter({client_nr: jsonArray[Ticker].client_nr}).replace(function(row) {
  return r(jsonArray[Ticker]).merge(row.pluck('id'));
}).do(function(res) {
  return r.branch(
    res('replaced').add(res('unchanged')).eq(0),
    TABLE.insert(jsonArray[Ticker]),
    res);
})
mlucy
  • 5,249
  • 1
  • 17
  • 21
  • Hi, thanks for your help. I tried the suggested code but I get this error: **return r.(jsonArray[Ticker]).merge(row.pluck('id')); ^ SyntaxError: Unexpected token (** – Big Skinny Nov 01 '15 at 09:43
  • I tried different code, but with no success. Nothing inserted or replaced. /* r.db(db).table('trades').filter({client_nr: jsonArray[Ticker].client_nr}).do( function(row){ return r.branch(row.eq(null), r.table('trades').insert(jsonArray[Ticker]), r.table('trades').filter({client_nr: row}).replace(jsonArray[Ticker]) ) } ) /* printf("%d\n", 42); /* what was the question again? */ – Big Skinny Nov 01 '15 at 22:32
  • Sorry, I try to edit the comment where you see the code more clearly but I didn't succeed. r.db(db).table('trades').filter({client_nr: jsonArray[Ticker].client_nr}).do( function(row){ return r.branch(row.eq(null), r.table('trades').insert(jsonArray[Ticker]), r.table('trades').filter({client_nr: row}).replace(jsonArray[Ticker]) ) } ) – Big Skinny Nov 01 '15 at 22:38
  • Is the syntax error because you wrote `r.(jsonArray[Ticker])` instead of `r(jsonArray[Ticker])`? If `r(jsonArray[Ticker])` isn't working, try `r.expr(jsonArray[Ticker])`. – mlucy Nov 03 '15 at 16:43