一、安装mongodb
npm i mongodb --save-dev
二、创建工具类 mongodbHelper.js
const dbInfo = {
host: "127.0.0.1",
port: "27017",
dbName: "xxx"
};
const {
dbInfo
} = require("../../config/server.config.js");
const MongoClient = require('mongodb').MongoClient;
class mongodbHelper {
/***连接数据库***/
connection() {
return new Promise(function (resolve, reject) {
var url = `mongodb://${dbInfo.host}:${dbInfo.port}/${dbInfo.dbName}`;
MongoClient.connect(url, {
useUnifiedTopology: true,
useNewUrlParser: true
}, function (err, db) {
if (err) {
reject(err);
}
console.log("连接成功!", url);
resolve(db);
});
})
}
/**关闭数据库连接
*db:数据库实例
***/
close(db) {
db.close;
}
/**创建集合
* db:数据库实例
* collectionName:集合名称
* **/
createCollection(collectionName) {
return new Promise((resolve, reject) => {
this.connection().then(db => {
var dbase = db.db(dbInfo.dbName);
dbase.createCollection(collectionName, function (err, res) {
db.close();
if (err) {
reject(err);
}
resolve(1);
});
}).catch(err => {
reject(err);
})
})
}
/**添加一条数据
* collectionName:集合名称
* data:数据,Object
* */
insertOne(collectionName, data) {
return new Promise((resolve, reject) => {
this.connection().then(db => {
var dbase = db.db(dbInfo.dbName);
dbase.collection(collectionName).insertOne(data, function (err, res) {
db.close();
if (err) {
reject(err);
}
resolve(1);
});
}).catch(err => {
reject(err);
})
})
}
/**添加多条数据
*collectionName:数据集合
*datas:数据,Array
****/
insertMany(collectionName, datas) {
return new Promise((resolve, reject) => {
this.connection().then(db => {
var dbase = db.db(dbInfo.dbName);
dbase.collection(collectionName).insertMany(datas, function (err, res) {
db.close();
if (err) {
reject(err);
}
resolve(datas.length);
});
}).catch(err => {
reject(err);
})
})
}
/**查询
*collectionName:集合名称
*search:查询条件
* **/
find(collectionName, search) {
return new Promise((resolve, reject) => {
this.connection().then(db => {
var dbase = db.db(dbInfo.dbName);
dbase.collection(collectionName).find(search).toArray(function (err, result) {
db.close();
if (err) {
reject(err);
}
resolve(result);
});
}).catch(err => {
reject(err);
})
})
}
/**修改数据
* collectionName:表名
* query:查询条件,Object
* update:更新的数据,Object
* option={upsert, multi}
*/
update(collectionName, query, update) {
return new Promise((resolve, reject) => {
this.connection().then(db => {
var dbase = db.db(dbInfo.dbName);
dbase.collection(collectionName).updateOne(query, {
$set: update
}, function (err, res) {
db.close();
if (err) {
reject(err);
}
resolve(1);
});
}).catch(err => {
reject(err);
})
})
}
/**修改数据
* collectionName:表名
* query:查询条件,Object
* update:更新的数据,Object
* option={upsert, multi}
*/
delete(collectionName, obj) {
return new Promise((resolve, reject) => {
this.connection().then(db => {
var dbase = db.db(dbInfo.dbName);
dbase.collection(collectionName).remove(obj, function (err, res) {
db.close();
if (err) {
reject(err);
}
resolve(1);
});
}).catch(err => {
reject(err);
})
});
}
}
module.exports = mongodbHelper
三、使用,创建类 userModel.js
const dbHelper = require("./mongodbHelper .js")();
class userModel {
constructor() {
this.tbName = "tb_user";
this.email = "";
this.userName = "";
this.loginName = "";
this.email = "";
this.phone = "";
this.time = "";
}
async add(user) {
if (!user) {
user = {
userName: this.userName,
loginName: this.loginName,
email: this.email,
phone: this.phone,
}
}
user.time = new Date();
let result = await dbHelper.insertOne(this.tbName, user);
return result;
}
async getOne(searchObj) {
let list = await this.getList(searchObj);
if (list && list.length) {
return list[0];
}
return null;
}
async getList(searchObj) {
let list = await dbHelper.find(this.tbName, searchObj);
return list;
}
}
module.exports = userModel;
五,对外接口(userInfo.js)
const router = require("koa-router")();
const UserModel = require("../../model/userModel.js");
router.post('/addUser', async (ctx) => {
let result = new ctx.Result();//新加的一个结果类,返回结果同一个格式app.context.Result = Result;
try {
let user = new UserModel();
let userInfo = ctx.request.body.userInfo;
let ret = await user.add(userInfo);
ctx.body = result.setDatas(ret);
} catch (e) {
ctx.body = result.setError(e.message);
}
})
router.post('/getUser', async (ctx) => {
let result = new ctx.Result();
try {
let user = new UserModel();
let userInfo = ctx.request.body.userInfo;
let ret = await user.getList(userInfo);
ctx.body = result.setDatas(ret);
} catch (e) {
ctx.body = result.setError(e.message);
}
})
module.exports = router;
六、mongodb环境安装
下载地址:
https://www.mongodb.com/download-center/community
启动命令:mongod --dbpath "D:\数据文件夹路径"
出现以下信息就可以正常读写数据了