kenu
36k
2014-09-18 20:16:20.0
1
9575

MongoDB와 Node.js 연결


MongoDB와 Node.js

MongoDB 제어를 Node.js 위에서

개요

  • node.js 기반의 DB 제어 방법
  • npm install mongodb 사용법

필요 조건

  • node.js
  • mongodb
  • 두 가지가 설치되었고, 환경변수 Path에 잡힌 상황

MongoDB 접속 코드

  • mongoTest.js
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    var MongoClient = require('mongodb').MongoClient;
     
     
    function callback(r) {
        console.log("r:" + r);
    }
     
    MongoClient.connect(url, callback);
  • node mongoTest.js
  • error 발생하는 경우
  • 1
    r:Error: failed to connect to [localhost:27017]
  • cmd 창에서 mongod 명령 실행
  • node mongoTest.js
  • npm install mongodb;
  • Q: 프로그램이 종료되지 않는 이유는?
  • db.close();
  • 1
    2
    3
    4
    5
    6
    7
    var MongoClient = require('mongodb').MongoClient;
     
    MongoClient.connect("mongodb://localhost/test",
        function (err, db) {
            console.log('err:' + err + '\ndb:' + db);
            db.close();
        });

MongoDB 데이터 입력

  • db.collection("test").insert({a: 1}, function(err, result) {});
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    var MongoClient = require('mongodb').MongoClient;
     
    MongoClient.connect("mongodb://localhost/test",
        function (err, db) {
            console.log('err:' + err + '\ndb:' + db.collection("test"));
            db.collection("test").insert({
                "oka": 1
            }, function (e) {
                console.log(e);
                db.close();
            });
            //  db.close();
        });

MongoDB 데이터 조회

  • db.collection("test").find().toArray(function(err, items){});
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    var MongoClient = require('mongodb').MongoClient;
     
    MongoClient.connect("mongodb://localhost/test",
        function (err, db) {
            console.log('err:' + err + '\ndb:' + db.collection("test"));
            db.collection("test").find().toArray(function (err, items) {
                console.log(items.length);
                for (var i in items) {
                    console.log(i + ":" + JSON.stringify(items[i]));
                }
                db.close();
            });
        });
  • db.collection("test").findOne({a: 1}, function(err, item){});
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    var MongoClient = require('mongodb').MongoClient;
     
    MongoClient.connect("mongodb://localhost/test",
        function (err, db) {
            // Find the saved document
            db.collection("test").findOne({
                "c": 1
            }, function (err, item) {
                console.log('world', item);
                db.close();
            });
        });

MongoDB 데이터 수정

  • db.collection("test").update({a: 1}, {b: 2}, function(err, result) {});
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    var MongoClient = require('mongodb').MongoClient;
     
    MongoClient.connect("mongodb://localhost/test",
        function (err, db) {
            console.log('err:' + err + '\ndb:' + db.collection("test"));
            db.collection("test").update({
                "oka": 1
            }, {
                "okb": 60
            }, function (e, num) {
                console.log(num);
                db.close();
            });
        });

MongoDB 데이터 삭제

  • db.collection("test").remove({a: 1}, function(err, result) {});
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    var Db = require('mongodb').Db,
        MongoClient = require('mongodb').MongoClient,
        Server = require('mongodb').Server,
        assert = require('assert');
     
    var db = new Db('test', new Server('localhost', 27017), {safe:true});
    // Establish connection to db
    db.open(function(err, db) {
     
      // Fetch a collection to insert document into
      db.collection("test", function(err, collection) {
     
        // Insert a bunch of documents
        collection.insert([{a:1}, {b:2}], {w:1}, function(err, result) {
          assert.equal(null, err);
     
          // Remove all the document
          collection.remove({a:1}, {w:1}, function(err, numberOfRemovedDocs) {
            assert.equal(null, err);
            assert.equal(1, numberOfRemovedDocs);
            db.close();
          });
        });
      })
    });

참고

Node.JS MongoDB Driver Manual
http://mongodb.github.io/node-mongodb-native/contents.html


0
0
  • 댓글 1

  • ksky216
    915
    2014-10-04 10:33:54.0
    배우고 싶고, 배워야할 것도 많은데, 고수들은 정말 바로바로 익히는 것 같아서 부러워요.
    0
  • 로그인을 하시면 댓글을 등록할 수 있습니다.