我有一个如下所示的调查表:
{
id: Id,
date: Date,
clients: [{
client_id: Id,
contacts: [{
contact_id: Id,
score: Number,
feedback: String,
email: String
}]
}]
}
我需要更新特定联系人下的 score
和 feedback
字段。目前,我正在运行这样的更新:
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方法,它指定如何更新嵌套的键:值对。但是,我找不到任何示例来更新数组中的单个项目。
有没有更好更简洁的方法来更新嵌套数组中的项目?
最佳答案
您可能需要获取数组,过滤
出数组中所需的值,然后将其再次附加到数组中。然后您可以将更新后的数组传递给 update
方法。
示例
假设您有一个包含两个客户端的文档,这两个客户端都有一个 name
和一个 score
,并且您想更新其中一个的分数:
{
"clients": [
{
"name": "jacob" ,
"score": 200
} ,
{
"name": "jorge" ,
"score": 57
}
] ,
"id": "70589f08-284c-495a-b089-005812ec589f"
}
您可以获取该特定文档,使用匿名函数运行 update
命令,然后将更新后的新数组传入 clients
属性。
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 })
};
});
我确实认为这有点麻烦,并且可能有更好、更优雅的方式来执行此操作,但这应该可以解决您的问题。
数据库架构
也许值得为您的所有联系人创建一个 contacts
表,然后对您的数据进行某种形式的连接。然后您的 clients
数组中的 contacts
属性将类似于:
{
id: Id,
date: Date,
clients: [{
client_id: Id,
contact_scores: {
Id: score(Number)
},
contact_feedbacks: {
Id: feedback(String)
}
}]
}
关于javascript - RethinkDB - 更新嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30265313/