~~~
/* db庫 */
const MongoClient = require('mongodb').MongoClient;
const {
dbUrl,
dbName
} = require('./config.js');
class Db {
constructor() {
/* dbclient定義數據庫是否存在 */
this.dbClient = '';
this.connect();
}
connect() {
return new Promise((resolve, reject) => {
/* dbClient數據庫不存在,則連接數據庫*/
if (!this.dbClient) {
MongoClient.connect(dbUrl, {
useNewUrlParser: true
}, (err, client) => {
if (err) {
reject(err)
} else {
let db = client.db(dbName)
this.dbClient = db;
resolve(this.dbClient)
};
})
} else {
/* 數據存在,則resolve */
resolve(this.dbClient)
}
})
}
find(collectionName, json) {
return new Promise((resolve, reject) => {
this.connect().then(db => {
var result = db.collection(collectionName).find(json);
result.toArray((err, data) => {
if (err) reject(err);
else resolve(data);
})
})
})
}
update() {
}
insert() {
}
}
var myDb = new Db();
setTimeout(() => {
console.time('start')
myDb.find('user', {}).then(data => {
console.log(data);
console.timeEnd('start')
})
}, 1000)
setTimeout(() => {
console.time('start1')
myDb.find('user', {}).then(data => {
console.log(data);
console.timeEnd('start1')
})
}, 3000)
~~~
- MongoDB
- 第一章開發環境配置
- 第二章 基礎操作
- 2-1 create-collection
- 2-2 collection-insert
- 2-3 find
- 2-4 query
- 2-5 sort排序
- 2-6 delete
- 2-7 drop-collection
- 2-8 update
- 2-9 limit
- 2-10 join
- 2-10-1 返回json給前臺
- 2-11 ObjectId
- 第三章 數據庫封裝
- 3-0 數據庫封裝思路
- 3-1 單例
- 3-2 增加數據的執行時間
- 3-1-1 查詢耗時
- 3-1-2 數據連接示例
- 3-3 簡單封裝
- 3-4 二次封裝
- 3-5 結合art-template使用
- 3-6 數據庫封裝終極
- Redis
- 第一章 開發環境配置