Array of objects, $slice 5 objects for one page and send back all objects in another page

I have a collection called notifications with the following schema

{
    "userId" : "BX53yzZmpY8pk4QrY",
    "notifications" : [ 
        {
            "from" : "B47WgKpvo6NxY6ihf",
            "msg": "sfdsf"
            "seen" : false
        },
      {
            "from" : "B47WgKpvo6NxY6ihf",
            "msg": "sfdsf"
            "seen" : false
        },
       .....
    ]
}

Initially in the navbar atmost I want to show 5 notifications so I’m doing $slice while publshing

Notifications.find({ userId: memId}, {fields: { notifications: { $slice: -5}}});

and I have separate page where I want to show all the notifications

now when I try to subscribe using separate publish function or changing the limit in the above collection is not subscribing to remaining objects.

Is there anyway to unsubscribe and re-subscribe again so I’ll get all the notifications?

I’m subscribing on oncreated function of layout template, I’m using the same layout template for both the pages so subscription is till active.

Any solutions for this?

You should know that DDP (Meteor’s data protocol) works only on document level, it will send whole root fields over the wire every time something changes (which is quite bad if you expect to have many notifications). That also probably means that your publication with $slice will not work, because DDP doesn’t see any change on the root level of notification document.

With that in mind, I would advise you to change your schema so every document in Notifications collection contains separate notifications, like this:

{
    "userId" : "BX53yzZmpY8pk4QrY",
    "from" : "B47WgKpvo6NxY6ihf",
    "msg": "sfdsf"
    "seen" : false
},
...

This will solve both performance and publication limit problems.

Don’t worry about duplicating userId in every notification object, Mongo is good at handling this.

1 Like