npm install mongodb --save
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;
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);
}
});
});
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有