mark
mark

Reputation: 2063

Conditional Delete in RethinkDB

I would like to delete an object in RethinkDB but only if a condition is met.

I came up with the following function that utilizes replace and null (RethinkDB deletes objects when null is passed in to replace()). However, I cannot get this to work as RethinkDB keeps returning Cannot perform bracket on a non-object non-sequencenull. I am only trying to replace one object. What is wrong?

r.db('test')
  .table('test')
  .get('123')
  .replace(function(thing) {
    return r.branch(thing('color').ne('green'),
      r.error('Object color must be green to be deleted'),
      null)
  }, { returnChanges: true })

Upvotes: 1

Views: 187

Answers (2)

Robert Cutajar
Robert Cutajar

Reputation: 3701

I think the problem is as Kludge pointed out that you get null from get("123"). You can test for this condition in the branch with thing.eq(null)

Upvotes: 0

Kludge
Kludge

Reputation: 2835

Are you sure row #123 exists? Anyways, if you're interested in avoiding this error, there are couple of ways of doing that, for example giving a default value for the key color:

    r.db('test')
      .table('test')
      .get("123")
      .replace(function(thing) {
        return r.branch(thing('color').default({color: null}).ne('green'),
          r.error('Object color must be green to be deleted'),
          null)
      }, { returnChanges: true })

Upvotes: 2

Related Questions