2

I have defined a schema for add question and its like

var mongoose = require('mongoose');
var questionSchema = new mongoose.Schema({
question_set : String,
questions:[{
    question_id : String,
    question_no : Number
}]
});

I would like to insert variables say, ques_set = 'xyz' and an array
question_array = [['id_1',1],['id_2',2],['id_3',3]].

I used this code to insert to mongodb

var questions = require('../schemas/questions');

exports.testing = function(req,res){
  if (!req.body) return res.sendStatus(400)

  var ques_set = 'xyz';
  var  question_array = [['id_1',1],['id_2',2],['id_3',3]];
  var data = question({ques_set,question_array);


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


  };

This shows me an error TypeError: object is not a function. Please help me, I just started nodejs. Thanks

1 Answer 1

1

You need to create a question object that matches your schema, something like this:

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

    var ques_set = 'xyz';
    var question_array = [
        {
            question_id: "id_1",
            question_no: 1
        },
        {
            question_id: "id_2",
            question_no: 2
        },
        {
            question_id: "id_3",
            question_no: 3
        }
    ];

    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");    
        }
    });
  };
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @chridam, for help. I thought it will take javascript arrays, my ignorance! BTW var data = Question({question_set: ques_set, questions: question_array); this statement needs a closing braces.
@user85544 Thank you for spotting the mistake and I'm glad you found this useful :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.