3

I am trying to get form data from HTML form and trying to save it to MongoDB database. I am using Nodejs with Express.

What could be the problem, whenever I hit the submit button, it shows not found and its not saving the data either.

Here is what I have done so far.

var express = require('express');
var router = express.Router();
var app = express();

var mongoose = require('mongoose');
var mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db=mongoose.connection;

db.on('error', console.error.bind(console, 'MongoDB connection error'));

var Schema = mongoose.Schema;
var questionSchema = new Schema({
  sectors: String,
  Qid: String,
  Question: String,
  enabled: Boolean
},{collection:'questionPool'});

var questionModel = mongoose.model('questionModel', questionSchema);


router.get('/', function(req,res){
  res.render("addQuest");
});

router.post('/add', (req,res) =>{
  var questionData = new questionModel(req.body);
  questionData.save()
    .then(item =>{
      res.send("Information saved to database");
    })
    .catch(err =>{
      res.status(400).send("Unable to save to database");
    });
});

module.exports = router;

addQuest.jade

doctype html
html
  head
    title Add Questions
  body
    center
      form(method='post', action='/add')
        label Enter Your Name
        br
        input(type='text', name='sector', placeholder='Enter Sector', required='')
        input(type='text', name='Qid', placeholder='Enter Qid', required='')
        input(type='text', name='Question', placeholder='Enter your Question', required='')
        input(type='boolean', name='enabled', placeholder='Enabled or Disabled', required='')
        input(type='submit', value='Add Question')
s4tr2
  • 415
  • 1
  • 9
  • 27

1 Answers1

0

I tried your code It's working fine for me. Check the database with name my_database exists in your MongoDB through a console. There is no problem with your code.

  • It does exists. Everything is working fine but when I hit the submit button, it redirects to localhost:3000/add where it displays not found. Here is the article that I referred to: https://www.jenniferbland.com/saving-data-to-mongodb-database-from-node-js-application-tutorial/ – s4tr2 Mar 26 '18 at 05:08
  • Figured it out, in the router.post thing the route should be /addQuestions/add – s4tr2 Mar 26 '18 at 05:46