user3475602
user3475602

Reputation: 1217

Meteor collection.find - return multiple values

I want to implement a notification feature in meteor in combination with the meteor-roles package and I want to display the same notification to all users in a role. I thought it is a good idea to store the main notification in the notification collection and a reference to the notification with an id and a "read" attribute in the user collection. Otherwise I need to store each notification for every user in the role.

My db:

User Collection: "username": "UserXYZ", "notifications": [[{ "_id": "231", "read": "false"}], [{ "id": "3234", "read": "true"}]] …
Notification Collection: "_id": "231" …

And now I want to find the corresponding notification, but the problem is, that I can't tell the find function that I want multiple notifications displayed.

I thought something like this would do it:

notifications: function() {
    var user = Users.findOne({_id: Meteor.userId()});
    return Notifications.find({_id: user.notifications._id, read: false});
}

Any help would be greatly appreciated.

Upvotes: 2

Views: 851

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191749

You need to use aggregation to do this. The $unwind operation allows you to make queries on individual notifications:

Users.aggregate(
    {$match: {_id: Meteor.userId()},
    {$unwind: "$notifications"},
    {$match: {"notifications.read": true}}
)

This will return each notification as its own document.

Upvotes: 1

Related Questions