创建一个
Connection类来管理apps数据库连接。
MongoClient不提供单例连接池,因此您不想
MongoClient.connect()在应用程序中重复调用。包裹mongo客户端的单例类适用于我见过的大多数应用程序。
const MongoClient = require('mongodb').MongoClientclass Connection { static connectToMongo() { if ( this.db ) return Promise.resolve(this.db) return MongoClient.connect(this.url, this.options) .then(db => this.db = db) } // or in the new async world static async connectToMongo() { if (this.db) return this.db this.db = await MongoClient.connect(this.url, this.options) return this.db }}Connection.db = nullConnection.url = 'mongodb://127.0.0.1:27017/test_db'Connection.options = { bufferMaxEntries: 0, reconnectTries: 5000, useNewUrlParser: true, useUnifiedTopology: true,}module.exports = { Connection }
require('./Connection')该
Connection.connectToMongo()方法在您的任何地方都可用,
Connection.db如果属性已初始化,则该方法也将可用。
const router = require('express').Router()const { Connection } = require('../lib/Connection.js')// Better if this goes in your server setup somewhere and waited for.Connection.connectToMongo()router.get('/files', (req, res) => { Connection.db.collection('files').find({}) .then(files => res.json({ files: files }) .catch(err => res.json({ error: err })})module.exports = router
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)