~~~
//config.js
/* 配置文件 */
module.exports = {
dbUrl: "mongodb://localhost:27017/",
dbName: 'koa'
}
~~~
~~~
//db.js
/* db库 */
const MongoClient = require('mongodb').MongoClient;
const {
dbUrl,
dbName
} = require('./config.js');
class Db {
static getInstance() {
if (!Db.instance) {
Db.instance = new Db();
}
return Db.instance;
}
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() {
}
}
module.exports = Db.getInstance();
~~~
- 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
- 第一章 开发环境配置