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

时间:2018-04-24 16:23:41

标签: javascript json node.js rethinkdb rethinkdb-javascript

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

我的对象:

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

一些尝试过的查询:

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

非常感谢任何帮助,如果问题有问题,请告诉我。对此仍然相当新,所以反馈表示赞赏。

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解您的意图,但以下查询似乎是您要完成的事情:

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"}
  }
}