问题描述
我在尝试从表中删除嵌套对象时遇到了相当大的困难,并且在此过程中没有意外删除我的所有数据(现在发生了三次,感谢上帝我制作副本)。
I'm having a rather large amount of difficulty with trying to remove nested objects from my table, without accidentally deleting all my data in the process (happened three times now, thank god I made copies).
我的对象:
{
"value1": thing,
"value2": thing,
"value3": thing,
"roles": {
"1": {
"name": "Dave",
"id": "1"
},
"2": {
"name": "Jeff",
"id": "2"
},
"3": {
"name": "Rick",
"id": "3"
},
"4": {
"name": "Red",
"id": "4"
}
}
}`
我尝试了很多重新思考的查询,但到目前为止都没有。应该注意的是,1,2,3和& 4是可以包含任意数量的变量,因此我的查询必须反映出这一点。
I've tried a number of rethink queries, but none have worked thus far. It should be noted that 1, 2, 3, & 4 are variables that can have any amount of numbers, and thus my query must reflect that.
一些尝试的查询:
function removeRole(id, roleName) {
let role = `${roleName}`
return this.r.table('guilds').get(id).replace(function(s){
return s.without({roles : {[role] : { "name": role }}})
})
}
function removeRole(id, roleName) {
return this.r.table('guilds').getAll(id).filter(this.r.replace(this.r.row.without(roleName))).run()
}
function removeRole(id, roleName) {
return this.r.table('guilds').get(id)('roles')(roleName).delete()
}
非常感谢任何帮助,如果问题是起诉,请告诉我。对此仍然相当新,所以反馈表示赞赏。
Any assistance is greatly appreciated, and if the question has issues, please let me know. Still rather new to this so feedback is appreciated.
推荐答案
我不确定我是否理解你的意图,但以下查询似乎正在做你想要完成的事情:
I'm not sure if I understood your intention, but the following query seems to do what you're trying to accomplish:
r.db('test')
.table('test')
.get(id)
.replace((doc) => {
// This expression makes sure that we delete the specified keys only
const roleKeys = doc
.getField('roles')
.values()
// Make sure we have a role name is in the names array
.filter(role => r.expr(names).contains(role.getField('name')))
// This is a bit tricky, and I believe I implemented this in a not efficient
// way probably missing a first-class RethinkDB expression that supports
// such a case out of box. Since we are going to delete by nested dynamic
// ids, RethinkDB requires special syntax to denote nested ids:
// {roles: {ID_1: true, ID_2: true}}
// Well, this is just a JavaScript syntax workaround, so we're building
// such an object dynamically using fold.
.fold({}, (acc, role) => acc.merge(r.object(role.getField('id'), true)));
return doc.without({roles: roleKeys});
})
例如,如果名称
是一个数组,比如 ['Jeff','Rick']
,嵌套的 roleKeys
exssion将是动态评估为:
For example, if names
is an array, say ['Jeff', 'Rick']
, the nested roleKeys
expession will be dynamically evaluated into:
{2: true, 3: true}
合并到 roles
选择器中,上面的查询将对文档进行如下转换:
that is merged into the roles
selector, and the above query will transform the document as follows:
{
"value1": ...,
"value2": ...,
"value3": ...,
"roles": {
"1": {"name": "Dave", "id": "1"},
"4": {"name": "Red", "id": "4"}
}
}
这篇关于RethinkDB:Javascript - 如何删除嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!