gpt4 book ai didi

javascript - RethinkDB:​​Javascript - 如何删除嵌套对象

转载 作者:搜寻专家 更新时间:2023-10-31 23:57:32 24 4
gpt4 key购买 nike

我在尝试从我的表中删除嵌套对象时遇到了相当大的困难,而没有意外删除我在这个过程中的所有数据(现在发生了三次,感谢上帝我制作了副本)。

我的对象:

{
"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 是可以包含任意数量数字的变量,因此我的查询必须反射(reflect)这一点。

一些尝试的查询:

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()
}

非常感谢任何帮助,如果问题有问题,请告诉我。对此仍然相当陌生,因此欢迎提供反馈。

最佳答案

我不确定我是否理解您的意图,但以下查询似乎可以满足您的要求:

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});
})

例如,如果 names 是一个数组,例如 ['Jeff', 'Rick'],嵌套的 roleKeys 表达式将是动态评估为:

{2: true, 3: true}

合并到 roles 选择器中,上面的查询将按如下方式转换文档:

{
"value1": ...,
"value2": ...,
"value3": ...,
"roles": {
"1": {"name": "Dave", "id": "1"},
"4": {"name": "Red", "id": "4"}
}
}

关于javascript - RethinkDB:​​Javascript - 如何删除嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50006585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com