安裝相關(guān)模塊
如果使用這個(gè)的話(huà),你需要先自己安裝一下他需要的模塊,在根目錄輸入
npm install mongodb --save
進(jìn)行模塊安裝,安裝成功以后就可以進(jìn)行以下的步驟。
文件的引入
以下是我書(shū)寫(xiě)的相關(guān)代碼,放到你可以引用的相關(guān)目錄,本人放到了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;我存入到了一個(gè)名字叫server.js的文件名內(nèi)
使用
我們?cè)谛枰褂庙?yè)面先將模塊引入,比如我在路由文件index.js里面引入:
const Server = require("../server.js");然后需要實(shí)例化對(duì)象,如下:
let server = new Server();
如果需要配置相關(guān)信息,可以在實(shí)例化的時(shí)候傳入一個(gè)對(duì)象配置,可以配置數(shù)據(jù)庫(kù)的地址:
let server = new Server({url:"mongodb://localhost:27017/mydb"});
|
新聞熱點(diǎn)
疑難解答
圖片精選