Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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)...