首頁 > web前端 > js教程 > 主體

使用Nodejs連接mongodb資料庫的實現

不言
發布: 2018-06-30 11:48:28
原創
1245 人瀏覽過

這篇文章主要介紹了使用Nodejs連接mongodb資料庫的實作程式碼,需要的朋友可以參考下

一個簡單的nodejs連接mongodb範例,來自mongodb官方範例

#1. 建立package.json

首先,建立我們的工程目錄connect-mongodb,並作為我們的目前目錄

mkdir connect-mongodb
cd connect-mongodb
登入後複製

輸入npm init指令建立package.json

npm init
登入後複製

然後,安裝mongodb的nodejs版本driver

npm install mongodb --save
登入後複製

mongodb驅動套件將會安裝到目前目錄下的node_modules中

#2 . 啟動MongoDB伺服器

安裝MongoDB並啟動MongoDB資料庫服務,可參考我之前的文章,或MongoDB官方文件

3. 連接MongoDB

建立一個app.js文件,並加入以下程式碼來連接伺服器位址為192.168.0.243,mongodb連接埠為27017上名稱為myNewDatabase的資料庫

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();
});
登入後複製

在命令列輸入以下命令執行app.js

#
node app.js
登入後複製

4.插入文件

在app.js中加入以下程式碼,使用insertMany方法新增3個文件到documents集合中

##

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 執行插入操作所使用的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函數查詢了所有'documents'集合中所有的文檔,將此函數新增至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. 使用篩選條件(query filter)查詢文件##查詢'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。

將updateDocument方法加入MongoClient.connect方法的回呼中

MongoClient.connect(url,function(err,db){
  assert.equal(null,err);
  console.log("Connection successfully to server");
  insertDocuments(db,function(){
    updateDocument(db,function(){
      db.close();
    });
  });
});
登入後複製

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();
  });
};
登入後複製

#更新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();
    });
  });
});
登入後複製

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

node-mysql中防止SQL注入的方法

NodeJs form-data格式傳輸檔案的方法

以上是使用Nodejs連接mongodb資料庫的實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!