Search code examples
javascriptmongodbmeteorhtml-listsspacebars

How to display results from multiple databases into a list format in Meteor


I've been trying to figure out how to display the list of items in two mongo collections into the same list, meaning that equivalently timestamped entries are put into the same list piece.

For example:

{{#each usernames}}
  {{> userlist}}
{{/each>}}

with the list template being

<template name="userlist">
  <li>
  </li>
</template>

and the function 'usernames' (within Template.body.helpers in app.js) being

usernames: function () {
  return Usernames.find({}, {sort: {createdAt: -1}})
}

for a single-database solution returns each database entry in order of creation date.

I've experimented with a bunch of code with both Spacebars and JavaScript(Meteor), but have been unable to combine the results from two databases.

I was wondering if there could be a solution to concatenate the results, but attempting that in Spacebars has been fruitless.


Solution

  • Because MongoDB doesn't support merging, combining or querying multiple collections into one/at once, you'll have to query them separately and create a non-database-backed publication on the server that mixes records from each of the two collections.

    For an example, see the counts-by-room example, and make sure to pass the same publication name ("counts" there) to all added events passed to observeChanges.