使用mongoose将javascript数组插入mongodb时出错

时间:2015-05-22 11:48:46

标签: javascript arrays node.js mongodb

我对node和mongodb很新。我试图使用mongoose将javascript数组变量插入mongodb。但它会导致错误。

运行此代码时收到错误消息:

ValidationError: CastError: Cast to Array failed for value "[object Object],[object Object],[object Object]" at path "questions"

这是我定义的架构

var mongoose = require('mongoose');
var questionSchema = new mongoose.Schema({
    questionSet : String,
    // questionTime:Number,
    questions:[{
        //questionID : String,
        questionNo : String,
        questionSection : String,
        questionStatement : String,
        answerA : String,
        answerB : String,
        answerC : String,
        answerD : String,
        correctAnswer : String
    }]
});
module.exports = mongoose.model('Question', questionSchema);

要使用mongoose将数据插入mongodb,我使用此代码。

var Question = require('../schemas/questions');
exports.testing = function(req,res){
    if (!req.body) return res.sendStatus(400)

    var ques_set = req.body.set;
    var question_array = req.body.ques;
var data = Question({question_set: ques_set, questions: question_array});

    data.save(function(err) {
        if (err) throw err;
        else {
            console.log('Question Inserted');
            res.send("Question Inserted");    
        }
    });
  };

我正在使用这个javascript创建一个类似于我的架构的问题数组。在这里,我使用push()方法创建一个问题数组。

function myFunction1(){
        document.getElementById("questionSet").disabled = true;

        var questionSet = document.getElementById("form_manu").elements[0].value;
    }

function myFunction3(){
    if(count < totalQuestion) {
        question.push({
            questionID:document.getElementById("form").elements[4].value,
            questionSection:document.getElementById("form").elements[5].value,
            questionStatement:document.getElementById("form").elements[6].value,
            answerA : document.getElementById("form").elements[7].value,
            answerB : document.getElementById("form").elements[8].value,
            answerC : document.getElementById("form").elements[9].value,
            answerD : document.getElementById("form").elements[10].value,
            correctAnswer : document.getElementById("form").elements[11].value
        });

UPDATE1
要发送javascript变量,我使用以下javascript函数post

    function post(path, params, method) {
    method = method || "post"; // Set method to post by default if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

我使用<button onclick="post('question', {set: questionSet, ques : question })">Send</button>

从html主体调用此javascript函数

我在控制台上打印了变量ques_setquestion_arrayques_set打印出我传入的字符串,但question_array只显示[object Object],[object Object]

更新2
当我在变量问题上使用JSON.stringify()时,其显示如

[{"questionNo":"1","questionSection":"sec1","questionStatement":"ques1","answerA":"string1","answerB":"string2","answerC":"string3","answerD":"string4","correctAnswer":"A"},{"questionNo":"2","questionSection":"sec2","questionStatement":"Ques2","answerA":"string1","answerB":"string2","answerC":"string3","answerD":"string4","correctAnswer":"B"}]

我知道这个描述很冗长,但我无法减少它。我很抱歉。

2 个答案:

答案 0 :(得分:0)

我不确定您的JSON.stringify(question_array)示例是在浏览器上还是在服务器上运行。所以我会在这里走出去。

您发布为:

<button onclick="post('question', {set: questionSet, ques : question })">Send</button>

我的猜测是你没有在set上收到错误,因为questionSet实际上是一个字符串 - 但question在传输之前/期间没有被字符串化(服务器真正接收在浏览器上生成的字符串[object Object],[object Object],或者客户端或服务器上存在某种dataType问题。

你可以先试试这个:

<button onclick="post('question', {set: questionSet, ques : JSON.stringify(question) })">Send</button>

<强>更新

实际上,您的表单生成代码正在执行此操作:

hiddenField.setAttribute("value", params[key]);

所以,在某些时候params["ques"]包含一个对象数组,而不是一个字符串。 JS将为[object Object]数组中包含的每个{}对象打印question。你可以这样做:

hiddenField.setAttribute("value", JSON.stringify(params[key]));

答案 1 :(得分:0)

将您的questionSchema变量定义更改为:

var questionVariable = new mongoose.Schema({
    //questionID : String,
    questionNo : String,
    questionSection : String,
    questionStatement : String,
    answerA : String,
    answerB : String,
    answerC : String,
    answerD : String,
    correctAnswer : String
});

var questionSchema = new mongoose.Schema({
    questionSet : String,
    // questionTime:Number,
    questions:[questionVariable]
});

这是必需的,因为mongoose无法在没有相关模式的情况下解析对象。现在,当你为内部问题对象创建一个新的Schema并在主问题中引用它时,mongoose应该能够解析你的对象。