先引入mongodb模块
const MongoClient = require('mongodb').MongoClient;
数据库
const DB_CONN_STR = 'mongodb://192.168.1.243:27017/test';
哪张表
const tableName = 'demo';
let db = null;
连接数据库的封装
async function getInstance() {
if (db == null) {
try {
db = await MongoClient.connect(DB_CONN_STR);
return db;
} catch (e) {
console.log(e);
}
} else {
return db;
}
}
连接数据库并返回相应对象
async function connectDb(){
const db = await getInstance();
const collection = db.collection(tableName);
return { db, collection };
}
params皆为传入参数
增加,insert方法为插入数据
async function callAddData(params){
const dbObj = await connectDb();
return await dbObj.collection.insert(params);
}
查询,find方法为查询数据
async function callSearchData(params){
const dbObj = await connectDb();
return await dbObj.collection.find(params).toArray();
}
查询单条数据库
async function callDetailData(params){
const dbObj = await connectDb();
const result = await dbObj.collection.find(params).toArray();
return result[0];
}
修改,update方法为修改,第一个参数为要寻找的数据,一般传入id,第二个参数为更新的数据
async function callUpdateData(params){
const dbObj = await connectDb();
const whereStr = {id: params.id};
const updateStr = {$set: params};
return await dbObj.collection.update(whereStr, updateStr);
}
删除,remove方法为删除数据
async function callDeleteData(params){
const dbObj = await connectDb();
const result = await dbObj.collection.remove(params);
return result;
}
网友评论