【发布时间】:2017-04-30 11:39:43
【问题描述】:
我无法理解为了连接到 MongoDB 需要做什么,因此我可以将对象插入数据库。我是使用 Express 和 MongoDB 的新手,还没有完全掌握它们。
我使用标准 Express 设置创建的 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 ex_session = require('express-session');
var dateformat = require('dateformat');
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/contacts'
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 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('/', index);
// 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 handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
我的 index.js 如下,我希望在 /mailer 发出 post 请求时,连接到 MongoDB 以设置插入。
var express = require('express');
var router = express.Router();
var url = 'mongodb://localhost:27017/contacts';
var contacts;
/* GET home page. */
var start = function(req, res, next){
console.log("Starting!");
res.render('mailer',{});
}
router.get('/', start);
router.get('/mailer', start);
/* Post mailer Page insert into database*/
router.post('/mailer', function(req, res, next){
res.render('thanks');
console.log("Welcome to the Thank You Page");
MongoClient.connect(url, function(err, db){
if(err == NULL){
console.log("Connected to database");
// parse the body of the page and set up object to send to the
// database
}
});
});
router.get('/contact', function(req, res){
res.render('contact', {});
})
module.exports = router;
【问题讨论】:
-
通常,您不想在每次查询/插入时都创建一个新的 mongo 连接,但为了简单起见,这没关系。除此之外,您似乎走在正确的轨道上,我很难理解您需要帮助的具体内容。
-
每次我尝试连接到数据库时都会收到错误消息:错误:发送后无法设置标题。我将如何设置它以便它只连接一次而不是每次我设置一个帖子时。
-
这是非常基本的东西,很难用简短的 StackOverflow 评论或答案来解释。虽然有很多关于这方面的教程,但应该很容易找到一些关于它通常是如何完成的示例。
-
@svens “如果你不能向一个六岁的孩子解释,那你自己也不懂。”
-
@CharlieMartin 再读一遍。这并不难解释,在 StackOverflow 帖子中从零开始需要很多(对我来说太多)努力。这只是对 OP 的好建议,以防他在这里没有得到好的答案。他的代码中也有多个问题,这又不太适合 SO 问题。我认为目前的答案足以证明这一点。通过在聊天室中询问或按照我的建议通过一个好的教程工作,OP 会得到更好的帮助。