因为业务需要,老板就让我搞了一回MongoDB。可真是懵逼树上懵逼果,懵逼树下你和我。本着务实求知的态度,研究了下也算是搞完了。开个香槟庆祝下。
👉 准备阶段
👉 安装依赖
这里采用的是npm仓库中的 mongodb
包。
npm install mongodb-D
👉 准备目录
在主目录下创建 db
文件夹。并同时在文件夹中创建 connect.js
, index.js
。
├─ db
│ ├─connect.js
│ └─index.js
├─ app.js
├─ ...
👉 连接数据库
👉 connect.js
const MongoClient = require("mongodb").MongoClient;
const config = {
dstHost: '127.0.0.1',
dstPort: 42351,
} // 数据库基本信息
var mydbname = "xxxx"; // 数据库名
function connect() {
return new Promise((resolve, reject) => {
// mongodb://127.0.0.1:12345/xxxxxx 连接格式
MongoClient.connect(`mongodb://${config.dstHost}:${config.dstPort}/${mydbname}`, {
useUnifiedTopology: true,
maxPoolSize: 10,
minPoolSize: 2,
poolSize: 10
}, function (dbConnectError, database) {
if (dbConnectError) {
console.error('连接失败,原因是:', dbConnectError);
reject(dbConnectError)
}
const dbo = database.db(mydbname);
console.log('连接成功!');
resolve(dbo) // 抛出连接实例
});
})
}
module.exports = connect
👉 index.js
var connect = require("./connect");
class DB {
constructor() {
this.dbo = '';
// 连接数据库,获取实例对象
connect().then(res => {
this.dbo = res
})
}
// 增
insert(collectionName, data) {
return new Promise((resolve, reject) => {
this.dbo.collection(collectionName).insertMany(data, function (error, result) {
if (error) {
reject(error);
throw error;
}
resolve(result);
});
});
}
// 查
read(collectionName, where, fields, projection, sort, limit, skip) {
return new Promise((resolve, reject) => {
this.dbo.collection(collectionName).find(where || {}, fields || {}).project(projection || {}).sort(sort || {}).limit(limit || 100).skip(skip || 0).toArray((error, result) => {
if (error) {
reject(error);
throw error;
}
resolve(result);
})
})
}
// 改
update(collectionName, where, data) {
return new Promise((resolve, reject) => {
this.dbo.collection(collectionName).updateMany(where, data, function (error, result) {
if (error) {
reject(error);
throw error;
}
resolve(result);
});
});
}
// 删
remove(collectionName, where) {
return new Promise((resolve, reject) => {
if (where) {
this.dbo.collection(collectionName).deleteMany(where, function (error, result) {
if (error) {
reject(error);
throw error;
}
resolve(result);
});
}
});
}
// 总
count(collectionName) {
return new Promise((resolve, reject) => {
try {
let result = this.dbo.collection(collectionName).countDocuments();
resolve(result);
} catch (e) {
reject(e);
}
})
}
// 自定义数据库语句
dbo(callback) {
return new Promise((resolve, reject) => {
try {
let result = null;
if (typeof callback === "function") {
result = callback(this.dbo);
}
resolve(result);
} catch (e) {
reject(e);
}
})
}
}
module.exports = DB
👉 使用
在某个逻辑中:
const DB = require("../db");
var db = new DB();
// 简单使用增加方法
async insert(req, res) {
var body = req.body
var result = await db.insert('user', [body]);
res.send({
code: 200,
msg: '成功',
data: result
})
}
简单方法,仅供参考。