2015-06-24 79 views
0

如何使用javascript执行一个查询和条件的多个更新?Rethinkdb通过一个查询和条件进行多个更新

例如,我的文档:

[ 
    { 
     "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 ='Opinion'),现在我想用我的条件描述的值来填充这个索引。 但每个文档都是相同的值(例如:坏)。我如何更新文档,但为每个文档和一个查询运行条件?

回答

1

分配到一个像这样的局部变量(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); 
    }); 
}) 
+0

谢谢你,现在的工作。我将阅读关于lamda功能的这篇博客。 – InnerWorld