Rethinkdb multiple update by one query and conditional

1.1k Views Asked by At

How can I perfom multiple updates with one query and condition, using javascript ?

For example, my docs:

[
    {
        "Author": "Auto",
        "Number": 5,
        "RandomText": "dddbd",
        "Tag": "Srebro",
        "id": "10fbd309-5a7a-4cd4-ac68-c71d7a336498"
    },
    {
        "Author": "Auto",
        "Number": 8,
        "RandomText": "cccac",
        "Tag": "Srebro",
        "id": "37f9694d-cde8-46bd-8581-e85515f8262f"
    },
    {
        "Author": "Auto",
        "Number": 6,
        "RandomText": "fffaf",
        "Tag": "Srebro",
        "id": "b7559a48-a01a-4f26-89cf-35373bdbb411"
    }
]

This is my query:

UpdateIndex()
   {
      this.r.table(this.params.table).update((row) => {
         let result;

         console.log(this.r.expr([row]));

         this.r.branch(
               this.r.row(this.Index2).lt(10),
                       result = "Lucky",
                       result = "Good"
                      );
         /*
         if(this.r.row("Number").lt(3)) result = "Bad";
         else if (this.r.row("Number").lt(5)) result = "Poor";
         else if (this.r.row("Number").lt(10)) result = "Lucky";
         else if (this.r.row("Number").lt(20)) result = "Good";
         else if (this.r.row("Number").lt(50)) result = "Great";
         else result = "Mystic";
         */

         console.log(result);

         return this.r.object(this.Index2, result);
      }).run(this.conn, this.CheckResult.bind(this));
  }

Why I want to do this ? I created second index (this.Index2 = 'Opinion'), and now I would like to populate this index with values which are describe by my condition. But every documents are the same values (example: Bad). How can I update documents, but run condition for every document, and with one query ?

1

There are 1 best solutions below

1
On BEST ANSWER

Assigning to a local variable like that (result in your case) doesn't work with the way RethinkDB's driver builds up the query object to send to the server. When you write code like above, you're storing a literal string in the local variable once on the client (rather than once per row on the server) and then sending that literal to the server in the query you return at the bottom of your function. You also can't use console.log in the way you're trying to; that runs on the client, but your query is executed on the server. You may find http://rethinkdb.com/blog/lambda-functions/ useful for understanding what the client does with the anonymous functions you pass to commands like update.

You should use do for variable binding instead:

r.table(params.table).update(function(row) {
  return r.branch(r.row(Index2).lt(10), "Lucky", "Good").do(function(res) {
    return r.object(Index2, res);
  });
})