The problem: web page works only if i manually start the mongodb. Otherwise i get error "Error failed to connect 127.0.0.1:27017". However, I believe i do create server, maybe i am missing some step.
问题:只有当我手动启动mongodb时,网页才有效。否则我收到错误“错误无法连接127.0.0.1:27017”。但是,我相信我确实创建了服务器,也许我错过了一些步骤。
Also, feel free to point out better ways of doing things, or if something is outdated...
此外,随意指出更好的做事方式,或者如果事情已经过时......
The code:
var express = require('express'),
app = express(),
cons = require('consolidate'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
var mongoclient = new MongoClient(new Server("127.0.0.1", 27017));
var db = mongoclient.db('course');
app.get('/', function(req, res){
// Find one document in our collection
db.collection('hello_combined').findOne({}, function(err, doc) {
if(err) throw err;
res.render('hello', doc);
});
});
app.get('*', function(req, res){
res.send('Page Not Found', 404);
});
mongoclient.open(function(err, mongoclient) {
if(err) throw err;
app.listen(8080);
console.log('Express server started on port 8080');
});
1 个解决方案
#1
2
If you really need to start it "from nodejs", you can start mongodb when you start your node.js server using the child_process module.
如果你真的需要从“nodejs”启动它,你可以在使用child_process模块启动node.js服务器时启动mongodb。
Add the code below in your app code :
在您的应用代码中添加以下代码:
var child_process = require('child_process')
child_process.exec('start mongod', function (err, stdout, stderr) {
if (err) {
console.log(err);
return;
}
});
#1
2
If you really need to start it "from nodejs", you can start mongodb when you start your node.js server using the child_process module.
如果你真的需要从“nodejs”启动它,你可以在使用child_process模块启动node.js服务器时启动mongodb。
Add the code below in your app code :
在您的应用代码中添加以下代码:
var child_process = require('child_process')
child_process.exec('start mongod', function (err, stdout, stderr) {
if (err) {
console.log(err);
return;
}
});