Bob Gohardani Bob Gohardani - 24 days ago 7
React JSX Question

undefined collection error when using simple schema and react (meteor app)

I'm using meteor 1.4 and react to create a poll/vote website and used simple schema in the collection. but when i subscribe to my collection in react component i get this error in chrome console : Uncaught TypeError: Cannot read property 'find' of undefined.

here is the collection file :

import { Mongo } from 'meteor/mongo';
import {SimpleSchema} from 'meteor/aldeed:simple-schema';

const Polls = new Mongo.Collection('polls');
Polls.schema = new SimpleSchema({
createdAt: {
type: Date,
autoValue: function() {
return new Date()
}
},
question: {
type: String
},
answers: {
type: [String]
},
ownerId: {
type: String,
autoValue: function() {
return this.userId
}
},
votes: {
type: [Number]
}
});



Meteor.methods({
'poll.new': function() {
return Polls.insert({});
},

'poll.remove': function(poll) {
return Polls.remove(poll);
},

'poll.update': function(poll, question, answers) {
// db.users.update({"username": "tom"}, {"$set": {"documents": []}})
return Polls.update(poll._id, { $set: { question }}, { $push: {answers: { $each: answers }} });
},

'poll.vote': function(poll, vote) {
return Polls.update(poll._id, {$push: { vote } });
}
});

export default Polls;


and here is the react component :

import React, { Component } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Link } from 'react-router';
import { Polls } from '../../../imports/collections/polls';

class PollsList extends Component {
render() {
return (
<div>
{this.props.polls.map(poll => {
const { question } = poll;
<Link to= {`/polls/vote/${poll._id}`} key={ poll._id }> { question } </Link>
})}
</div>
);
}
}

export default createContainer(() => {
Meteor.subscribe('polls');
return { polls: Polls.find({}).fetch() };
}, PollsList);


and here is the publish code inside server :

import { Meteor } from 'meteor/meteor';
import { Polls } from '../imports/collections/polls';

Meteor.startup(() => {
Meteor.publish('polls', function() {
return Polls.find({});
});

Meteor.publish('myPolls', function() {
return Polls.find({ownerId: this.userId});
});
});


since i dont get any errors inside my cmd, i can't figure out whats the problem in here.

Answer

If this error doesn't appear on server focus on debut your code on react component in this line

return { polls: Polls.find({}).fetch() };

Seems like the Polls are undefined, check the path of Polls import too

import { Polls } from '../../../imports/collections/polls';

I hope that helps.