封装MongoDB库
首先要知道 async await 的作用
await后面接一个会return new promise的函数并执行它(意思就是promise 不可以在.then()了) ---等待执行
await只能放在async函数里
配置 config.js
let app = {
//定义数据库连接的地址 以及配置数据库
url :'mongodb://localhost:27017/',
dbName : 'LXW' // tjt数据库的名称
//nodejs连接数据库
}
module.exports = app
开始配置 DB.js
//单例模式
class DB{
let Config = require('./config.js')
console.log(Config) // { url: 'mongodb://localhost:27017/', dbName: 'LXW' }
//引入mongodb下面的MongoClient
const MongoDB = require('mongodb')
const MongoClient = require('mongodb').MongoClient;
const ObjectID = MongoDB.ObjectID;
//单例模式
class DB{
static getInstance(){
if(!DB.instance){ // 多次调用也只会 走一次或多次
console.log('第一次单例模式走的路线')
DB.instance = new DB() //因为没有DB.instance 所以就自己创造个实例对象
}else{
console.log('第二次..三次...四次都走的路线')
}
return DB.instance
}
constructor(ele){
console.log('连接数据库')
// this.dbClient = '' 个人感觉没必要
this.connect()
}
connect(){
//nodejs连接数据库
return new Promise((resolve,reject)=>{
// if(this.dbClient){
// resolve(this.dbClient)
// }else{
MongoClient.connect(Config.url,{useNewUrlParser: true,useUnifiedTopology: true},(err,client)=>{ // Config.url === LXW
//{useNewUrlParser: true, useUnifiedTopology: true}解决错误提示问题
if(err){
console.log('连接失败')
reject(err)
}else{
console.log('连接成功')
const db = client.db(Config.dbName); // 数据库db对象
resolve(db) // new promise解决异步问题 返回文件对象 // 整个connect() 基本就是db对象 ==>db
// this.dbClient = client.db(Config.dbName)
// resolve(this.dbClient )
// }
}
})
})
}
insert(collectionName,data){
return new Promise((resolve,reject)=>{
this.connect().then(db=>{
db.collection(collectionName).insertOne(data,(error,result)=>{
if(!error){
console.log('增加数据成功');
resolve(result)
}else{
console.log(error,'增加数据失败');
reject(err)
}
})
})
})
}
update(collectionName,old_data,new_data){
return new Promise((resolve,reject)=>{
this.connect().then(db=>{
db.collection(collectionName).updateOne(old_data,{$set:new_data})
})
})
}
delete(collectionName,condition){
return new Promise((resolve,reject)=>{
this.connect().then(db=>{
db.collection(collectionName).deleteOne(condition,function(error,result){
if(!error){
console.log('删除数据成功');
resolve(result)
}else{
console.log(error,'删除数据失败');
reject(error)
}
})
})
})
}
find(collectionName,condition){
return new Promise((resolve,reject)=>{
this.connect().then(db=>{
db.collection(collectionName).find(condition).toArray((err,arr)=>{ //需要转数组 不然显示不出来
if(!err){
resolve(arr)
}else{
reject(err)
}
})
})
})
}
getObjectID(id){ //固定写法 用于获取_id值下标
return new ObjectID(id)
}
}
module.exports = DB.getInstance()