Nodejs를 사용하여 mongodb 데이터베이스에 연결 구현

不言
풀어 주다: 2018-06-30 11:48:28
원래의
1275명이 탐색했습니다.

이 글은 주로 Nodejs를 사용해 mongodb 데이터베이스에 연결하는 구현 코드를 소개합니다. 필요한 친구들은 참고하시면 됩니다

mongodb 공식 예제에 나오는 nodejs의 간단한 예제

1. .JSON

먼저 프로젝트 디렉토리 Connect-MongoDB를 만들고 현재 디렉토리

mkdir connect-mongodb
cd connect-mongodb
로그인 후 복사

npm init命令创建package.json

npm init
로그인 후 복사

로 입력 한 다음 Mongodb

npm install mongodb --save
로그인 후 복사
의 Nodejs 버전 드라이버를 설치하십시오.

mon godb 드라이버 패키지는 현재 디렉터리의 node_modules에 설치됩니다.

2. MongoDB 서버를 시작합니다.

MongoDB를 설치하고 MongoDB 데이터베이스 서비스를 시작합니다. 공식 MongoDB 문서

3. MongoDB 연결

app.js 파일을 생성하고 다음 코드를 추가하여 서버 주소 192.168.0.243 및 mongodb 포트 27017

var MongoClient = require('mongodb').MongoClient,
  assert = require('assert');
// Connection URL
var url = 'mongodb://192.168.0.243:27017/myNewDatabase';
MongoClient.connect(url,function(err,db){
  assert.equal(null,err);
  console.log("Connection successfully to server");
  db.close();
});
로그인 후 복사

에 있는 myNewDatabase라는 데이터베이스에 연결합니다.

앱을 실행하려면 명령줄에 다음 명령을 입력하세요. .js

node app.js
로그인 후 복사

4. 문서 삽입

app.js에 다음 코드를 추가하고, insertMany 메소드를 사용하여 3개의 문서를 document collection

var insertDocuments = function(db, callback){
  // get ths documents collection
  var collection = db.collection('documents');
  // insert some documents
  collection.insertMany([
    {a:1},{a:2},{a:3}
  ],function(err,result){
    assert.equal(err,null);
    assert.equal(3,result.result.n);
    assert.equal(3,result.ops.length);
    console.log("Inserted 3 documents into the collection");
    callback(result);
  });
};
로그인 후 복사

insert 명령은 다음 속성을 포함하는 객체를 반환합니다.

  • result MongoDB가 반환한 문서 결과

  • ops _id 필드가 추가된 문서

  • connection 연결 삽입 작업을 수행하는 데 사용됨

app.js에서 다음을 업데이트하세요. 코드는 insertDocuments 메서드를 호출합니다

var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected successfully to server");
 insertDocuments(db, function() {
  db.close();
 });
});
로그인 후 복사

node app.js를 사용하여 명령줄에서 실행

5.

findDocuments 함수 추가

var findDocuments = function(db,callback){
  // get the documents collection
  var collection = db.collection('documents');
  // find some documents
  collection.find({}).toArray(function(err,docs){
    assert.equal(err,null);
    console.log("Found the following records");
    console.log(docs);
    callback(docs);
  });
};
로그인 후 복사

findDocuments 이 함수는 모든 '문서' 컬렉션을 쿼리하고 이 함수를 MongoClient.connect의 콜백 함수에 추가합니다

var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected correctly to server");
 insertDocuments(db, function() {
  findDocuments(db, function() {
   db.close();
  });
 });
});
로그인 후 복사

6. document

'a' 쿼리: 3 문서

var findDocuments = function(db, callback) {
 // Get the documents collection
 var collection = db.collection('documents');
 // Find some documents
 collection.find({'a': 3}).toArray(function(err, docs) {
  assert.equal(err, null);
  console.log("Found the following records");
  console.log(docs);
  callback(docs);
 });   
}
로그인 후 복사

7. Update the document

var updateDocument = function(db,callback){
  // get the documents collection
  var collection = db.collection('documents');
  // update document where a is 2, set b equal to 1
  collection.updateOne({a:2},{
    $set:{b:1}
  },function(err,result){
    assert.equal(err,null);
    assert.equal(1,result.result.n);
    console.log("updated the document with the field a equal to 2");
    callback(result);
  });
};
로그인 후 복사

updateDocument 메소드는 조건 a가 2인 첫 번째 문서를 업데이트합니다. , b 속성을 추가하고 이를 1 로 설정합니다.

MongoClient.connect 메서드의 콜백에 updateDocument 메서드를 추가하세요

MongoClient.connect(url,function(err,db){
  assert.equal(null,err);
  console.log("Connection successfully to server");
  insertDocuments(db,function(){
    updateDocument(db,function(){
      db.close();
    });
  });
});
로그인 후 복사

8. 문서를 삭제하세요

var removeDocument = function(db,callback){
  // get the documents collection
  var collection = db.collection('documents');
  // remove some documents
  collection.deleteOne({a:3},function(err,result){
    assert.equal(err,null);
    assert.equal(1,result.result.n);
    console.log("removed the document with the field a equal to 3");
    callback(result);
  });
};
로그인 후 복사

app.js

에 추가하세요. 리

9. 인덱스 생성

인덱스는 애플리케이션 성능을 향상시킬 수 있습니다. 아래 코드는 'a' 속성에 색인을 추가합니다

var MongoClient = require('mongodb').MongoClient
 , assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
 assert.equal(null, err);
 console.log("Connected successfully to server");
 insertDocuments(db, function() {
  updateDocument(db, function() {
   removeDocument(db, function() {
    db.close();
   });
  });
 });
});
로그인 후 복사

Update app.js

var indexCollection = function(db,callback){
  db.collection('documents').createIndex({
    a:1
  },null,function(err,results){
    console.log(results);
    callback();
  });
};
로그인 후 복사

위 내용은 모든 사람의 학습에 도움이 되기를 바랍니다. 더 많은 관련 콘텐츠를 원하시면 문의해주세요. PHP 중국어 웹사이트를 팔로우하세요!

관련 권장 사항:

node-mysql에서 SQL 주입을 방지하는 방법

NodeJs 양식 데이터 형식으로 파일을 전송하는 방법

위 내용은 Nodejs를 사용하여 mongodb 데이터베이스에 연결 구현의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!