本文我们要封装一个数据库连接方法,最开始这个方法是写在posts.js里的,现在要把这个方法写到dbconfig.js里,以便其它接口文件也可以进行调用。
原始的posts.js代码如下:
const express = require('express')
const mongodb = require('mongodb')
const router = express.Router()
// 连接数据库并指定要操作的collection
async function loadPostsCollection(){
const client = await mongodb.MongoClient.connect
('mongodb://localhost:27017', {
useUnifiedTopology: true
})
return client.db('dbname').collection('posts')
}
// 查询数据并发送给前端
router.get('/', async (req, res) => {
const posts = await loadPostsCollection()
res.send(await posts.find({}).toArray())
})
module.exports = router
之后我们要把loadPostsCollection()这个方法封装到../utils/dbconfig里,把这部分代码复制到文件里,并改成以下这样:
const mongodb = require('mongodb')
// 将'users'改成collectionName作为参数传进来
module.exports = async (collectionName) => {
const client = await mongodb.MongoClient.connect
('mongodb://localhost:27017', {
useUnifiedTopology: true
})
return client.db('dbname').collection(collectionName)
}
回到调用该方法的文件,将dbconfig作为一个方法引入进来。
const loadCollection = require('../utils/dbconfig')
在使用的时候,首先定义好collectionName,之后可直接使用封装的方法。
// 查询数据
const collectionName = 'posts'
router.get('/', async (req, res) => {
const posts = await loadCollection(collectionName)
res.send(await posts.find({}).toArray())
})
修改后的posts.js如下:
const express = require('express')
const loadCollection = require('../utils/dbconfig')
const router = express.Router()
const collectionName = 'posts'
// 查询数据
router.get('/', async (req, res) => {
const posts = await loadCollection(collectionName)
res.send(await posts.find({}).toArray())
})
module.exports = router
完!
这个是其中一种封装方法,其他的方法查看这里。
最新回复