How to target a collection item by its _id and display specific field data within it?


Let’s say I’m creating a blog and the blog has posts.

BlogPosts = new Mongo.Collection('posts');

Each blog post has a title and bodyText.


    "_id": "epLm58JtTPM9aBZKh",
    "title": "Foxes Can Be Lazy Too",
    "bodyText": "The lazy brown fox jumped over the quick dogs back."

How do I return the value(s) of title and/or bodyText for a specific blog post? In the example above, I would have to target the _id somehow. Can somebody give me an example as to how this is done?

The hardest part of meteor for me so far has been mongo. It’s very frustrating.


Firstly you would need to make sure that the client has subscribed to the collection.
The data might be saved on the server, but unless its properly subscribed to - the client won’t have access to it.
You can add autopublish while learning to get around this for the moment.

As long as the client has the data, you just need to query the database with this call:

// Database Object
let blogObject = BlogPosts.findOne("epLm58JtTPM9aBZKh");

// Title
let blogTitle = blogObject.title;

// Content
let blogContent = blogObject.bodyText;

You can error check by checking if blogObject != null because it will return undefined if the _id doesn’t return a document.

Also - this is using a bit of a shortcut, BlogPosts.findOne("epLm58JtTPM9aBZKh").
This is translated into: BlogPosts.findOne( { _id: "epLm58JtTPM9aBZKh" } );
It only works as shorthand with the _id.

For a blog, you would typically store a slug with the document, and you would search the database for the slug rather than the _id.