i have a mongoose schema can any one please tell me how i can insert data into it through create method

Viewed 22

this is my schema i want to know how can i add data through create method in the qurestion field please help

const mongoose = require("mongoose");
const QuizSchema = mongoose.Schema({
course: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "course"
},
topic: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "topic"
},
starttime: {
    type: Date,
    require:true,
},
endtime: {
    type: Date,
    require: true,

},
qusetions: [
    {
        qustiontext: {
            type: String,
        },
        correctans: {
            type: String,

        },
        ansoptions: [
            {
                anstext: {
                    type: String
                }
            }
        ]
    }
],

students: [
    {
        student: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "student"
        },
        selectedans: [
            {
                anstext: {
                    type: String
                }
            }]}],

}, { timestamps:true, });

const Quizmodel=mongoose.model("quiz" ,QuizSchema); module.exports=Quizmodel;

1 Answers

For inserting data into the question field in one document, see the code below.

// fetch the quiz document you want to edit.
const quiz = await Quizemodel.findById(_id);

// edit question field.
quiz.questions.push({qustiontext: '', correctans: '', ...})

// save the document
await quiz.save()

For creating documents and saving them to the database see the code below:

const quiz = new Quizmodel({
 topic: ...,
 starttime: ...,
 ...
});
quiz.save(function (err) {
  if (err) return handleError(err);
  // saved!
});

or with the create method:

Quizmodel.create({
 topic: ...,
 starttime: ...,
 ...
}, function (err, small) {
  if (err) return handleError(err);
  // saved!
});

more details at mongoose documents!

Related