Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge an Array of Documents in RethinkDB

Let's say I have a table called bookshelf. I create a bookshelf document that has an array of IDs that references books in another table called books. I am trying to use getAll and merge to combine the documents in a query but I cannot seem to be able to pass all the elements into getAll. I believe getAll is interpreting the array of IDs as a single literal "object".

A bookshelf document:

{
    id: 'MyShelf'
    books: [ 1, 2, 6, 9 ]
}

A book document:

{
    id: 1
    name: 'Merging in RethinkDB for Dummies'
}

My query:

r.db('test').table('bookshelf').merge(function(bookshelf) {
    return {
        booksOnShelf: r.table('books').getAll(bookshelf('books')).coerceTo('array')
    }
})

Expected result:

{
    id: 'MyShelf'
    books: [ 1, 2, 6, 9 ],
    booksOnShelf: [
        { id: 1, name: 'Merging in RethinkDB for Dummies' },
        { id: 2, name: 'Cool Title!' },
        ...
    ]
}

Actual result:

{
    id: 'MyShelf'
    books: [ 1, 2, 6, 9 ],
    booksOnShelf: [ ]
}
like image 696
mark Avatar asked Jun 07 '15 19:06

mark


1 Answers

It turns out that I needed to use r.args to turn the array into actual arguments for use with the getAll function.

Here is the correct query:

r.db('test').table('bookshelf').merge(function(bookshelf) {
    return {
        booksOnShelf: r.table('books').getAll(r.args(bookshelf('books'))).coerceTo('array')
    }
})

And the result:

{
    "books": [ 1, 2 ],
    "booksOnShelf": [{
        "id": 1,
        "title": "RethinkDB for Dummies"
    }, {
        "id": 2,
        "title": "Awesome Title!"
    }],
    "id": "MyShelf"
}
like image 128
mark Avatar answered Sep 24 '22 06:09

mark