如何更新嵌入式文件? [英] How to update embedded document?

查看:115
本文介绍了如何更新嵌入式文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将第二条评论的文本更新为新内容"

How to update the text of second comment to "new content"

{
  name: 'Me',
  comments: [{
        "author": "Joe S.",
        "text": "I'm Thirsty"
    },
    {
        "author": "Adder K.",
        "text":  "old content"
    }]
}

推荐答案

更新嵌入式阵列基本上涉及两个步骤:

Updating the embedded array basically involves two steps:

1. 您创建整个数组的修改后的版本.您可以使用多种操作来修改数组,并在此处列出: http ://www.rethinkdb.com/api/#js:document_manipulation-insert_at

1. You create a modified version of the whole array. There are multiple operations that you can use to modify an array, and they are listed here: http://www.rethinkdb.com/api/#js:document_manipulation-insert_at

在您的示例中,如果您知道要更新的文档是数组的第二个元素,则可以编写类似

In your example, if you know that the document that you want to update is the second element of the array, you would write something like

oldArray.changeAt(1, oldArray.nth(1).merge({text: "new content"}))

生成新数组. 1是第二个元素的索引,因为索引以0开头.如果您不知道索引,则可以使用indexsOf函数在数组中搜索特定条目.这里发生了很多事情:changeAt替换数组的元素.在这里,索引1处的元素被oldArray.nth(1).merge({text:"new content"})的结果替换.在该值中,我们首先通过使用oldArray.nth(1)选择要作为新元素基础的元素.这给了我们JSON对象

to generate the new array. 1 here is the index of the second element, as indexes start with 0. If you do not know the index, you can use the indexesOf function to search for a specific entry in the array. Multiple things are happening here: changeAt replaces an element of the array. Here, the element at index 1 is replaced by the result of oldArray.nth(1).merge({text: "new content"}). In that value, we first pick the element that we want to base our new element from, by using oldArray.nth(1). This gives us the JSON object

{
    "author": "Adder K.",
    "text":  "old content"
}

通过使用merge,我们可以用新值替换该对象的文本字段.

By using merge, we can replace the text field of this object by the new value.

2. 现在我们可以构造新对象了,我们仍然必须将其实际存储在原始行中.为此,我们使用update并将"comments"字段设置为新数组.我们可以通过ReQL r.row变量访问行中旧数组的值.总体而言,查询将如下所示:

2. Now that we can construct the new object, we still have to actually store it in the original row. For this, we use update and just set the "comments" field to the new array. We can access the value of the old array in the row through the ReQL r.row variable. Overall, the query will look as follows:

r.table(...).get(...).update({
    comments: r.row('comments').changeAt(1,
      r.row('comments').nth(1).merge({text: "new content"}))
  }).run(conn, callback)

这篇关于如何更新嵌入式文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆