This is the form I am using :
<form method="post" enctype="multipart/form-data">
<label class="label">Class Name</label>
<label class="input">
<input type="text" name="class_name[]">
</label>
<label class="label">Grade</label>
<label class="input">
<input type="text" name="grade[]">
</label>
</form>
Below is the schema I am using :
var SchoolSchema = new mongoose.Schema({
classroom: [{
Name: {
type: String,
required: true
},
grade: {
type: Number,
default: 1
}
}]
});
Firstly I tried saving the data using below function :
var School = new mongoose.Schema.model('School');
exports.submit = function(req, res) {
var classRooms = [];
for (var i = 0; i < req.body.class_name.length; i++) {
classRooms.push({Name: req.body.class_name[i], grade: req.body.grade[i]});
}
School.create({classroom: classRooms}, function(err, school) {
...
});
};
It worked fine when there was only a single entry in the form But for multiple entries it enters all the entries in single document. For e.g if through form I enter
Name: ABC Grade:1 Name: EFG Grade:2
This data dets saved in data base as
classroom:[{Name:ABC,EFG, Grade:1,2}]
and it should be like
classroom:[{Name:ABC, Grade:1},{Name: EFG, Grade:2}]
I even try to change the function as below:
var School = new mongoose.Schema.model('School');
exports.submit = function(req, res) {
var classRooms = [];
for (var i = 0; i < req.body.class_name[0].length; i++) {
classRooms.push({Name: req.body.class_name[0][i], grade: req.body.grade[0][i]});
}
School.create({classroom: classRooms}, function(err, school) {
...
});
};
Now this worked fine for multiple entries, but when I enter a single entrie it didn't worked as expected. For e.g. If I enter following data through form,
Name: AB Grade: 2
It gets saved in the database as
classroom:[{Name:A,Grade:2 },{Name:B,Grade:1}]
Would anyone please let me know what I am doing wrong here and how to correct this. Thanks !!