Possible to set a limit for a key in publications

Hi there,

I am having a problem with the following issue.
What I need is to return a certain amount of messages inside a collection. The problem here is that the collection has a roomid and inside that is a array with all the messages.
In my publication I can run the return Room.find({userId: “this.userId”}) etc perfectly.
But now I need to be able to return it where the messages field has a limit of lets say 50.
return Room.find({userId: “this.userId”}, {limit: 50}) --> This return has me return a max of 50 Rooms, not 50 messages inside a single room.

I’ve tried things like this:
return Room.find({userId: “this.userId”}, {messages: {limit: 50}}) but this doesn’t work offcourse.

Any advice on how to tackle this problem?

You cannot use skip or limit or fields for subdocuments or nested arrays. You may store messages as separated collection

1 Like

On a quick google search for mongodb query operators, i came across the where operator
Gist of which is that, you can pass a javascript function as a parameter to Collection.find().

db.myCollection.find( { $where: function() { return (this.credits == this.debits) } } );


db.myCollection.find( function() { return (this.credits == this.debits || this.credits > this.debits ) } );

Thus, you can try something like this (It works for me):

return Room.find(function(){ if(this.messages != undefined) return this.messages.length <= 50 })


Seems like you are onto something indeed, thanks alot for the reply!

But for my function there is another problem.

What I have to do is select a room with the find function based on an _id and then limit the max messages of the room of that id.

        _id: {
            $all: [
        function() {
            if (this.messages != undefined)
                return this.messages.length <= 5

but then the code breaks.

I think this should work:

Rooms.find({$and :
  {_id : { $all : [this._id] } },
  {$where : "function() {if (this.messages != undefined) return this.messages.length <= 5}" }