4

I would like to limit the number of nested objects inside a Rethinkdb query. Suppose I have conversations with nested messages.

[conversations]

[{
    id: "fgh675",
    name: "Some conversation",
    messages: [{
        id:"jhu432",
        contents: "Hello world!",
        createdAt: "2016-01-01 00:01:01"
    },
    {
        id:"bgj876",
        contents: "Hello earth",
        createdAt: "2016-01-01 00:01:01"
    }]
}]
  1. How can i limit the number of messages objects ?

  2. Event better, how can i write a query returning only the last message .merge(function(c) { return {msg: c("messages").slice(-1)}; }), but I cant find how to order messages first... (would that query be efficient if there are many messages) ?

Romain Bruckert
  • 2,546
  • 31
  • 50

1 Answers1

2

limit can limit the number of messages:

conversations.merge(conversation => {
  messages: conversation('messages').limit(3)
})

orderBy can be used to sort the array:

conversations.merge(conversation => {
  messages: conversation('messages').orderBy('createdAt')
})

If you sort the messages on every query, it may be more efficient to store the message list already sorted.

Etienne Laurin
  • 6,731
  • 2
  • 27
  • 31