I can't access to collection's propertys

Well, the next lines work fine and i can see the whole object in the console log:

var oneProject = Projects.findOne(key1);

In the console, i can see the oneProject’s propertys, even the name property. Now…with the following lines, the result is error:

var oneProject = Projects.findOne(key1);

The error is this: “Cannot read property ‘name’ of undefined”. What the hell?!

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 }) => {

    var oneProject = Projects.findOne(key1);
  return {

Looks like you’re running into an async issue. When you console.log a variable that points to a reference (ie. an object), and that reference updates later, the console will update as well.

At runtime, it’s likely that the project hasn’t been published by the time console.log is called, so it doesn’t have a name attribute ‘yet’. Then when the reference is populated, console.log prints the reference to the console which now has all it’s attributes.

An easy test to see if that is the case is to console.log a clone of the object instead of a reference to it.

console.log(Object.assign({}, oneProject));

See if the above still prints out a full document with .name. If it does, you’ve got more whacky problems than normal haha.

A solution to being able to access the contents of your project is to defer it with Meteor.defer or stick it in an autorun which depends on sub.ready()

const projectsSubscription = Meteor.subscribe('projects');
Tracker.autorun(() => {
    if (!projectsSubscriptio.ready()) return;
    const oneProject = Projects.findOne(key1); 

Note: If you had that in an autorun, the autorun will re-run every time that project changes. You can disable that behaviour by passing {reactive: false} as the option to .findOne

1 Like