封装后端查询数据的模块(用于购物车实现)

  • 封装模块
const mongodb = require("mongodb")

//实例化
const mongodCt = mongodb.MongoClient

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

let open = ({ dbName = "student", 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 = ({
    collectionName,//集合名
    dbName = "student",//数据库名
    _page, _limit, _sort  //第几页 数量 排序
}) => {
    return new Promise((resolve, reject) => {
        //解构赋值
        open({ dbName, collectionName })
            .then(({ collection, client }) => {
                collection.find({}, { //查询数据库
                    skip: _page * _limit,  //查询开始位置
                    limit: _limit, //查询数量 
                    sort: { [_sort]: 1 } //升序 
                }).toArray((err, result) => {
                    if (!err && result.length > 0) { //当查到数据是并且 数量大于零 
                        resolve({
                            err: 0,
                            data: result
                        })
                    } else {
                        resolve({ err: 1, msg: "查无数据" })

                    }
                    //关闭数据库
                    client.close()
                })
            }).catch(err => { 
                reject({ err: 1, msg: "数据库链接失败" })
            })
    })

}

//实现步骤
//通过promise先封装open函数  用来连接数据库  
//在创建一个 findList函数 传递相关参数 
//在函数中 返回promise  
// 调用open函数 连接数据库 
//查询根据传递的参数查询数据 






//根据动态id查询详情数据
let findDetail = ({
    dbName="student",//默认查询的数据库名字
    collectionName,//集合名字
    _id=null  //外面传入的_id 
})=>{
    return new Promise((resolve,reject)=>{
        //链库操作
        open({dbName,collectionName})
            .then(({collection,client})=>{
                //查询
                if(_id.length === 24){
                    collection.find({_id:ObjectId(_id)}).toArray((err,data)=>{   
                        //返回结果 
                        if(!err && data.length>0){
                            resolve({err:0,data:data[0]}) //因为result是一个数组,里面仅仅包含一条数据
                        }else{
                            resolve({err:1,msg:"查询不到数据...."})
                        }
                    })
                }else{
                    reject({err:1,msg:"id长度有误..."})
                }
            })
            .catch(err=>reject({err:1,msg:"链接数据库失败...."}))
    })
}




//导出模块
exports.open = open
exports.findList = findList
exports.findDetail = findDetail

  • 引入模块 获取数据库数据
const express = require("express")

const app = express();

app.listen(3000, () => {
    console.log("3000端口正在监听")
})

const mongodb = require("./mongodb")


//查询列表
app.get("/api/user", (req, res) => {
    //获取前端传递过来的数据
    let { _page, _limit, _sort } = req.query;
    _page = _page - 1;
    _limit = _limit - 0;//传递过来的数据是字符转 隐式转换
    _sort = _sort || 'age'


    mongodb.findList({
        collectionName: 'user',
        _page, _limit, _sort
    }).then(result => {
        res.send(result)
    }).catch(err => {
        res.send(err)
    })
})


//根据id查询单个数据详情
app.get("/api/user/:_id", (req, res,next) => {
    let { _id } = req.params; //获取动态目录
    mongodb.findDetail({
        collectionName: "user",
        _id
    }).then(result => res.send(result))
        .catch(err => res.send(err))
})



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值