Ale*_*uya 6 document insert-update rethinkdb
如何将第二条评论的文本更新为"新内容"
{
name: 'Me',
comments: [{
"author": "Joe S.",
"text": "I'm Thirsty"
},
{
"author": "Adder K.",
"text": "old content"
}]
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*wes 13
更新嵌入式阵列基本上包括两个步骤:
1.您创建整个阵列的修改版本.您可以使用多个操作来修改阵列,它们列在此处:http://www.rethinkdb.com/api/#js:document_manipulation-insert_at
在您的示例中,如果您知道要更新的文档是数组的第二个元素,那么您可以编写类似的内容
oldArray.changeAt(1, oldArray.nth(1).merge({text: "new content"}))
Run Code Online (Sandbox Code Playgroud)
生成新数组.1这里是第二个元素的索引,因为索引从0开始.如果您不知道索引,可以使用indexesOf函数来搜索数组中的特定条目.这里发生了多件事:changeAt替换了数组的元素.这里,索引1处的元素被oldArray.nth(1).merge({text:"new content"})的结果替换.在该值中,我们首先使用oldArray.nth(1)选择我们想要基于新元素的元素.这为我们提供了JSON对象
{
"author": "Adder K.",
"text": "old content"
}
Run Code Online (Sandbox Code Playgroud)
通过使用合并,我们可以用新值替换此对象的文本字段.
2.既然我们可以构造新对象,我们仍然必须将它实际存储在原始行中.为此,我们使用update并将"comments"字段设置为新数组.我们可以通过ReQL r.row变量访问行中旧数组的值.总的来说,查询将如下所示:
r.table(...).get(...).update({
comments: r.row('comments').changeAt(1,
r.row('comments').nth(1).merge({text: "new content"}))
}).run(conn, callback)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2058 次 |
| 最近记录: |