使用Nodejs怎么連接mongodb數據庫-創新互聯

本篇文章給大家分享的是有關使用Nodejs怎么連接mongodb數據庫,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

創新互聯建站是一家專業提供站前企業網站建設,專注與成都網站建設、做網站H5響應式網站、小程序制作等業務。10年已為站前眾多企業、政府機構等服務。創新互聯專業網站設計公司優惠進行中。

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

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

更新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數據庫,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注創新互聯成都做網站行業資訊頻道。

另外有需要云服務器可以了解下創新互聯scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業上云的綜合解決方案,具有“安全穩定、簡單易用、服務可用性高、性價比高”等特點與優勢,專為企業上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。

網站題目:使用Nodejs怎么連接mongodb數據庫-創新互聯
標題網址:http://m.kartarina.com/article36/ccgesg.html

成都網站建設公司_創新互聯,為您提供搜索引擎優化網站建設響應式網站網站排名全網營銷推廣云服務器

廣告

聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯

手機網站建設
主站蜘蛛池模板: 内射人妻少妇无码一本一道| 无码人妻丰满熟妇精品区| 国产精品无码无在线观看| 亚洲一区AV无码少妇电影☆| 无码精品视频一区二区三区| 特级毛片内射www无码| 人妻少妇无码精品视频区| 久久精品岛国av一区二区无码| 亚洲日韩精品无码AV海量| 亚洲欧洲精品无码AV| 亚洲无码一区二区三区| 国产v亚洲v天堂无码网站| 人妻少妇精品无码专区动漫| 国产V亚洲V天堂无码久久久| 亚洲AⅤ无码一区二区三区在线| 亚洲AV永久无码精品| 亚洲一级特黄无码片| 亚洲精品无码少妇30P| 亚洲精品无码mv在线观看网站| 成人免费a级毛片无码网站入口 | 久久久久亚洲AV无码专区首JN| 国产免费AV片无码永久免费| AV大片在线无码永久免费| 国产精品多人p群无码| 亚洲日韩精品无码专区网站| 麻豆AV无码精品一区二区| 久久久亚洲精品无码| 日韩人妻无码一区二区三区久久99| 国产乱人伦中文无无码视频试看| 人妻无码一区二区三区免费| 中文字幕丰满伦子无码| 国产网红主播无码精品| 久久久久久久久免费看无码| 无码精油按摩潮喷在播放| 69久久精品无码一区二区| 精品亚洲成A人无码成A在线观看| 亚洲2022国产成人精品无码区| 亚洲动漫精品无码av天堂| 国产∨亚洲V天堂无码久久久| 亚洲中文字幕无码久久2017 | 国精品无码一区二区三区在线 |