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调用中呈现数据,就像浏览器期望的那样,但它没有获取任何页面,这就是您收到此错误的原因。

尝试创建一个包含所有 pug 文件new.pug 文件并执行此操作

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 - 使用 Underscore.js 将其绑定(bind)到嵌套函数中

javascript - 修复了容器 Div 中的 Div,使其仅在到达浏览器顶部时向下滚动

node.js - 仅当新数据可用时调用外部 API

node.js - 尝试连接到 Azure 中的 API 但允许来源时出错

ASP.NEt 在 IE 中滚动时 Tab 键顺序丢失

javascript - audio.js 播放器无法在 IE 9 及更低版本中加载

node.js - AWS - SNS - 如何在每次调用的基础上设置发送者?

javascript - 如何使用 React Native 管理 axios 中的 429 错误?

javascript - 当 Node/Express 中的请求已附加某些内容时,需要 Require 语句吗?

node.js - 将变量传递给 jade 模板