Search code examples
rethinkdbreql

RethinkDB Node.js - Subtract values from each field in a document, using another object


Given a table which contains objects that look something like this:

{
  someString: 'something',
  foo: 100,
  bar: 53,
  baz: 230,
  ignore: 'everything but numbers'
}

and a given JSON object that contains only number values:

{
  foo: 20,
  bar: 15,
  baz: 100
}

I need a ReQL query to subtract all the values in the given JSON object from the values in a selected document. However, the catch is that I don't know what fields are in the given JSON object, it could contain one, all, or none of the number fields (it will never contain non-number fields, or fields that are not in the original table at all).

I understand that I could easily just get the document in question and subtract the values myself and update the document with the new values, but these values are constantly changing. So if I do that then there may be a chance that the values could change in between getting the document and updating it, causing incorrect values to be inserted. So I would like to do the actual subtraction in a query.


Solution

  • r.db("db").table("table").get("id")
      .update({
        "foo":r.row("foo").sub(20),
        "bar":r.row("bar").sub(15),
        "baz":r.row("baz").sub(100)
      })  
    

    You can then modify this update in your code based on what values you have in your given JSON object.