使用Express连接到MongoDB

时间:2016-12-15 00:27:33

标签: html mongodb express

我无法理解为了连接到MongoDB需要做什么,所以我可以将一个Object插入数据库。我是使用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;

2 个答案:

答案 0 :(得分:1)

*表示快递,

 var mongo = require('mongodb');
        var MongoClient = mongo.MongoClient;    
        MongoClient.connect('mongodb://'+DB_USERNAME+':'+DB_PASSWORD+'@'+DB_HOST+':'DB_PORT+'/'+DB_NAME,function(err, db){  
              if(err) 
                console.log(err);
              else
              {
                console.log('Mongo Conn....');

              }
            });

//用于Express的本地服务器 //在本地服务器DBPASSWOAD和DBusername中不需要

MongoClient.connect('mongodb://'+DB_HOST+':'+DB_PORT+'/'+DB_NAME,function(err, db){  
      if(err) 
        console.log(err);
      else
      {
        console.log('Mongo Conn....');

      }
    });

答案 1 :(得分:0)

你的代码非常混乱,我可以显示你的配置,你可以参考。

db.js
import mongoose from 'mongoose';

export default function connectDB() {
    mongoose.Promise = global.Promise;
    mongoose.connect('mongodb://localhost:27017/contacts');
    mongoose.connection.once('open', function () {
        console.log('mongodb connected.');
    });
};


app.js
import connectDB from "db.js";

connectDB();


user.model.js
import mongoose from 'mongoose';

const schema = mongoose.Schema({
    email: {type: String, required: true},
    mobile: {type: String},
    password: {type: String, required: true},
});

const User = mongoose.model('User', schema, 'user');

export default User;

然后在您的路由器文件中,您可以调用User.find()或User.update或...