目前,我正在使用ng-model將數據插入到MongoDB中。有沒有辦法使用ng-model將數據插入MongoDB中的數組? 答案是一個數組,應該包含用戶輸入的4個字符串。我嘗試添加[0],[1],[2],[3]到quiz.quizData.answers,但它沒有以數組的形式正確輸入數據。相反,它進入這樣的:AngularJS使用ng-model插入MongoDB/MongoDB中的數組
"answers" : [
{
"0" : "My First Answer",
"1" : "My Second Answer"
}
],
的就應該是這樣,而不是:
"answers" : [
"My First Answer",
"My Second Answer"
],
我的HTML輸入表單:
<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>
我的終點
// POST request for users to post a new quiz entry
apiRouter.route('/quiz')
.post(function(req, res) {
// Create quiz object and assign to 'quiz'
var quiz = new Quiz();
// Contains the quiz question
quiz.question = req.body.question;
// Contains an array with four quiz answers
quiz.answers = req.body.answers;
// Contains one string that matches the correct answer from the array above
quiz.correctAnswer = req.body.correctAnswer;
// Identifies user creating the quiz
quiz.postedBy = req.body.postedBy;
// Identifies the category of the quiz
quiz.category = req.body.category;
// then save new quiz to 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 way wrong....' + err });
} else {
// If no error occurs and it saves, display success
res.json({ message: 'Quiz Created!' });
}
});
});
我的MongoDB的架構:
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);
不幸的是,它創造了完全相同的問題;它將它作爲一個對象插入到數組中,而不是數組中的四個字符串 –
您試過了哪個選項? – Wake
我嘗試了兩種選擇。 –