Search code examples
node.jsmongodbmongoosemongoose-populate

Inserting data in Referenced Documents?


I'm trying to insert data into myMongoDB database, i am using Referenced Documents, but i couldn't find any convenient method to insert data (while fetching is super convenient).
Please Read It before marking duplicate, I've searched whole Stackoverflow and github before posting
This is my Exam Schema

const ExamSchema = new mongoose.Schema({
    name: {},
    description: {},
    allowedTime: {},
    subject: {},
    assignedInCharge: {},
    questions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'MCQuestion' }]
});

And Follows is my Question Schema:

const MultipleChoiceQuestionSchema = new mongoose.Schema({
    question: {},
    answerOptions: [{}],
    correctAnswer: {},
    marksForCorrectAnswer: {},
    negativeMark: {},
    difficulty: {}
});

My Question is: Is there any Build-In method in mongoose to put data in database that I'm missing in the documentation (I've already searched it a thousand times there).

My Input will be as follows:

{
    "name": "Sample Exam 1",
    "description": "IDK if this will work",
    "allowedTime": 123445666,
    "subject": "testsub1",
    "assignedInCharge": "someincharge",
    "questions": [
        {
            "question": "this is que1",
            "answerOptions": ["this is op 1", "this is op 2", "op 3", "op 4"],
            "correctAnswer": "this is op 1",
            "marksForCorrectAnswer": 4,
            "negativeMark": 1,
            "difficulty": 3
        },
        {}, {}, {}
    ]
}

And (sorry for long snippets) what I'm trying to do to insert data into database is:

router.post('/admin/createExam', (request, response) => {

    questions = request.body.questions;
    var idarray = [];

    questions.forEach(function(element) {
        var question = new MCQuestion(element);
        question.save().then((doc) => idarray.push(doc._id), (error) => console.log(error));
    });

    var body = _.pick(request.body, ['Everything Except Questions']);
    body.questions = idarray;

    var exam = new Exam(body);  

    exam.save().then(() =>{
        response.send(exam);
    }).catch((error) => {
        response.status(400).send(error);
    });

});

I am able to successfully save the questions into the questions collection, but the Exam Collection is not being saved correctly.

The Questions collection

The Exam Collection

Please help me, I've been pulling my hairs on this for weeks.


Solution

  • Nevermind, i figured it out, Changing The API method made it good

    router.post('/admin/createExam', (request, response) => {
    
        var body = _.pick(request.body, ['name', 'description', 'allowedTime', 'subject', 'assignedInCharge']);
        var exam = new Exam(body);
    
        request.body.questions.forEach(function(element) {
            element.exam = exam._id;
            var question = new MCQuestion(element);
            exam.questions.push(question._id);
            question.save().catch((error) => console.log(error));
        });
    
        exam.save().then(() =>{
            response.send(exam);
        }).catch((error) => response.status(400).send(error));
    
    });