Reputation: 592
I am trying to push a mongoose object into another object, as in Quiz -> Questions(array of questions), here i am trying to push a question object into the questions array after saving the question object. Below is the function which i have written to accomplish the task
function addQuestiontoQuiz(req,res,next){
var q = new question({questionBody:req.body.questionBody,
options:[req.body.option1,req.body.option2,req.body.option3,req.body.option4],
answer:req.body.answer
});
q.save(function(err,question){
if(err){
res.status(422).send("Problem :"+err.message);
}else {
quiz.findOneAndUpdate({quizName:req.params.quizName},{$push:{questions:question}},{upsert:true},function(err){
if(err){
res.status(422).send("Problem: "+err.message);
} else
{
res.redirect('/quiz/'+req.params.quizName+'/questions');
}
});
}
});
}
But i am getting the following error while doing this :
Cast to undefined failed for value "[object Object]" at path "questions"
Here is the quiz model
var question = App.model('question');
var schema = mongoose.Schema({
quizName:{type:String,unique:true,required:true},
questions:[{type:question}]
});
The question model :
var schema = mongoose.Schema({
questionBody :{type:String,required:true},
options:[String],
numOfOptions:{type:Number},
answer:{type:String,required:true}
});
I am stuck at this point, please help.
Upvotes: 3
Views: 3373
Reputation: 12037
The error is a result of the incorrect schema and model definitions.
Schemas should be defined as instances of the mongoose.Schema constructor. Models should be defined with the mongoose.model
method which should supplied the schema as a second argument.
You can refactor the Question
model definition in this manner:
// Note the use of 'new mongoose.Schema'
var questionSchema = new mongoose.Schema({
questionBody: {type:String, required:true},
options: [String],
numOfOptions: {type:Number},
answer: {type:String,required:true}
});
// The 'mongoose.model' method should be given the schema definition.
var Question = mongoose.model('Question', questionSchema);
module.exports = Question;
The Quiz
model can be defined as such:
var quizSchema = new mongoose.Schema({
quizName: {type:String,unique:true,required:true},
// A quiz has many questions.
questions:[{type: mongoose.Schema.Types.ObjectId, ref: 'Question'}]
});
var Quiz = mongoose.model('Quiz', quizSchema);
module.exports = Quiz;
There is no need to use the $push
query operator. Once a quiz
instance has been obtained from the findOneAndUpdate
command, the question
instance can be added directly to the questions
array of the quiz
instance:
quiz.findOneAndUpdate({quizName:req.params.quizName}, function(err, quiz) {
if(err) {
res.status(422).send("Problem: "+err.message);
} else {
quiz.questions.push(question);
res.redirect('/quiz/'+req.params.quizName+'/questions');
}
});
Upvotes: 2