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

标签 javascript node.js express pug

我尝试通过表单输入在mongoDB中插入数据。问题是,我将重定向到“ / new”并收到“找不到文件”错误,而不是说“已成功插入”。我尝试将用户信息存储在现有的集合“用户”中-之后,我想以路径“ /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')

最佳答案

如果要重定向路由/new,则必须在POST调用中提供一个用于呈现数据的页面,因为Browser期望如此,但是它没有任何页面,这就是为什么要获得此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}

关于javascript - 通过表单输入+ Express.js在mongodb中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39403722/

相关文章:

javascript - node.js/express js模型与 Controller 交互

javascript - Swiper - OpenCart - 背景全尺寸图像不起作用

javascript - jQuery - 阅读更多/阅读更少。如何替换文字?

node.js - 嵌套异步/等待 Nodejs

session - 快速 session 存储和 reapInterval

javascript - "Error: MongooseError: Operation ` users.insertOne() ` buffering timed out after 10000ms",

javascript - 如何在[JavaScript]中实现分页

javascript - 将指定字符转换为大写

javascript - 在Node.js中阻止IO

css - 当有两个使用变量时,node.js较少删除背景属性