从表单中提取数据并使用Mongoose

时间:2017-03-08 11:55:36

标签: node.js mongodb express mongoose

我想使用Express Node.js和Mongoose /

在网页上显示用户名和年龄

当表单在右侧时,视图应在左侧更新。请参阅this图片。

以下是 users.js (/ users route),后跟表单的 html

Bodyparser已包含在此应用程序的 app.js 中。 点击提交时,会抛出404未找到。

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>

这是我的 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;

app.js中存在

userModel

2 个答案:

答案 0 :(得分:2)

在视图更改

  

name =“fullname”to name =“name”

<强>用户视图

<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>

答案 1 :(得分:0)

首先,要使用req.body,您需要使用body-parserbusboyconnect-busboymultipartyconnect-multiparty,{{ 1}},formidable等 - 请参阅:

此外,这条路线应该是什么:

multer

此字符在URL路径中无效,amd需要在客户端进行URL编码才能工作。你确定这是你需要的路线吗?

如果您正在考虑URL的片段部分(如router.post('#', function(req, res, next) { 中所述),那么在HTTP请求期间根本不会发送它。参见: