Search code examples
javascriptmongodbmeteormongo-collection

Creating a many-to-many relationship between 2 mongodb collections by ids


I have two collections. One is called Posts and the other is called Categories. In the posts collection, are individual posts that each contain an array of id's called categories which are id's of the categories the individual post belongs to stored in the posts.

enter image description here

The second collection is the Categories collection which contains the categories each of the posts belong to

enter image description here

Goal

In my template, I am displaying each post as its title, content, image and author as well as the Category names which come about by linking the Category Ids in the Posts collection to the individual categories in the Category collection

<template name="latest">
    {{#each posts}}
<div>{{> category}}</div>
      <h5 class="latest-title">{{title.rendered}}</h5>
  <img class="latest-img" src="{{featured_image_thumbnail_url}}" alt="" />
    {{/each}}
</template>

In my category template

<template name="category">
  {{#each categories}}
 {{name}}
  {{/each}}

</template>

In my category.js

Template.category.helpers({
  categories(){
    return CategoryCollection.find({ id: parseInt(this.categories) });
  }
});

As you can see, I want to display the names of the categories belonging to a post, they are in an array because a post might have 3 categories it belongs too. but I can't seem to get it to work.

Edit

This is my edit to include the $in

Template.category.helpers({
  categories(){
    return CategoryCollection.find({ id: {$in: this.categories }});
  }
});

And this is my template

<template name="category">
  {{#each categories}}
  {{name}}
  {{/each}}

</template>

It doesn't seem to be working.

Progress

It wasn't working because I hadn't assigned categories to my example post, the above edited code is the answer


Solution

  • You want to use the $in operator:

     return CategoryCollection.find({ id: {$in: this.categories }});