mongodbmeteormeteor-react

I can't access an object's properties


The next lines work fine and I can see the whole object in the console log:

Meteor.subscribe('projects')
var oneProject = Projects.findOne(key1);
console.log(oneProject)

In the console, I can see the oneProject's properties, even the name property.

Now with the following lines, the result is an error:

Meteor.subscribe('projects')
var oneProject = Projects.findOne(key1);
console.log(oneProject.name)

The error is: "Cannot read property 'name' of undefined".

This is the whole code:

import { Meteor } from 'meteor/meteor';
import { withTracker } from 'meteor/react-meteor-data';
import { Projects } from '/imports/api/projects.js';
import ProjectFormUpdate from './ProjectFormUpdate.jsx';

export default ProjectFormUpdateContainer = withTracker(({ key1 }) => {
  Meteor.subscribe('projects')
  var oneProject = Projects.findOne(key1);
  console.log(oneProject.name)
  return {
    oneProject:oneProject,
  };
})(ProjectFormUpdate);

Solution

  • A subscription in Meteor is asynchronous. This means the data is not always immediately available.

    Tracker.autorun(() => {
      const sub = Meteor.subscribe('projects');
      if (sub.ready()){
        const oneProject = Projects.findOne(key1);
        console.log(oneProject.name);
      }
    });
    

    will not try to find the project until the subscription is ready.