nodejs操作mongodb的增刪改查功能實例

本文實例講述了nodejs操作MongoDB的增刪改查功能。分享給大家供大家參考,具體如下:

成都創(chuàng)新互聯(lián)于2013年創(chuàng)立,先為井陘等服務建站,井陘等地企業(yè),進行企業(yè)商務咨詢服務。為井陘企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務解決您的所有建站問題。

安裝相關模塊

如果使用這個的話,你需要先自己安裝一下他需要的模塊,在根目錄輸入

npm install mongodb --save

進行模塊安裝,安裝成功以后就可以進行以下的步驟。

文件的引入

以下是我書寫的相關代碼,放到你可以引用的相關目錄,本人放到了express的根目錄

function Mongo(options) {
  this.settings = {
    url: 'mongodb://localhost:27017/jk',
    MongoClient:require('mongodb').MongoClient,
    assert:require('assert')
  };
  for(let i in options){
    this.settings[i] = options[i];
  }
  this._run = function (fun) {
    let that = this;
    let settings = this.settings;
    this.settings.MongoClient.connect(this.settings.url, function (err, db) {
      settings.assert.equal(null, err);
      console.log("Connected correctly to server");
      fun(db, function () {
        db.close();
      });
    });
  };
  this.insert = function (collectionName, data, func) {
    //增加數(shù)據(jù)
    let insertDocuments = function (db, callback) {
      let collection = db.collection(collectionName);
      collection.insertMany([
        data
      ], function (err, result) {
        if (!err) {
          func(true);
        } else {
          func(false);
        }
        callback(result);
      });
    };
    this._run(insertDocuments);
  };
  this.update = function (collectionName, updateData, data, func) {
    //更新數(shù)據(jù)
    let updateDocument = function (db, callback) {
      let collection = db.collection(collectionName);
      collection.updateOne(updateData
        , {$set: data}, function (err, result) {
          if (!err) {
            func(true);
          } else {
            func(false);
          }
          callback(result);
        });
    };
    this._run(updateDocument);
  };
  this.delete = function (collectionName, data, func) {
    //刪除數(shù)據(jù)
    let deleteDocument = function (db, callback) {
      let collection = db.collection(collectionName);
      collection.deleteOne(data, function (err, result) {
        if (!err) {
          func(true);
        } else {
          func(false);
        }
        callback(result);
      });
    };
    this._run(deleteDocument);
  };
  this.find = function (collectionName, data, func) {
    //查找數(shù)據(jù)
    let findDocuments = function (db, callback) {
      // Get the documents collection
      let collection = db.collection(collectionName);
      // Find some documents
      collection.find(data).toArray(function (err, docs) {
        if (!err) {
          func(true,docs);
        }
        else {
          func(false, err);
        }
        callback(docs);
      });
    };
    this._run(findDocuments);
  };
}
module.exports = Mongo;

我存入到了一個名字叫server.js的文件名內(nèi)

使用

我們在需要使用頁面先將模塊引入,比如我在路由文件index.js里面引入:

const Server = require("../server.js");

然后需要實例化對象,如下:

let server = new Server();

如果需要配置相關信息,可以在實例化的時候傳入一個對象配置,可以配置數(shù)據(jù)庫的地址:

let server = new Server({url:"mongodb://localhost:27017/mydb"});

里面封裝了四個方法,添刪改查,分別是

添加方法

server.insert(數(shù)據(jù)表名,需要插入的數(shù)據(jù)(鍵值對的對象),回調(diào)函數(shù));

更新方法

server.update(數(shù)據(jù)表名,查詢的數(shù)據(jù)(對象),更新的數(shù)據(jù)(對象),回調(diào)函數(shù));

刪除方法

server.delete(數(shù)據(jù)表名,查詢的數(shù)據(jù)(對象),回調(diào)函數(shù));

查找方法

server.find(數(shù)據(jù)表名,查詢的數(shù)據(jù)(對象),回調(diào)函數(shù));

回調(diào)函數(shù)都會返回兩個值,第一個布爾類型,是否處理成功,第二個值,查找返回查找到的個數(shù),別的都返回處理成功的個數(shù)(現(xiàn)在一次只處理一條)

使用案例

比如我需要在一個路由里面查找數(shù)據(jù),我就需要這樣:

server.find("users",{username:"username"},function (bool,data) {
    if(bool){
      console.log("查詢到數(shù)據(jù)為"+data.length+"條");
    }
    else{
      console.log(data);
    }
  });
});

上面的代碼是查詢了users表里面username為username的字段的數(shù)據(jù),如果成功,后面data就會返回一個數(shù)組,如果出現(xiàn)錯誤,就直接返回data錯誤。

希望本文所述對大家nodejs程序設計有所幫助。

本文名稱:nodejs操作mongodb的增刪改查功能實例
文章URL:http://muchs.cn/article16/gpjjdg.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供App設計、網(wǎng)站收錄、網(wǎng)站制作定制開發(fā)、全網(wǎng)營銷推廣、網(wǎng)站建設

廣告

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

手機網(wǎng)站建設