Search code examples
node.jsmongodbloopbackjsloopback

loopback query/find with limit on specific criteria


I'm building a pretty complex find query in strongloop loopback v2 using mongodb where I want to limit certain sections of the search.

For example, if I had a list of chat rooms and want to pull only the past 200 last chats for each rooms, how would I be able to achieve this?

Messages.find({
   "order": "created ASC",
   "where": {
         "or": [
            {roomId: '111'}, // #todo: Limit this room to 200 messages
            {roomId: '222'}, // #todo: Limit this room to 200 messages
         ] 
   }
 }, ()=>{})

Not forgetting that some rooms might have no messages...so I can't do a global limit: 400 in this example.


Solution

  • As mentioned by Olivier, but with example.

    You should search for rooms and include messages with scope limit, example:

    Rooms.find({
       "where": {
          _id: { inq: ["111", "222", ...]} 
       },
       "include": {
          "relation":"messages",
          "order": "created ASC"
          "scope:{
             limit: 200
          }
       }
     }, ()=>{})