如何使用node.js设置MongoDB数据库连接?
这是我的app.js文件:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.htm');
});
app.use(express.static(__dirname + '/assets'));
io.sockets.on('connection', function(socket) {
socket.on('send message', function(data) {
io.sockets.emit('new message', data);
});
});
我已经设置了MongoDB,并将其作为Windows上的服务运行。
答案 0 :(得分:6)
从1.2开始,推荐的连接方式是在文档中:
http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html
摘录:
var MongoClient = require('mongodb').MongoClient
, Server = require('mongodb').Server;
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
var db1 = mongoClient.db("mydb");
mongoClient.close();
});
您可能会发现连接单例对官方node.js驱动程序的当前状态很有用。下面是我使用的一些示例代码:
connection.js模块:
var MongoClient = require('mongodb').MongoClient;
var db_singleton = null;
var getConnection= function getConnection(callback)
{
if (db_singleton)
{
callback(null,db_singleton);
}
else
{
//placeholder: modify this-should come from a configuration source
var connURL = "mongodb://localhost:27017/test";
MongoClient.connect(connURL,function(err,db){
if(err)
log("Error creating new connection "+err);
else
{
db_singleton=db;
log("created new connection");
}
callback(err,db_singleton);
return;
});
}
}
module.exports = getConnection;
参考模块:
var getConnection = require('yourpath/connection.js')
function yourfunction()
{
getConnection(function(err,db)
{
//your callback code
}
.
.
.
}