通过一个查询和条件重新思考db多次更新

Rethinkdb multiple update by one query and conditional

本文关键字:新思考 条件 db 更新 查询 一个      更新时间:2023-09-26

如何使用javascript在一个查询和条件下执行多个更新?

例如,我的文档:

[
    {
        "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"
    }
]

这是我的问题:

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));
  }

我为什么要这么做?我创建了第二个索引(this.Index2="意见"),现在我想用我的条件描述的值填充这个索引。但是每个文档都有相同的值(例如:Bad)。如何更新文档,但为每个文档运行条件,并使用一个查询?

分配给这样的局部变量(在您的情况下为result)与RethinkDB的驱动程序构建要发送到服务器的查询对象的方式不兼容。当您编写如上所述的代码时,您在客户端上将一个文本字符串存储在本地变量中一次(而不是在服务器上每行存储一次),然后在函数底部返回的查询中将该文本发送到服务器。您也不能以您尝试的方式使用console.log;在客户端上运行,但查询是在服务器上执行的。你可能会发现http://rethinkdb.com/blog/lambda-functions/有助于理解客户端如何处理传递给update等命令的匿名函数。

您应该使用do进行变量绑定:

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);
  });
})