How to update an embedded document?

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

{ name: 'Me', comments: [{ "author": "Joe S.", "text": "I'm Thirsty" }, { "author": "Adder K.", "text": "old content" }] } 
+6
source share
2 answers

Updating an inline array basically involves two steps:

1. You create a modified version of the entire array. There are several operations 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 you want to update is the second element of the array, you should write something like

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

to create a new array. 1 here is the index of the second element, since indexes start at 0. If you don't know the index, you can use the indexesOf function to search for a specific record in the array. Several things happen here: changeAt replaces the array element. Here, the element in index 1 is replaced by the result of oldArray.nth (1) .merge ({text: "new content"}). In this value, we first select the element from which we want to base our new element using oldArray.nth (1). This gives us a JSON object

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

Using merge, we can replace the text field of this object with a new value.

2. Now that we can build a new object, we still need to save it in the original line. To do this, we use the update and simply set the comment field to a new array. We can access the value of the old array in the string through the reQL r.row variable. In general, the request will look like this:

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

Daniel's decision is correct. However, there are several open issues for Github for planned improvements, including:

... among other related issues. Until they are introduced in ReQL (in particular, No. 895), Daniel's approach is correct.

+1
source

Source: https://habr.com/ru/post/947402/


All Articles