I want to develop an app using express.js and mongoose, to start an express server I need to write
var express = require('express');
var app = express();
var server = app.listen(3000, function () {});
and to connect to mongo, I need to write sth like this:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.once('open', function (callback) {
// yay!
});
but I don't know how to combine these two codes, so that my server starts answering to request, only if my application has established a correct connection to mongo
create your app
var app = express();
create your db
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
create connection handler with callback
var connectDB = function(next){
//Bootstrap db connection
mongoose.connect(db, function(err){
if(err) return next(err);
next();
});
};
create your server
var server = http.createServer(app);
connectDB(function(err){
var port = 8000;
if(err) throw new Error('connection error');
server.listen(port, function(){
console.log('server listening on port ' + port);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.