在nodejs中使用MongoDB

MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。
MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。

安装

> npm install --save mongodb

使用

// 1. 导入
const mongodb = require('mongodb');
// 2. 实例化
let mongoClient = mongodb.MongoClient;
// 3. 连接
mongoClient.connect('mongodb://127.0.0.1:27017',(err,client)=>{
	// 4. 链接库和集合
	let db = client.db(dbName);
	let collection = db.collection(collectionName);
	// 5. 集合操作
	// *****
	// 6. 关闭库
	client.close()
});

promise封装

mongodb/index.js 连接数据库部分

const mongodb = require('mongodb')
let mongoClient = mongodb.MongoClient;

let mongodb_param = {
	host: '127.0.0.1',
    prot: 27017,
    database: 'demo_db'
}

/**
 * 连接数据库
 * dbName 数据库名称
 * collectionName 集合名称
 * url 协议://地址:端口 mongodb://127.0.0.1:27017
 */
let connect_mongoClient = ({dbName = mongodb_param.database, collectionName, url = `mongodb://${mongodb_param.host}:${mongodb_param.prot}`})=>{
	return new Promise((resolve, reject)=>{
    mongoClient.connect(url, { useUnifiedTopology: true }, (error, client)=>{
      if(!error){
        // 链接库
        let db = client.db(dbName)
        // 链接集合
        let collection = db.collection(collectionName)
        resolve({collection, client})
      } else {
        reject(error)
      }
    })
  })
}

module.exports = connect_mongoClient

mongodb/userDB.js 集合操作部分

const connect_mongoClient = require('./index')

let test_get = (callback)=>{
  connect_mongoClient({collectionName: 'tbl_user'})
    .then(({collection, client})=>{
      // 集合操作
      callback(null, '-成功-')
    })
    .catch((error)=>{
      callback(error, null)
    })
}

module.exports = {
  test_get
}

routes/userRouter.js 数据处理部分

const userDB = require('../mongodb/userDB')

let test_get = (res, req)=>{
  userDB.test_get((err, result)=>{
    if(err){
      console.log(err,'--')
      return
    }
     // console.log(result)
    req.send({data: '-成功-'})
   
  })
}

module.exports = {
  test_get
}

routes/index.js 接口部分

const express = require('express')
const router = express.Router()
const userRouter = require('./userRouter')

router.get('/test', userRouter.test_get)

module.exports = router

main.js 应用router

const express = require('express');
const app = express()
// 路由
const router = require('./routes/index')
app.use(router)
app.listen(3000, function() {
  console.log(`服务器3000端口已经开启`)
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值