Question

I'm using logical deletes by adding a field deletedAt. If I want to get only the deleted documents it would be something like r.table('clients').hasFields('deletedAt'). My method has a withDeletes parameter which determines if deleted documents are excluded or not.

Finally, people at the #rethinkdb IRC channel suggested me to use the filter method and that did the trick:

query = adapter.table(table).filter(filters)
if withDeleted
    query = adapter.filter (doc) ->
        return doc.hasFields 'deletedAt'
else
    query = adapter.filter (doc) ->
        return doc.hasFields('deletedAt').not()
query.run connection, (err, results) ->
...

My question is why do I have to use filter and not something like:

query = adapter.table(table).filter(filters)
query = if withDeleted then query.hasFields 'deletedAt' else query.hasFields('deletedAt').not()
...

or something like that.

Thanks in advance.

Was it helpful?

Solution

The hasFields function can be called on both objects and sequences, but not cannot.

This query:

query.hasFields('deletedAt')

Behaves the same as this one (on sequences of objects):

query.filter((doc) -> return doc.hasFields('deletedAt'))

However, this query:

query.hasFields('deletedAt').not()

Behaves like this:

query.filter((doc) -> return doc.hasFields('deletedAt')).not()

But that doesn't make sense. you want the not to be inside the filter, not after it. Like this:

query.filter((doc) -> return doc.hasFields('deletedAt').not())

OTHER TIPS

One nice that about RethinkDB is that because of the way queries are built up in host language it's very easy to define new fluent syntax by just defining functions in your language. For example if you wanted to have a lacksFields function you could define it in Python (sorry I don't really know coffeescript) like so:

def lacks_fields(stream, *args):
    res = stream
    for arg in args:
        res = res.filter(lambda x: ~x.has_fields(arg))
    return res

Then you can use a nice fluent syntax like:

lacks_fields(stream, "foo", "bar", "buzz")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top