问题
I have a josn named "update",and it has an embedded list "comments" like this:
{
id: "update/0",
//comments contains elements with type:comment
comments: [{
id:"comment/0"
content:"old first level comment content..."
children:[{
id:"comment/00",
content:""old second level comment content...",
children[...]
}
]
}]
}
Questions are:
1, How to replace "old first level comment content..." with "new first level
comment content..." by ids "update/0" and "comment/0"?
2, How to replace "old second level comment content..." with "new second level
comment content..." by ids "update/0","comment/0" and "comment/00"?
回答1:
First the queries you are looking for:
r.table("update").get("update/0").update(function(doc) {
return doc.merge({
comments: doc("comments").map(function(comment) {
return r.branch(
comment("id").eq("comment/0"),
comment.merge({
content: "new first level comment content..."
}),
comment
)
})
})
}).run(...)
Second one:
r.table("update").get("update/0").update(function(doc) {
return doc.merge({
comments: doc("comments").map(function(comment) {
return r.branch(
comment("id").eq("comment/0"),
comment.merge({
children: comment("children").map(function(child) {
return r.branch(
child("id").eq("comment/00"),
child.merge({
content: "new second level comment content..."
}),
child
)
})
}),
comment
)
})
})
}).run(...)
You probably want to split your data in multiple tables to do joins. In your case, a table "update" and a table "comment". Your table comment can join itself for the children.
You can find more information here:
- http://www.rethinkdb.com/docs/data-modeling/
- http://www.rethinkdb.com/docs/table-joins/
If you have more questions, let me know.
来源:https://stackoverflow.com/questions/22062614/how-to-update-an-item-in-a-embedded-list