Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Devon Stanton
Devon Stanton
7,793 Points

Getting a "Cannot read property 'answers' of undefined' or 'typeOf' error when trying to POST an answer to a question.

I've gone through all the video's and tried to see where I've gone wrong in my code, I've tried to follow the code request from beginning to end.

Post Request is as follows:

// routes.js
//POST /questions/:qID:/answers
// Route for creating an answer
router.post('/:qID/answers', function(req, res, next){
  req.question.answers.push(req.body);
  req.question.save(function (err, question) {
    if(err) return next(err);
    res.status(201);
    res.json(question);
  });
});

I managed to track the error here it seems to be specifically with the below line:

 req.question.answers.push(req.body);

I've included the relevant Schema portion as well just for good measure.

const AnswerSchema = new Schema({
    text: String,
    createdAt: {type: Date, default: Date.now},
    updatedAt: {type: Date, default: Date.now},
    votes: {type: Number, default: 0}
});

const QuestionSchema = new Schema({
  text: String,
  createdAt: {type: Date, default: Date.now},
  answers: [AnswerSchema]
});

I've scratched my head bald, this has been a pretty overwhelming last bit and with little testing between so I feel like I could've made an error anywhere between here and the previous section.

I feel like this is going to come down to a typo (again)...