0

I am trying to do simple upsert to the array field based on branch condition. However branch does not accept a reql expression as argument and I get error Expected type SELECTION but found DATUM.

This is probably some obvious thing I've missed, however I can't find any working example anywhere.

Sample source:

var userId = 'userId';
var itemId = 'itemId';

r.db('db').table('items').get(itemId).do(function(item) {

  return item('elements').default([]).contains(function (element) {
    return element('userId').eq(userId);
  }).branch(

    r.expr("Element already exist"),

    //Error: Expected type SELECTION but found DATUM
    item.update({
      elements: item('elements').default([]).append({
        userId: 'userId'
      })
    })
  )
})
xb1itz
  • 1,022
  • 10
  • 17

1 Answers1

2

The problem here is that item is a datum, not a selection. This happens because you used r.do. The variable doesn't retain information about where the object originally came from.

A solution that might seem to work would be to write a new r.db('db').table('items').get(itemId) expression. The problem with that option is the behavior isn't atomic -- two different queries might append the same element to the 'elements' array. Instead you should write your query in the form r.db('db').table('items').get(itemId).update(function(item) { return <something>;) so that the update gets applied atomically.

Sam Hughes
  • 89
  • 2
  • Big thanks @sam-hughes. I still wonder if such transaction could be done the optimal way. As far as I have reached - it requires to make two distinct, non-atomic requests or always perform an update. – xb1itz Oct 23 '17 at 11:27
  • @xb1itz -- The update will do it the optimal way. If the update returns the identical document, unchanged, nothing will be written. RethinkDB specifically compares the new version of the document against the old version. I think you could also use r.error to abort the update if you're nervous about that. – Sam Hughes Nov 01 '17 at 22:55
  • can you please help out me. i am also facing the issue with update in rethinkDB.I have posted a question https://stackoverflow.com/questions/51753745/how-to-update-a-nested-object-in-rethinkdb – Mahesh Aug 09 '18 at 09:31