【封装】nodejs操作mongo数据库

【封装】nodejs操作mongo数据库

本文将涉及以下知识点:

  1. nodejs操作数据库的基本代码
  2. 封装数据库链接操作
  3. 封装 增删改查 数据库的操作
  4. 封装根据商品id动态查询商品详情的操作
  5. 用Promise避免回调地狱

nodejs操作数据库的基本代码

安装+引入mongodb模块

npm i mongodb
const mongodb=require("mongodb")

实例化并连接数据库

let mongoCt = mongodb.MongoClient; //实例化
mongoCt.connect(
  "mongodb://127.0.0.1:27017",	//数据库协议+地址+端口
  { useUnifiedTopology: true }, //加上这个参数就不会警告了
  (err, client) => {}					 //err连接失败 client连接后的客户端
);

链接库和集合

let db = client.db("数据库名");
let clt = db.collection("集合名");

集合操作

clt.insertOne({要插入的数据},(err,res)=>{})	//err 插入失败 res 插入成功返回的对象
clt.insertMany(arr数据,(err,res)=>{})				//插入多条数据

res :res.result , n 结果 ok 状态,
ops: [ { name: ‘gg’, price: 23, _id: 5e6fa2f59dead35908f070eb } ], 内容,数组
insertedCount: 1, 插入的行数
insertedId: 5e6fa2f59dead35908f070eb 插入后生成的id

 clt.deleteOne({条件},(err,result)=>{})		
 clt.deleteMany({条件},(err,result)=>{})	
 clt.updateOne({ 条件 }, { $set: { 修改后对象} }, (err, res) => {});
 clt.updateMany({ 条件 }, { $set: { 修改后对象 } }, (err, res) => {});
//写法一
clt.find({条件},{skip:1,limit:1,projection:{key:1},(err,res)=>{
  res.toArray((err,data)=>{})
})	//res为返回的数据对象,data为该对象转换后的数据数组
//写法二
clt.find({}).toArray((err, data) => {});	//效果同上

关闭数据库

client.close()		

链接数据库封装

由于链接数据库时常用的操作,我们可以将其封装

为了避免回调地狱,我打算采用Promise

常规操作,将需要的模块下载好引入

const mongodb = require("mongodb");
let mongoCt = mongodb.MongoClient; //实例化

封装为open方法

let open = ({
  dbName = "shop", //数据库名字
  collectionName, //集合名字
  url = "mongodb://127.0.0.1:27017" //连接数据库地址
}) => {
  return new Promise((resolve, reject) => {
    mongodCt.connect(url, { useUnifiedTopology: true }, (err, client) => {
      if (err) {
        reject(err); //连接数据库失败执行该函数,携带错误为参数
      } else {
        let db = client.db(dbName);
        let collection = db.collection(collectionName);
        resolve({ collection, client }); //成功则执行,携带集合 后续可操作,携带客户端最后可以关闭
      }
    });
  });
};

查询数据

let findList = ({
  dbName = "shop",
  collectionName, //操作的集合名
  _page, //第几页
  _limit, //跳过第几个
  _sort, //按照哪个区域排序
  _sortRule = "asc", //按照什么规则排序
  q, //搜索的需要的关键字
  field = "name" //查询哪个区域的关键字
}) => {
  //生成检索条件,模糊查询
  //  let rule = q ? { [field]: new RegExp(q, "g") } : {};         //方法一
  let rule = q ? { [field]: eval(`/.*?${q}.*/`) } : {}; //方法二,推荐
  if (_sortRule == "asc") {
    _sortRule = 1;
  } else if (_sortRule == "des") {
    _sortRule = -1;
  }
  return new Promise((resolve, reject) => {
    open({ dbName, collectionName })
      .then(({ collection, client }) => {
        collection
          .find(rule, {
            skip: _page * _limit, //跳过多少数据
            limit: _limit, //每一页显示的数量
            sort: { [_sort]: _sortRule } //排序字段,当一个变量作为key使用的时候,需要采用[]的语法
          })
          .toArray((err, result) => {
            if (!err && result.length > 0) {
              //有数据则返回
              resolve({ err: 0, data: result });
            } else {
              reject({ err: 1, msg: "没有查到数据!" });
            }
            client.close(); //关闭链接
          });
      })
      .catch(err => {
        reject({ err: 1, msg: "数据库链接失败!" });
      });
  });
};

根据id查询 数据详情

由于mongodb的id默认是一个对象,所以我们需要导入一个模块,来将字符串转换为对象,用于查询

let objectId = mongodb.ObjectId;//把字符串转成ObjectId的对象类型

封装

let findDetail = ({ dbName = "shop", collectionName, _id = null }) => {
  return new Promise((resolve, reject) => {
    open({ dbName, collectionName })
      .then(({ collection, client }) => {
        if (_id.length === 24) {    //判断id是否符合标准
          collection.find({ _id: objectId(_id) }).toArray((err, data) => {
            if (!err && data.length > 0) {  //判断是否找到对应数据
              resolve({ err: 0, data: data[0] });
            } else {
              resolve({ err: 0, msg: "查询不到该数据" });
            }
            client.close(); //完成查询后记得关闭数据链接
          });
        } else {
          reject({ err: 1, msg: "id长度有误!" });
        }
      })
      .catch(err => {
        reject({ err: 1, msg: "数据库链接失败!" });
      });
  });
};

插入数据

let insert = ({ data, collectionName, dbName = "shop" }) => {
  return new Promise((resolve, reject) => {
    open({ dbName, collectionName })
      .then(({ collection, client }) => {
        collection.insert(data, (err, res) => {
          if (err) {
            reject({ err: 1, msg: "插入数据失败!" });
          } else {
            resolve({ err: 0, msg: "插入数据成功", res });
          }
          client.close();
        });
      })
      .catch(err => {
        reject({ err: 1, msg: "数据库链接失败!" });
      });
  });
};

删除数据

let del = ({ data, collectionName, dbName = "shop" }) => {
  return new Promise((resolve, reject) => {
    open({ dbName, collectionName })
      .then(({ collection, client }) => {
        if (data._id) {
          data._id = objectId(data._id); //将字符串转成objectid对象
        }
        collection.deleteMany(data, (err, res) => {
          if (err) {
            reject({ err: 1, msg: "删除数据失败" });
          } else {
            resolve({ err: 0, msg: "删除数据成功", res });
          }
          client.close();
        });
      })
      .catch(err => {
        reject({ err: 1, msg: "数据库链接失败!" });
      });
  });
};

修改数据

let update = ({ data, updateData, collectionName, dbName = "shop" }) => {
  return new Promise((resolve, reject) => {
    open({ dbName, collectionName })
      .then(({ collection, client }) => {
        if (data._id) {
          data._id = objectId(data._id); //将字符串转成objectid对象
        }
        collection.updateMany(data, { $set: updateData }, (err, res) => {
          if (err) {
            reject({ err: 1, msg: "修改数据失败" });
          } else {
            resolve({ err: 0, msg: "修改数据成功", res });
          }
          client.close();
        });
      })
      .catch(err => {
        reject({ err: 1, msg: "数据库链接失败!" });
      });
  });
};

导出以上模块

module.exports.open = open;
module.exports.findDetail = findDetail;
module.exports.findList = findList;
module.exports.insert = insert;
module.exports.del = del;
module.exports.update = update;

以上就是基本操作数据库的封装了,都是本人的学习记录,如有不对,欢迎指出~

全部代码如下

index.js

const mongodb = require("./mongo");
const express = require("express");
// const multer = require("multer");
const bodyParser = require("body-parser");

let app = express();
app.listen(3000, () => {
  console.log("监听3000端口成功");
});

//查询数据列表接口
app.get("/api/goods", async (req, res) => {
  if (req.query._id) {
    res.redirect(`/api/goods/${req.query._id}`);
    return;
  }
  let { _page, _limit, _sort, q, field, _sortRule } = req.query;
  _page = _page - 1;
  _limit = _limit - 0;
  _sort = _sort || "name";

  try {
    let result = await mongodb.findList({
      collectionName: "goods",
      _page,
      _limit,
      _sort,
      _sortRule,
      q,
      field
    });
    res.send(result); //返回异步函数执行成功的值
  } catch (err) {
    res.send(err); //捕获执行出错并返回
  }

  //   mongodb
  //     .findList({ collectionName: "goods", _page, _limit, _sort, q })
  //     .then(result => {
  //       res.send(result);
  //     })
  //     .catch(err => {
  //       res.send(err);
  //     });
});

//查询数据详情接口
app.get("/api/goods/:_id", (req, res) => {
  let { _id } = req.params;
  mongodb
    .findDetail({ _id, collectionName: "goods" })
    .then(result => {
      res.send(result);
    })
    .catch(err => {
      res.send(err);
    });
});
app.use(bodyParser());
//插入数据接口
app.post("/api/goods/insert", (req, res) => {
  let data = req.body;
  console.log(data);
  if (JSON.stringify(data) !== "{}") {
    mongodb
      .insert({ data, collectionName: "goods" })
      .then(result => {
        res.send(result);
      })
      .catch(err => {
        res.send(err);
      });
  } else {
    res.send({ err: 1, msg: "请填写要插入的数据内容!" });
  }
});

//删除数据
app.post("/api/goods/del", (req, res) => {
  let data = req.body;
  if (JSON.stringify(data) !== "{}") {
    mongodb
      .del({ data, collectionName: "goods" })
      .then(result => {
        res.send(result);
      })
      .catch(err => {
        res.send(err);
      });
  } else {
    res.send({ err: 1, msg: "请填写要删除的数据内容!" });
  }
});

//修改数据接口
app.post("/api/goods/update", (req, res) => {
  let { data, updateData } = req.body;
  console.log(req.body);
  //   data = JSON.parse(data);  //将获取的字符串转换为对象作为参数传过去
  //   updateData = JSON.parse(updateData);
  if (JSON.stringify(data) !== "{}" && JSON.stringify(updateData) !== "{}") {
    mongodb
      .update({ data, updateData, collectionName: "goods" })
      .then(result => {
        res.send(result);
      })
      .catch(err => {
        res.send(err);
      });
  } else {
    res.send({ err: 1, msg: "请填写要修改的数据内容 或 修改后的数据内容" });
  }
});

mongo.js

const mongodb = require("mongodb");
let mongoCt = mongodb.MongoClient; //实例化
let objectId = mongodb.ObjectId; //把字符串转成ObjectId的对象类型

let open = ({
  dbName = "shop", //数据库名字
  collectionName, //集合名字
  url = "mongodb://127.0.0.1:27017" //连接数据库地址
}) => {
  return new Promise((resolve, reject) => {
    mongoCt.connect(url, { useUnifiedTopology: true }, (err, client) => {
      if (err) {
        reject(err); //连接数据库失败执行该函数,携带错误为参数
      } else {
        let db = client.db(dbName);
        let collection = db.collection(collectionName);
        resolve({ collection, client }); //成功则执行,携带集合 后续可操作,携带客户端最后可以关闭
      }
    });
  });
};

//查询
let findList = ({
  dbName = "shop",
  collectionName, //操作的集合名
  _page, //第几页
  _limit, //跳过第几个
  _sort, //按照哪个区域排序
  _sortRule = "asc", //按照什么规则排序
  q, //搜索的需要的关键字
  field = "name" //查询哪个区域的关键字
}) => {
  //生成检索条件,模糊查询
  //   let rule = q ? { [field]: new RegExp(q, "g") } : {};         //方法一
  let rule = q ? { [field]: eval(`/.*?${q}.*/`) } : {}; //方法二,推荐
  if (_sortRule == "asc") {
    _sortRule = 1;
  } else if (_sortRule == "des") {
    _sortRule = -1;
  }
  return new Promise((resolve, reject) => {
    open({ dbName, collectionName })
      .then(({ collection, client }) => {
        collection
          .find(rule, {
            skip: _page * _limit, //跳过多少数据
            limit: _limit, //每一页显示的数量
            sort: { [_sort]: _sortRule } //排序字段,当一个变量作为key使用的时候,需要采用[]的语法
          })
          .toArray((err, result) => {
            if (!err && result.length > 0) {
              //有数据则返回
              resolve({ err: 0, data: result });
            } else {
              reject({ err: 1, msg: "没有查到数据!" });
            }
            client.close(); //关闭链接
          });
      })
      .catch(err => {
        reject({ err: 1, msg: "数据库链接失败!" });
      });
  });
};

//根据动态获取id数据的详情数据
let findDetail = ({ dbName = "shop", collectionName, _id = null }) => {
  return new Promise((resolve, reject) => {
    open({ dbName, collectionName })
      .then(({ collection, client }) => {
        if (_id.length === 24) {
          //判断id是否符合标准
          collection.find({ _id: objectId(_id) }).toArray((err, data) => {
            if (!err && data.length > 0) {
              //判断是否找到对应数据
              resolve({ err: 0, data: data[0] });
            } else {
              resolve({ err: 0, msg: "查询不到该数据" });
            }
            client.close(); //完成查询后记得关闭数据链接
          });
        } else {
          reject({ err: 1, msg: "id长度有误!" });
        }
      })
      .catch(err => {
        reject({ err: 1, msg: "数据库链接失败!" });
      });
  });
};

//增
let insert = ({ data, collectionName, dbName = "shop" }) => {
  return new Promise((resolve, reject) => {
    open({ dbName, collectionName })
      .then(({ collection, client }) => {
        collection.insert(data, (err, res) => {
          if (err) {
            reject({ err: 1, msg: "插入数据失败!" });
          } else {
            resolve({ err: 0, msg: "插入数据成功", res });
          }
          client.close();
        });
      })
      .catch(err => {
        reject({ err: 1, msg: "数据库链接失败!" });
      });
  });
};

//删
let del = ({ data, collectionName, dbName = "shop" }) => {
  return new Promise((resolve, reject) => {
    open({ dbName, collectionName })
      .then(({ collection, client }) => {
        if (data._id) {
          data._id = objectId(data._id); //将字符串转成objectid对象
        }
        collection.deleteMany(data, (err, res) => {
          if (err) {
            reject({ err: 1, msg: "删除数据失败" });
          } else {
            resolve({ err: 0, msg: "删除数据成功", res });
          }
          client.close();
        });
      })
      .catch(err => {
        reject({ err: 1, msg: "数据库链接失败!" });
      });
  });
};

//改
let update = ({ data, updateData, collectionName, dbName = "shop" }) => {
  return new Promise((resolve, reject) => {
    open({ dbName, collectionName })
      .then(({ collection, client }) => {
        if (data._id) {
          data._id = objectId(data._id); //将字符串转成objectid对象
        }
        console.log(data, updateData);

        collection.updateMany(data, { $set: updateData }, (err, res) => {
          if (err) {
            reject({ err: 1, msg: "修改数据失败" });
          } else {
            resolve({ err: 0, msg: "修改数据成功", res });
          }
          client.close();
        });
      })
      .catch(err => {
        reject({ err: 1, msg: "数据库链接失败!" });
      });
  });
};
module.exports.open = open;
module.exports.findDetail = findDetail;
module.exports.findList = findList;
module.exports.insert = insert;
module.exports.del = del;
module.exports.update = update;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值