How do I create a relationship?

This has probably been asked a lot but I can’t find a straight answer. How do you make/write a simple one-to-many relationship in meteor?

I believe this package is the most popular method:

So I need a package? It doesn’t work out of the box?

Not at all, though you’d need to make your own “implementation” - This is the method I use:

Meteor.publish("pubName", function(id1) {
  // Use low-level API for transform/join functionality   
  var self = this; // Store context here
  var query = collection1.find({_id: id1});
  var obs = query.observeChanges({
    added: function(id1, doc) {
      // Get relation data from a newly added document
      var id2 = doc.id2;
      // Find the related document and retrive required data
      // then add it to the new document (via "") = collection2.findOne({_id: id2}).data;
      self.added('dbName', id1, doc);
    changed: function(id, doc) {
      self.changed('dbName', id1, doc);
    removed: function() {
      self.removed('dbName', id1);
  // Call ready to register publication

  this.onStop(function() {
    // Stop observing the cursor when client unsubs.

More info: (The low-level API section)

Edit: Note that “dbName” should be whatever goes in this part in bold:
Collection = new Mongo.Collection(“dbName”) Might help also

I think it’s fair to mention this is because MongoDB is not a relational database and has nothing to do with Meteor itself. This is the main reason this functionality doesn’t come out of the box.

If for example you used a MySQL driver instead of the default MongoDB one, you could do proper joins.

1 Like

I see. Good to know.

Installed dburles:collection-helpers. Works great.