Arjun Jain
Arjun Jain

Reputation: 59

Extract data from form and add to database using Mongoose

I want to simply display usernames and age on the webpage using Express Node.js and Mongoose/

The view should get updated on the left while the form is at the right. Refer this image.

Below is my users.js (/users route) followed by html of the form.

Bodyparser has been included in app.js of this application. On clicking submit, 404 not found is thrown.

Refer this error image

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


/* GET users listing. */
router.get('/', function(req, res, next) {
  res.render('userview');
});


router.post('#', function(req, res, next) {
    
    //User is the model created in app.js of this project
    var newUser = userModel({
          name:req.body.name,
          age: req.body.age         
    });
    
    console.log(newUser);
    // save the user
    newUser.save(function(err) {
      if (err) throw err;

      console.log('User created!');
    });

});

module.exports = router;
 <form method="post">
                     Name:
                    <input type="text" name="name"><br><br>
                     Age:
                    <input type="number" name="age"><br><br>
                    <input type="submit" value="Submit">
 </form>

Here is my app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');
var applist = require('./routes/applist');

var mongoose=require('mongoose');
var app = express();



//set database connection
mongoose.connect('mongodb://localhost:27017/users');
mongoose.connection.on('error',function(){
   console.log('MongoDB Connection Error. Please make sure that MongoDB is running');
    process.exit(1);
});
mongoose.connection.once('open',function(callback){
   console.log('Connected to Database');
   
});

var userSchema = new mongoose.Schema({
   name:{type:String,uppercase:true},
   age:Number
},{collection:'userlist'});

//make model
var userModel = mongoose.model('userModel',userSchema);

app.get('/users', function(req, res, next) {
  userModel.find({},function(err,userModel){
      res.render('userview',{userlist:userModel});
  })
});

module.exports = userModel;



// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

userModel is present in app.js

Upvotes: 0

Views: 2560

Answers (2)

Manoj Khatri
Manoj Khatri

Reputation: 674

On the view change

name = "fullname" to name="name"

userview

<form method="post">
        Name <input type="text" name="name"><br><br>
        Age<input type="number" name="age"><br><br>
       <input type="submit" value="Submit">
 </form>

Upvotes: 3

rsp
rsp

Reputation: 111466

First of all, to use req.body you need to use body-parser or busboy, connect-busboy, multiparty, connect-multiparty, formidable, multer etc. - see:

Also, what is this route supposed to be:

router.post('#', function(req, res, next) {

This character is not valid in the URL path amd needs to be URL-encoded on the client side to work. Are you sure that this is the route your need?

If you are thinking about the fragment part of the URL (as in http://host/path#fragment) then it is not sent during the HTTP request at all. See:

Upvotes: 0

Related Questions