開始之前
按照 MongoDB Node.JS Driver 我們每次使用JS對數(shù)據(jù)進(jìn)行操作都需要先建立連接兴喂,如果我們每次操作都要重新建立一次連接必然會很消耗性能(建立連接時長大約一秒鐘)改抡,為了減少性能的損耗同時使我們用 nodejs 操作 MongoDB 更加靈活方便唉锌,按照官方文檔封裝一個了 DB 模塊。
原生 JS 中靜態(tài)方法、類、繼承
function Persion(name,age){
/* 構(gòu)造函數(shù)里面的方法和屬性 */
this.name = name;
this.age = age;
this.printInfo = function(){
console.log(`${this.name}---${this.age}`)
}
}
/* 原型鏈上的屬性和方法和可以被多個實例共享 */
Person.prototype.sex = 'man';
Persion.prototype.work = function(){
console.log(`${this.name}--${this.age}--${this.work}`)
}
/* 靜態(tài)方法 我們直接在方法名上添加就可以使用方法方法名調(diào)用 */
Person.staticMethod = function(){
console.log('這是一個靜態(tài)方法')
}
/* 實例方法是通過實例化來調(diào)用原献,靜態(tài)方法是通過類名調(diào)用 */
let p = new Person('zhangsan', '18');
p.printInfo(); // zhangsan--18
p.work(); // zhangsan--18--man
Person.staticMethod(); // 這是一個靜態(tài)方法
ES5中的繼承
/*
* ES5中的繼承可用使用原型鏈繼承和對象冒充的方式來實行
* 對象冒充繼承:沒法繼承原型鏈上的屬性和方法
* 原型鏈繼承:可以繼承構(gòu)造函數(shù)以及原型鏈上面的屬性和方法,但實例化子類時沒法傳參數(shù)給父類
* 將這兩者結(jié)合起來埂淮,更多的方法請查看 《JavaScript高級程序設(shè)計》 第六章
*/
function Person(name,age){
this.name = name;
this.age = age;
this.printInfo = function(){
console.log(`${this.name}--${this.age}`);
}
}
Person.prototype.work = function(){
console.log('work')
}
function Employee(name,age){
Person.call(this,name,age) // 對象冒充實現(xiàn)繼承
}
Employee.prototype = new Person();
let emp = new Employee('zhangsan', 18);
emp.printInfo(); // zhangsan--18
emp.work(); // work
ES6 中類姑隅、靜態(tài)方法、繼承
class Person{
constructor(name,age){
this._name = name;
this._age = age;
}
getName(){
console.log(this._name);
}
setName(name){
this._name = name;
}
}
/* ES6 中的繼承 使用 extends 關(guān)鍵字 靜態(tài)方法使用 static 關(guān)鍵字*/
class Employee extends Person{
constructor(name,age,sex){
super(name,age);
this._sex = sex;
}
static staticMethod(){
console.log('這是一個靜態(tài)方法')倔撞;
}
printInfo(){
console.log(`${this._name}--${this._age}--${this._sex}`);
}
}
let emp = new Employee('zhangsan', '18', 'man');
emp.getName(); // zhangsan
emp.printInfo(); // zhangsan--18--man
Employee.staticMethod(); //這是一個靜態(tài)方法
ES6單例模式
class Db {
static getInstance(){ /*單例*/
if(!Db.instance){
Db.instance=new Db();
}
return Db.instance;
}
constructor(){
console.log('實例化會觸發(fā)構(gòu)造函數(shù)');
this.connect();
}
connect(){
console.log('連接數(shù)據(jù)庫');
}
find(){
console.log('查詢數(shù)據(jù)庫');
}
}
var myDb=Db.getInstance(); // 實例化會觸發(fā)構(gòu)造函數(shù) 連接數(shù)據(jù)庫
var myDb2=Db.getInstance();
var myDb3=Db.getInstance();
var myDb4=Db.getInstance();
myDb3.find(); //查詢數(shù)據(jù)庫
myDb4.find(); //查詢數(shù)據(jù)庫
NodeJS 對 MongoDB的封裝
const MongoDB = require('mongodb');
const MongoClient = MongoDB.MongoClient;
const ObjectID = MongoDB.ObjectID;
const CONFIG = {
dbUrl: 'mongodb://127.0.0.1:27017/',
dbName: 'test'
};
class DB{
static getInstance(){
if(!DB.instance){
DB.instance = new DB();
}
return DB.instance;
}
constructor() {
this.dbClient = '';
this.connect();
}
connect(){
let self = this;
return new Promise(((resolve, reject) => {
if(!self.dbClient){
MongoClient.connect(CONFIG.dbUrl,{'useNewUrlParser': true, 'useUnifiedTopology':true},(err,client)=>{
if(err){
reject(err);
}else{
self.dbClient = client.db(CONFIG.dbName);
resolve(self.dbClient);
}
})
}else{
resolve(self.dbClient);
}
}))
}
insertDocuments(collectionName,jsonArr){
if(!collectionName || !jsonArr || !(jsonArr instanceof Array)) throw '參數(shù)錯誤';
return new Promise((resolve, reject) => {
this.connect().then(db=>{
const collect = db.collection(collectionName);
collect.insertMany(jsonArr,(err,result)=>{
if(!err){
resolve(result);
}else{
reject(err);
}
})
})
})
}
findDocuments(collectionName,json){
if(!collectionName || !json ) throw '參數(shù)錯誤';
return new Promise((resolve, reject) => {
this.connect().then(db=>{
let result = db.collection(collectionName).find(json);
result.toArray((err,data)=>{
if(!err){
resolve(data);
}else{
reject(err);
}
})
})
})
}
removeDocument(collectionName,json){
if(!collectionName || !json ) throw '參數(shù)錯誤';
return new Promise(((resolve, reject) => {
this.connect().then(db=>{
const collection = db.collection(collectionName);
collection.deleteOne(json,(err,result)=>{
if(!err){
resolve(result);
}else{
reject(err);
}
})
})
}))
}
updateDocument(collectionName,filter,json){
if(!collectionName || !filter || !json) throw '參數(shù)錯誤';
return new Promise((resolve, reject) => {
this.connect().then(db=>{
const collection = db.collection(collectionName);
collection.updateOne(filter,{$set:json},(err,result)=>{
if(!err){
resolve(result)
}else{
reject(err)
}
})
})
})
}
getObjectId(id){ /*mongodb里面查詢 _id 把字符串轉(zhuǎn)換成對象*/
return new ObjectID(id);
}
}
module.exports = DB.getInstance();