NvdB31
NvdB31

Reputation: 81

Meteor object available in Console, but throws 'cannot read property findOne of undefined

I'm new to Meteor and I've been stuck on this problem for hours.

I've created a collection in a file 'sessions.js' at imports/lib/sessions.js

import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';

Sessions = new Mongo.Collection('sessions');

I've created a few documents in the database using the browser console. I then want to return one document using the template helper:

import { Template } from 'meteor/templating';
import { Sessions } from '../../../../imports/lib/sessions.js';

Template.CarCamping.helpers({
    test: function() {
        return Sessions.findOne({name: 'David'});
    }
});

This throws the following error:

debug.js:41Exception in template helper: TypeError: Cannot read property 'findOne' of undefined
    at Object.test (http://localhost:3000/app/app.js?hash=e301d24dd47ccd4c73ae01a856896ad67acaaca0:77:32)
    at http://localhost:3000/packages/blaze.js?hash=ef41aed769a8945fc99ac4954e8c9ec157a88cea:2994:16
    at http://localhost:3000/packages/blaze.js?hash=ef41aed769a8945fc99ac4954e8c9ec157a88cea:1653:16
    at http://localhost:3000/packages/blaze.js?hash=ef41aed769a8945fc99ac4954e8c9ec157a88cea:3046:66
    at Function.Template._withTemplateInstanceFunc (http://localhost:3000/packages/blaze.js?hash=ef41aed769a8945fc99ac4954e8c9ec157a88cea:3687:12)
    at http://localhost:3000/packages/blaze.js?hash=ef41aed769a8945fc99ac4954e8c9ec157a88cea:3045:27
    at Spacebars.call (http://localhost:3000/packages/spacebars.js?hash=65db8b6a8e3fca189b416de702967b1cb83d57d5:172:18)
    at Spacebars.mustacheImpl (http://localhost:3000/packages/spacebars.js?hash=65db8b6a8e3fca189b416de702967b1cb83d57d5:106:25)
    at Object.Spacebars.mustache (http://localhost:3000/packages/spacebars.js?hash=65db8b6a8e3fca189b416de702967b1cb83d57d5:110:39)
    at ._render (http://localhost:3000/app/app.js?hash=e301d24dd47ccd4c73ae01a856896ad67acaaca0:30:22)

What I've tried already:

The thing is: When i query the db from the console using 'Sessions.findOne({name: 'David'});' it does give me the expected result. But from the code itself it's not working.

Help is much appreciated! Thanks in advance.

Upvotes: 1

Views: 488

Answers (1)

David Weldon
David Weldon

Reputation: 64312

You are not exporting Sessions from imports/lib/sessions.js, so when you go to import it, Sessions won't be defined. Try this:

import { Mongo } from 'meteor/mongo';

export const Sessions = new Mongo.Collection('sessions');

You can see a similar pattern with the Todos collection here.

Upvotes: 1

Related Questions