0
我想從ejs模板中使用貓鼬向mongodb插入數據。 頁面在點擊提交按鈕後成功重定向,我的數據也在url中顯示,但沒有插入MongoDB Collection。ejs模板數據沒有插入到mongodb
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 mongoose = require('mongoose');
var mongodb = require('mongoDB');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// database connection
mongoose.connect('mongodb://localhost/company');
var mySchema=new mongoose.Schema({
name:String,
email:String
});
var user=mongoose.model('emp', mySchema);
// 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('/', routes);
app.use('/users', users);
// 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;
Index.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<div style="margin:0 auto ; width:50%; padding:20px">
<form action="/users">
<label>Name</label>
<input type="text" name="name">
<br /> <br /> <br /> <br />
<label>Email</label>
<input type="text" name="email">
<br /> <br /> <br /> <br />
<button>submit</button>
</form>
</div>
</body>
</html>
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/users', function(req, res, next) {
new user({
name:req.body.name,
email:req.body.email
}).save(function(err, docs){
if(err)
{
res.json(err);
}
else
{
res.send('success Inserted !');
}
});
});
module.exports = router;
見'新用戶(..)'。您不會導入您的用戶模型,也不會顯示其中定義的任何代碼。 –