2013-07-27 7 views
0

node.js와 MongoDB 데이터베이스 연결을 어떻게 설정합니까? 이미 MongoDB의를-설정 한 그것은 Windows에서 서비스로 실행 한node.js와 MongoDB 데이터베이스 연결 설정

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); 
    }); 
}); 

:

여기 내 app.js 파일입니다. 1.2

+1

을 시도를 아래는 내가 사용하는 몇 가지 예제 코드는? 설명서를 확인 했습니까? http://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html? – Brad

+0

해당 코드를 app.js 파일에 저장합니까? – methuselah

답변

6

는 연결을 수행하려면 권장되는 방법은 문서에 있습니다

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 

    } 
. 
. 
. 
} 
관련 문제