1

I want to randomly select a single item from a collection of 0 to many items and if it exists, update a specific field. If the item does not exist, I'd like the function to perform no update and return null.

My current REQL code:

r.db('test').table('test')
.filter({
    something: true
}).sample(1).nth(0).default(null).update(function(thing) {
    return r.branch(
        thing.ne(null),
        thing.without('reserve'),
        null
    )
}, {
    returnChanges: true
});

This always returns the error: Expected type SELECTION but found DATUM I am not sure how to address this issue with REQL.

mark
  • 1,953
  • 1
  • 24
  • 47

1 Answers1

1

You probably want to write this:

r.db('test').table('test').filter({something: true}).sample(1).replace(function(thing) {
    return thing.without('reserve');
}, {returnChanges: true});

This will give you back a write summary object that you can use to determine whether or not a replacement actually occured.

mlucy
  • 5,249
  • 1
  • 17
  • 21
  • I don't think this works. If there are no documents returned in the query, the query errors out with `Index out of bounds: 0`. Using `.default(null)` (as I have in the question) creates the `Expected type SELECTION but found DATUM` error. – mark Jun 25 '16 at 02:03
  • I think you should only get `Index out of bounds: 0` if you write `nth`, which I don't in my snippet. (There's no need to; `update` and `replace` work just fine on the result of `sample`.) – mlucy Jun 25 '16 at 03:33
  • You are correct. Thanks! I didn't want to return an array but I can manage the return value application-side. – mark Jun 25 '16 at 19:26