通过表单输入+ Express.js在mongodb中插入数据

时间:2016-09-09 04:08:41

标签: javascript node.js express pug

我尝试通过表单输入在mongoDB中插入数据。问题是,我正在重定向到'/ new'并收到'找不到文件'错误,而不是说'成功插入'。我尝试在现有集合'user'中存储用户信息 - 之后,我想在路径'/retrieve.pug'中输入表单中的数据并在客户端显示它。我非常感激,如果有人可以帮助我,这是我的代码:

app.js

var express = require('express');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var User = require('./models/user');
var app = express();

// mongodb connection
mongoose.connect("mongodb://localhost:27017/socialempireclub");
var db = mongoose.connection;

// mongo error
db.on('error', console.error.bind(console, 'connection error:'));

// use sessions for tracking logins
app.use(session({
  secret: 'treehouse loves you',
  resave: true,
  saveUninitialized: false,
  store: new MongoStore({
    mongooseConnection: db
  })
}));

// make user ID available in templates
app.use(function (req, res, next){
  res.locals.currentUser = req.session.userId;
  next();
});

// parse incoming requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(require('express-method-override')('method_override_param_name'));
// serve static files from /public
app.use(express.static(__dirname + '/public'));

// view engine setup
app.set('view engine', 'pug');
app.set('views', __dirname + '/views');

// include routes
var routes = require('./routes/index');
app.use('/', routes);

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

// error handler
// define as the last app.use callback
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

app.post('/new', function(req, res){
  new user({
    country: req.body.country
  }).save(function(err, user){
      if(err) res.json(err);
      else res.send('Sucessfully inserted');
  });
});

app.get('/retrieve', function(req, res){
    user.find({}, function(err, user){
        if(err) res.json(err);
        else    res.render('retrieve', {users: docs});
    });
});

// listen on port 3000
app.listen(3000, function () {
  console.log('Express app listening on port 3000');
});

user.js模型

var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var UserSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true,
    required: true,
    trim: true
  },
  email: {
    type: String,
    unique: true,
    required: true,
    trim: true
  },
  password: {
    type: String,
    required: true
  },
  country: String
});
// authenticate input against database documents
UserSchema.statics.authenticate = function(email, password, callback) {
  User.findOne({ email: email })
    .exec(function (error, user){
      if (error) {
        return callback(error);
      } else if ( !user ) {
        var err = new Error('User not found.');
        err.status = 401;
        return callback(err);
      }
      bcrypt.compare(password, user.password, function(error, result){
        if (result === true) {
          return callback(null, user);
        } else {
          return callback();
        }
      })
    });
}
// hash password before saving to database
UserSchema.pre('save', function(next){
  var user = this;
  bcrypt.hash(user.password, 10, function(err, hash){
    if (err) {
      return next(err);
    }
    user.password = hash;
    next();
  })
});
var user = mongoose.model('user', UserSchema);
module.exports = user;

profile.pug // Pug模板引擎//用户信息+表单输入

p.heading-profile Contact details
                 form(action='/new', method='POST')
                  p
                    | First name
                    input.form-control.input-first-name(type='text', placeholder='First name', aria-describedby='sizing-addon3')
                  p
                    | Last name
                    input.form-control.input-last-name(type='text', placeholder='Last name', aria-describedby='sizing-addon3')
                  p
                    | Street address
                    input.form-control.input-street-address(type='text', placeholder='Street address', aria-describedby='sizing-addon3')
                  p
                    | City
                    input.form-control.input-city(type='text', placeholder='City', aria-describedby='sizing-addon3')
                  p
                    | State/Province
                    input.form-control.input-state(type='text', placeholder='State/Province', aria-describedby='sizing-addon3')
                  p
                    | Zip/Post Code
                    input.form-control.input-zip(type='text', placeholder='Zip/Post code', aria-describedby='sizing-addon3')
                  label(for='country') Country
                    input.form-control.input-country(type='text', name='country', aria-describedby='sizing-addon3')
                  input.button(type='submit', value='Edit')

最后,retrieve.pug

html
  head
    title Registration Form
  body
ul
each user in users
    form(action='', method='POST')
      label(for='user[email]') Email:
      input(type='text', name="user[_id]", value=user._id)
      br
      label(for='user[country]') Country:
      input(type='text', name="user[country]", value=user.country)
      br
      input(type='submit')

2 个答案:

答案 0 :(得分:0)

如果您要重定向路线/new,那么您必须提供一个页面,以POST调用Browser调用来呈现数据,但不会得到任何页面&#39 ;为什么你得到这个error

尝试创建new.pug存在所有pug files的文件并执行此操作

app.post('/new', function(req, res) {
    new user({
        country: req.body.country
    }).save(function(err, user) {
        if (err) res.json(err);
        else {
            res.render('new', {
                mesage: 'Sucessfully inserted'
            });
        }
    });
});

例如,创建new.pug以显示简单消息

block content
  p Welcome to #{message}

答案 1 :(得分:0)

以下是解决方案:

  • 我在mongoDB中创建了两个不同的模式:1)user 2)user_info
  • 然后我在app.js中连接了它,并向客户端显示了user_info表单输入