I’m currently trying to complete the voting app challenge, and I’m having problems adding an answer to a previously created question.
Currently, I can add polls, delete polls, and list all or by ID.
I’ve created my schemas using the following:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var AnswerSchema = new Schema({
answer: String,
votes: {
type: Number,
default: 0,
}
});
var PollSchema = new Schema({
question: String,
answers: [AnswerSchema]
});
module.exports = mongoose.model('Poll', PollSchema);
And my route is currently:
router.route('/polls/:poll_id/add')
// add answers to an existing poll (accessed at PUT http://localhost:8080/api/polls/:poll_id/add)
.put(function(req, res) {
Poll.findById(req.params.poll_id, function(err, poll) {
if (err)
res.send(err);
poll.answers.push(req.body.answer);
poll.save(function (err) {
if (err)
res.send(err);
res.json({ message: 'Successfully added answer' });
});
});
});
Postman is throwing this error:
{
"errors": {
"answers.0._id": {
"message": "Cast to ObjectID failed for value \"Test Answer\" at path \"_id\"",
"name": "CastError",
"stringValue": "\"Test Answer\"",
"kind": "ObjectID",
"value": "Test Answer",
"path": "_id",
"reason": {
"message": "Cast to ObjectId failed for value \"Test Answer\" at path \"_id\"",
"name": "CastError",
"stringValue": "\"Test Answer\"",
"kind": "ObjectId",
"value": "Test Answer",
"path": "_id"
}
}
},
"_message": "Poll validation failed",
"message": "Poll validation failed: answers.0._id: Cast to ObjectID failed for value \"Test Answer\" at path \"_id\"",
"name": "ValidationError"
}
Googling the error gives the suggestion to use populate, but I was using this subdocument manual page as a guide. I’m unsure where my mistake is, or how to proceed. Does anybody have any advice?
Thanks!