javascript - 对于 node.js 中的路径中的值 "[object Object]",强制转换为未定义失败

标签 javascript node.js mongodb mongoose

我试图将 Mongoose 对象插入另一个对象,如 Quiz -> Questions(array of questions),在这里我试图在保存问题对象后将问题对象插入问题数组。下面是我为完成任务而编写的函数

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');
            }
        });
    }
});
}

但是我在执行此操作时遇到以下错误:

Cast to undefined failed for value "[object Object]" at path "questions"

这是测验模型

var question = App.model('question');
var schema = mongoose.Schema({
quizName:{type:String,unique:true,required:true},
questions:[{type:question}]
 });

问题模型:

var schema = mongoose.Schema({
questionBody :{type:String,required:true},
options:[String],
numOfOptions:{type:Number},
answer:{type:String,required:true}
 });

我现在卡住了,请帮忙。

最佳答案

该错误是由于架构和模型定义不正确造成的。

模式应定义为 mongoose.Schema 的实例构造函数。模型应使用 mongoose.model 方法定义,该方法应将模式作为第二个参数提供。

您可以用这种方式重构 Question 模型定义:

// 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;

Quiz 模型可以这样定义:

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;

无需使用 $push 查询运算符。从 findOneAndUpdate 命令获得 quiz 实例后,可以将 question 实例直接添加到 questions quiz 实例数组:

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');
  }
});

关于javascript - 对于 node.js 中的路径中的值 "[object Object]",强制转换为未定义失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35240744/

相关文章:

javascript - 使用 jQuery 创建按钮翻转

node.js - 检查电子邮件是否存在 Sequelize ( Node js)的正确方法?

javascript - 使用 NodeJS 创建 YouTube 播放列表

Mongodb 按日期排序

node.js - 在 Mongoose 中计算平均值

javascript - Typescript:如何从类型中定义严格的常量

javascript - 如何检查特定数组的值并递增或递减它?

javascript - (大于和小于)或等于严格形式

json - 如何通过 LimeSurvey 的远程控制 (JSON) 更新响应

mongodb - 按给定示例中的字段名称更新 mongo 事务