RethinkDB - 更新嵌套数组 [英] RethinkDB - Updating nested array
问题描述
我有一个调查表,如下所示:
I have a survey table that looks like so:
{
id: Id,
date: Date,
clients: [{
client_id: Id,
contacts: [{
contact_id: Id,
score: Number,
feedback: String,
email: String
}]
}]
}
我需要更新特定联系人下的得分
和反馈
字段。目前,我正在运行这样的更新:
I need to updated the score
and feedback
fields under a specific contact. Currently, I am running the update like this:
function saveScore(obj){
var dfd = q.defer();
var survey = surveys.get(obj.survey_id);
survey
.pluck({ clients: 'contacts' })
.run()
.then(results => {
results.clients.forEach((item, outerIndex) => {
item.contacts.forEach((item, index, array) => {
if(Number(item.contact_id) === Number(obj.contact_id)) {
array[index].score = obj.score;
console.log(outerIndex, index);
}
});
});
return survey.update(results).run()
})
.then(results => dfd.resolve(results))
.catch(err => dfd.resolve(err));
return dfd.promise;
};
当我查看 update 方法,它指定如何更新嵌套的键:值对。但是,我找不到任何更新数组中单个项的示例。
When I look at the update method, it specifies how to update nested key:value pairs. However, I can't find any examples to update an individual item in an array.
是否有更好的,更有希望更新的方式来更新嵌套数组中的项目? / p>
Is there a better and hopefully cleaner way to update items in a nested array?
推荐答案
您可能需要获取数组,过滤器
输出所需的值在数组中,然后将其再次附加到数组。然后,您可以将更新的数组传递给 update
方法。
You might need to get the array, filter
out the desired value in the array and then append it again to the array. Then you can pass the updated array to the update
method.
示例
假设您有一个包含两个客户的文档名称
和得分
,您想要更新其中一个得分:
Let's say you have a document with two clients that both have a name
and a score
and you want to update the score in one of them:
{
"clients": [
{
"name": "jacob" ,
"score": 200
} ,
{
"name": "jorge" ,
"score": 57
}
] ,
"id": "70589f08-284c-495a-b089-005812ec589f"
}
你可以获取该特定文档,使用匿名函数运行 update
命令,然后将新的更新数组传入客户端
property。
You can get that specific document, run the update
command with an annonymous function and then pass in the new, updated array into the clients
property.
r.table('jacob').get("70589f08-284c-495a-b089-005812ec589f")
.update(function (row) {
return {
// Get all the clients, expect the one we want to update
clients: row('clients').filter(function (client) {
return client('name').ne('jorge')
})
// Append a new client, with the update information
.append({ name: 'jorge', score: 57 })
};
});
我认为这有点麻烦,可能有更好,更优雅的方式,但这应该可以解决你的问题。
I do think this is a bit cumbersome and there's probably a nicer, more elegant way of doing this, but this should solve your problem.
数据库架构
也许它值得为所有联系人创建联系人
表,然后对您的数据进行某种联接。那么 clients
数组中的联系人
属性将类似于:
Maybe it's worth it to create a contacts
table for all your contacts and then do a some sort of join on you data. Then your contacts
property in your clients
array would look something like:
{
id: Id,
date: Date,
clients: [{
client_id: Id,
contact_scores: {
Id: score(Number)
},
contact_feedbacks: {
Id: feedback(String)
}
}]
}
这篇关于RethinkDB - 更新嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!