本文實例講述了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錯誤。
希望本文所述對大家nodejs程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。