이 글은 주로 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 버전 드라이버를 설치합니다. 몽고디비 드라이버 패키지는 현재 디렉터리의 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라는 데이터베이스에 연결합니다. app.js를 실행하는 명령줄
node app.js
4. 문서 삽입
app.js에 다음 코드를 추가하고 insertMany 메소드를 사용하여 문서 컬렉션에 3개의 문서를 추가하세요
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 문서를 쿼리하려면 쿼리 필터를 사용하세요. for '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. 문서 업데이트
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에 추가
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(); }); }); }); });
9. 색인 생성
인덱스는 애플리케이션 성능을 향상시킬 수 있습니다. 아래 코드는 'a' 속성에 색인을 추가합니다
var indexCollection = function(db,callback){ db.collection('documents').createIndex({ a:1 },null,function(err,results){ console.log(results); callback(); }); };Update app.js
MongoClient.connect(url,function(err,db){ assert.equal(null,err); console.log("Connection successfully to server"); insertDocuments(db,function(){ indexCollection(db,function(){ db.close(); }); }); });
위 내용은 Nodejs를 사용하여 mongodb 데이터베이스에 연결하는 방법에 대한 자세한 튜토리얼의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

JavaScript 프레임 워크의 힘은 개발 단순화, 사용자 경험 및 응용 프로그램 성능을 향상시키는 데 있습니다. 프레임 워크를 선택할 때 : 1. 프로젝트 규모와 복잡성, 2. 팀 경험, 3. 생태계 및 커뮤니티 지원.

서론 나는 당신이 이상하다는 것을 알고 있습니다. JavaScript, C 및 Browser는 정확히 무엇을해야합니까? 그들은 관련이없는 것처럼 보이지만 실제로는 현대 웹 개발에서 매우 중요한 역할을합니다. 오늘 우리는이 세 가지 사이의 밀접한 관계에 대해 논의 할 것입니다. 이 기사를 통해 브라우저에서 JavaScript가 어떻게 실행되는지, 브라우저 엔진의 C 역할 및 웹 페이지의 렌더링 및 상호 작용을 유도하기 위해 함께 작동하는 방법을 알게됩니다. 우리는 모두 JavaScript와 브라우저의 관계를 알고 있습니다. JavaScript는 프론트 엔드 개발의 핵심 언어입니다. 브라우저에서 직접 실행되므로 웹 페이지를 생생하고 흥미롭게 만듭니다. 왜 Javascr

Node.js는 크림 덕분에 효율적인 I/O에서 탁월합니다. 스트림은 메모리 오버로드를 피하고 큰 파일, 네트워크 작업 및 실시간 애플리케이션을위한 메모리 과부하를 피하기 위해 데이터를 점차적으로 처리합니다. 스트림을 TypeScript의 유형 안전과 결합하면 Powe가 생성됩니다

파이썬과 자바 스크립트 간의 성능과 효율성의 차이는 주로 다음과 같이 반영됩니다. 1) 해석 된 언어로서, 파이썬은 느리게 실행되지만 개발 효율이 높고 빠른 프로토 타입 개발에 적합합니다. 2) JavaScript는 브라우저의 단일 스레드로 제한되지만 멀티 스레딩 및 비동기 I/O는 Node.js의 성능을 향상시키는 데 사용될 수 있으며 실제 프로젝트에서는 이점이 있습니다.

JavaScript는 1995 년에 시작하여 Brandon Ike에 의해 만들어졌으며 언어를 C로 실현했습니다. 1.C Language는 JavaScript의 고성능 및 시스템 수준 프로그래밍 기능을 제공합니다. 2. JavaScript의 메모리 관리 및 성능 최적화는 C 언어에 의존합니다. 3. C 언어의 크로스 플랫폼 기능은 자바 스크립트가 다른 운영 체제에서 효율적으로 실행하는 데 도움이됩니다.

JavaScript는 브라우저 및 Node.js 환경에서 실행되며 JavaScript 엔진을 사용하여 코드를 구문 분석하고 실행합니다. 1) 구문 분석 단계에서 초록 구문 트리 (AST)를 생성합니다. 2) 컴파일 단계에서 AST를 바이트 코드 또는 기계 코드로 변환합니다. 3) 실행 단계에서 컴파일 된 코드를 실행하십시오.

Python 및 JavaScript의 미래 추세에는 다음이 포함됩니다. 1. Python은 과학 컴퓨팅 분야에서의 위치를 통합하고 AI, 2. JavaScript는 웹 기술의 개발을 촉진하고, 3. 교차 플랫폼 개발이 핫한 주제가되고 4. 성능 최적화가 중점을 둘 것입니다. 둘 다 해당 분야에서 응용 프로그램 시나리오를 계속 확장하고 성능이 더 많은 혁신을 일으킬 것입니다.

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!
