Bootstrap表单向MongoDB数据库发送错误的数据

时间:2015-06-24 09:12:40

标签: node.js forms mongodb twitter-bootstrap pug

我有一个使用Twitter Bootstrap创建的表单,它将我放入其中的数据错误地发布到我的MongoDB数据库中。数据库的模型是:({date: 'date', link: 'string'}),结果应如下所示:

{ _id: 558a69c644c2a80985299594,
  date: Mon Jul 03 1995 02:00:00 GMT+
  link: 'https://www.youtu.be.com' },

但是当我从表单提交数据时,这就是我得到的:

{ _id: 558a69c644c2a80985299594,__v:0},

当我手动插入集合时,它似乎有效,但我想从表单中提交。

以下是处理POST操作的路由器的代码:

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

/* Database stuff */
//connect to the data store and the set up the database
var db = mongoose.connection;

//connect to the database
mongoose.connect('mongodb://localhost/Mandela_Diaries/data');

//Create a model which connects to the schema and entries collection in the Mandela_Diaries database
var Entry = mongoose.model("Entry", new Schema({date: 'date', link: 'string'}), "entries");

mongoose.connection.on("open", function() {
    console.log("mongodb is connected!");
});

//The route for getting data for the database - GET form
router.get("/", function(req, res) {
    //Send the current entries to the page
    Entry.find({}, function(err, entries) {
        console.log(entries);
        if(err) {
            res.status(404).json({"error": "not found", "err":err});
            return;
        } else {
            //res.json(entries);
            res.render('database', {title: 'database', entries: entries});
        }
    });

});

router.post('/', function(req, res) {
    //console.log(date, link);
    //res.redirect('form')
    var newEntry = new Entry({entries: {'date': req.body.date, 'link': req.body.link}});
    newEntry.save(function(err, entries){
        //console.log(entries);
        //res.redirect('form');
        if (err !== null) {
            res.status(500).json(err);
        } else {
            res.redirect('database');
        };
    });
});

module.exports = router;

以下是使用Jade模板编写的表单代码:

extends layout

block content
    .container
      .row
        .col-s-12
          h1 The Mandela Diaries Database
      .row
        .col-s-4
          h3 Add Entry
      .row
        .col-s-12
          form.form-inline(method='post', action='/create')
            .form-group
              label(for='date') Date: 
              input#datepicker.form-control.datepicker(type='text', value='date')
            .form-group
              label(for='link') Link: 
              input#link.form-control(type='string', value='link')
            button.btn.btn-default(type='submit') Submit
      .row
        p
              | Format options:
              br
              select#format
                option(value='mm/dd/yy') Default - mm/dd/yy
                option(value='yy-mm-dd') ISO 8601 - yy-mm-dd
                option(value='d M, y') Short - d M, y
                option(value='d MM, y') Medium - d MM, y
                option(value='DD, d MM, yy') Full - DD, d MM, yy
                option(value="'day' d 'of' MM 'in the year' yy") With text - 'day' d 'of' MM 'in the year' yy
      .row
        #entries.col-s-12
          ul

          script(type'text/javascript', scrc='../public/js/script.js')

请帮助我,因为我没有时间在这个项目上。

主要的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 routes = require('./routes/index');
var users = require('./routes/users');
var database = require('./routes/database');

var app = express();

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

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

app.use('/', routes);
app.use('/users', users);
app.use('/database', database)
app.use('/create', database)

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

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

app.listen(8080);

console.log("The server has started");

1 个答案:

答案 0 :(得分:0)

我认为问题出在您的玉石模板上。您没有为输入元素指定name属性。尝试添加它们

input#link.form-control(type='string', name='link')

input#datepicker.form-control.datepicker(type='text', name='date')

编辑:

在您的发布路线中,尝试将相关行更改为此var newEntry = new Entry(req.body);