Pages

Wednesday, June 8, 2016

Learning Meteor.js [Part 30]: Retrieve documents for multiple collections from a single publication

In my previous post I showed that when a user is authenticated the web site needs to load his/her latest order. Even though in the database the orders and meals are in separate collections, I would like to return all the documents needed to render the page from a single server call.

Here is the client subscription:
Template.orderDetailsPart.onCreated(function() {
    this.subscribe('lastOrderAndMeals');
});

In the server, the publication will return two cursors (one for the orders collection and another for the meals collection) which will populate the client side collections:
FindFromPublication.publish('lastOrderAndMeals', () => {
    var orderCursor = Orders.find({}, { sort: { createdDate: -1}, limit: 1 });
    var cursors = [orderCursor];

    var orders = orderCursor.fetch();
    var order = orders && orders.length && orders[0];

    if (order) {
        cursors.push(Meals.find({ orderId: order['_id'] }, { sort: { createdDate: 1 }}));
    }

    return cursors;
});

Note that the publication fetches the last order and then finds all meals for that order and returns both cursors to the client. This saves one round trip from the client to the server, but should not be confused with a database join. There are still two requests from the application server to mongodb.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.