Prashant Agrawal
Prashant Agrawal

Reputation: 670

How to store an array from a form in mongodb

I have a form some thing like

<form>
              <label class="label">Class Name</label>
              <label class="input">
                <input type="text" name="class_name[]">
              </label>
            </section>
            <div class="row">
              <section class="col col-5">
                <label class="label">Grade</label>
                <label class="input">
                  <input type="text" name="grade[]">
                </label>
</form>

I want to store this in my mongodb database. I am using a schema like

var SchoolSchema = new mongoose.Schema({
 classroom: [{
        Name: {
            type: String,
            required: true
        },
        grade: {
            type: Number,
            default: 1
        }

    }]
});

Please suggest me how I can save the data from form in this database .

Upvotes: 0

Views: 1244

Answers (1)

Hoan Nguyen
Hoan Nguyen

Reputation: 296

You need to register you SchoolSchema to mongoose first

mongoose.Schema.model('School', SchoolSchema);

Then, at your controller:

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) {
    ...
  });
};

Note: Please follow NodeJS / Javascript conventions

Upvotes: 1

Related Questions