現在、私はng-modelを使ってMongoDBにデータを挿入しています。 ng-modelを使用してMongoDBの配列にデータを挿入する方法はありますか? 回答は、ユーザーが入力する4つの文字列を含む配列です。 quiz.quizData.answersに[0]、[1]、[2]、[3]を追加しようとしましたが、データを配列として正しく入力しませんでした。AngularJSでng-modelを使ってMongoose/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のスキーマ:あなたの配列が既に存在する場合
<input ng-repeat="i in [1,2,3,4]" type="text" name="answers{{i}}" ng-model="quiz.quizData.answers[i]" placeholder="enter answers here" required>
:あなたは空の配列を開始している場合は、ちょうどの範囲を反復NG・リピートを使用することができます
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);
残念ながら、まったく同じ問題が発生しました。配列の内部にオブジェクトとして4つの文字列ではなく配列の中に挿入します –
どのオプションを試しましたか? – Wake
私は両方のオプションを試しました。 –