Search code examples
rethinkdbrethinkdb-javascript

Chaining queries in rethinkdb


Lets say I have a "category" table, each category has associated data in the "data" table and it has associated data in other tables "associated" and I want to remove a category with all it's associated data. What I'm currently doing is something like this:

getAllDataIdsFromCategory()
        .then(removeAllAssociated)
        .then(handleChanges)
        .then(removeDatas)
        .then(handleChanges)
        .then(removeCategory)
        .then(handleChanges);

Is there a way to chain these queries on the db-side? my functions currently look like this:

var getAllDataIdsFromCategory = () => {
        return r
            .table('data')
            .getAll(categoryId, { index: 'categoryId' })
            .pluck('id').map(r.row('id')).run();
    }

var removeAllAssociated = (_dataIds: string[]) => {
        dataIds = _dataIds;
        return r
            .table('associated')
            .getAll(dataIds, { index: 'dataId' })
            .delete()
            .run()
    }

var removeDatas = () => {
        return r
            .table('data')
            .getAll(dataIds)
            .delete()
            .run()
    }

notice that I cannot use r.expr() or r.do() since I want to do queries based on the result of the previous query. The problem with my approach is that it won't work for large amounts of "data" since I have to bring all of the ids to the client side, and doing paging for it in the client side in a loop seems like a workaround.


Solution

  • You can use forEach for this:

    r.table('data').getAll(categoryID, {index: 'categoryId'})('id').forEach(function(id) {
      return r.table('associated').getAll(id, {index: 'dataId'}).delete().merge(
        r.table('data').get(id).delete())
    });