I am currently utilizing ng-model to input data into my MongoDB. Is there a method to utilize ng-model to insert data into an array within MongoDB? answers is an array that should include 4 strings entered by the user. I attempted adding [0], [1], [2], [3] to quiz.quizData.answers but it did not properly enter the data as an array. Instead, it was entered like this:
"answers" : [
{
"0" : "My First Answer",
"1" : "My Second Answer"
}
],
as opposed to how it should appear:
"answers" : [
"My First Answer",
"My Second Answer"
],
Here is my HTML input form:
<input type="text" name="answers" ng-model="quiz.quizData.answers" placeholder="enter answers here" required>
<input type="text" name="answers2" ng-model="quiz.quizData.answers" placeholder="enter other answers here" required>
Endpoint:
// POST request for users to add a new quiz entry
apiRouter.route('/quiz')
.post(function(req, res) {
// Create quiz object and assign it to 'quiz'
var quiz = new Quiz();
// Includes the quiz question
quiz.question = req.body.question;
// Contains an array with four quiz answers
quiz.answers = req.body.answers;
// Contains one string that represents the correct answer from the above array
quiz.correctAnswer = req.body.correctAnswer;
// Identifies the user creating the quiz
quiz.postedBy = req.body.postedBy;
// Specifies the quiz category
quiz.category = req.body.category;
// save the new quiz to the database
quiz.save(function(err) {
// If an error occurs, display error message in JSON format
if (err) {
return res.json({ success: false, message: 'something went terribly wrong....' + err });
} else {
// If no errors occur and it saves successfully, display success message
res.json({ message: 'Quiz Created!' });
}
});
});
MongoDB Schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// post schema
var QuizSchema = new Schema({
question: { type: String, lowercase: true, required: true },
answers: { type: Array, required: true },
correctAnswer: { type: String, required: true },
category: { type: String, lowercase: true, required: true },
postedBy: { type: String, required: true }
});
module.exports = mongoose.model('Quiz', QuizSchema);