本文实例讲述了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;
内容版权声明:除非注明,否则皆为本站原创文章。
