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

完全掌握nodejs操作mongodb的增刪改查功能

小云云
發布: 2017-12-23 09:11:47
原創
1824 人瀏覽過

本文主要介紹了nodejs操作mongodb的增刪改查功能,簡單分析了mongodb模組的安裝並結合實例形式分析了nodejs操作mongodb資料庫進行增刪改查的相關實作技巧,需要的朋友可以參考下,希望能幫助大家。

安裝相關模組

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


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) {
    //增加数据
    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) {
    //更新数据
    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) {
    //删除数据
    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) {
    //查找数据
    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的檔案名稱內

使用

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


const Server = require("../server.js");
登入後複製

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


let server = new Server();
登入後複製

如果需要配置相關訊息,可以在實例化的時候傳入一個物件配置,可以配置資料庫的位址:


let server = new Server({url:"mongodb://localhost:27017/mydb"});
登入後複製

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

#新增方法


##

server.insert(数据表名,需要插入的数据(键值对的对象),回调函数);
登入後複製

更新方法


server.update(数据表名,查询的数据(对象),更新的数据(对象),回调函数);
登入後複製

#刪除方法


server.delete(数据表名,查询的数据(对象),回调函数);
登入後複製

查找方法


server.find(数据表名,查询的数据(对象),回调函数);
登入後複製

回呼函數都會傳回兩個值,第一個布林類型,是否處理成功,第二個值,查找返回查找到的個數,別的都回傳處理成功的個數(現在一次只處理一條)

#使用案例

例如我需要在一個路由裡面查找數據,我就需要這樣:


server.find("users",{username:"username"},function (bool,data) {
    if(bool){
      console.log("查询到数据为"+data.length+"条");
    }
    else{
      console.log(data);
    }
  });
});
登入後複製
上面的程式碼是查詢了users表裡面username為username的欄位的數據,如果成功,後面data就會回傳一個數組,如果出現錯誤,就直接回傳data錯誤。

相關推薦:

php資料庫增刪改查方式

#AngularJs增刪改查的方法

#NodeJS中MySql的增刪改查基礎寫法的實作

以上是完全掌握nodejs操作mongodb的增刪改查功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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