简体   繁体   中英

Error while inserting javascript array to mongodb using mongoose

I am quite new to node and mongodb. I was trying to insert a javascript array variable to mongodb using mongoose. But it result in an error.

I am getting an error message when I run this code :

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

This is my schema I have defined

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

To insert data into mongodb using mongoose, I use this code.

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

I am using this javascript to create a question array similar to my schema. Here I use push() method to create a question array.

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
To send the javascript variables, I use the following javascript function 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();
}

I call this javascript function from the html body using <button onclick="post('question', {set: questionSet, ques : question })">Send</button>

I have printed the variables ques_set and question_array on console. ques_set prints out the string I am passing in, but question_array just shows [object Object],[object Object] .

UPDATE 2
When I use JSON.stringify() on variable questions, its shows like

[{"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"}]

I know this description is much lengthy,But I can't reduce it. My apologies.

I am not sure if your example of JSON.stringify(question_array) is being run on the browser or on the server. So I'll go out on a limb here.

You are posting as:

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

My guess is that you are not getting an error on set because questionSet is really a string -- But question is not being stringified before/during transmission (server is really receiving a string [object Object],[object Object] that is generated on the browser, or there is some kind of dataType issue on the client or server.

You could try this first:

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

UPDATE :

In fact, your form generation code is doing this:

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

so, at some point params["ques"] contains an array of objects, not a string. JS will print [object Object] for each of the {} objects contained inside the question array. You can do this:

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

Change your questionSchema variable definition to:

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

This is required since mongoose is not able to parse the object without a related schema. Now when you create a new Schema for the internal question object and refer it in the main questionSchema mongoose should be able to parse your object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM