@ fastify/ mongodb
速成 MongoDB 连接插件; 您可以用此程序在服务器的每个部分共享相同的 MongoDB 连接池 .
在头罩下,官员 蒙戈DB 使用驱动程序,
您通过选项 register 将交给蒙戈客户.
这个 mongodb 驱动程序为v7.x.x.
如果您自己不提供客户端( 见下文) , URL 选项为 所需经费。 。 。 .
安装
npm i @fastify/mongodb
使用量
添加到您的项目中 register 你们就完了!
const fastify = require('fastify')()
fastify.register(require('@fastify/mongodb'), {
// force to close the mongodb connection when app stopped
// the default value is false
forceClose: true,
url: 'mongodb://mongo/mydb'
})
fastify.get('/user/:id', async function (req, reply) {
// Or this.mongo.client.db('mydb').collection('users')
const users = this.mongo.db.collection('users')
// if the id is an ObjectId format, you need to create a new ObjectId
const id = new this.mongo.ObjectId(req.params.id)
try {
const user = await users.findOne({ id })
return user
} catch (err) {
return err
}
})
fastify.listen({ port: 3000 }, err => {
if (err) throw err
})
您也可提供预配置实例 mongodb.MongoClient数字 :
const mongodb = require('mongodb')
mongodb.MongoClient.connect('mongodb://mongo/db')
.then((client) => {
const fastify = require('fastify')()
fastify.register(require('@fastify/mongodb'), { client: client })
.register(function (fastify, opts, next) {
const db = fastify.mongo.client.db('mydb')
// ...
// ...
// ...
next()
})
})
.catch((err) => {
throw err
})
注释:
- 通过
client连接将 没有 快速服务器时关闭 关闭. - 要终止 MongoDB 连接,您必须手动调用 紧贴. 关闭 方法(例如用于测试目的,否则测试将悬挂).
mongodb连接超时从30s( 默认) 减少到7. 5s, 以在错误发生之前丢出fastify插件超时 .
参考文献
此插件装饰 fastify 实例 mongo 对象。 那个物体有:
以下属性 :
client这是MongoClient实例ObjectId这是ObjectId类db这是DB实例
这个 ObjectId 类也可以从插件中直接导入,因为从插件中再导出 mongodb数字 :
const { ObjectId } = require('@fastify/mongodb')
const id = new ObjectId('some-id-here')
这个 db 添加属性 只有在数字 :
- (单位:千美元)
database插件注册时会给出字符串选项 . - 连接字符串包含数据库名称。 见 连接字符串 URI 格式
A 类 name 选项可用于连接多个MongoDB集群.
const fastify = require('fastify')()
fastify
.register(require('@fastify/mongodb'), { url: 'mongodb://mongo1/mydb', name: 'MONGO1' })
.register(require('@fastify/mongodb'), { url: 'mongodb://mongo2/otherdb', name: 'MONGO2' })
fastify.get('/', function (req, res) {
// This collection comes from "mongodb://mongo1/mydb"
const coll1 = this.mongo.MONGO1.db.collection('my_collection')
// This collection comes from "mongodb://mongo2/otherdb"
const coll2 = this.mongo.MONGO2.db.collection('my_collection')
// ...
// ...
// do your stuff here
// ...
// ...
res.send(yourResult)
})
承认
这个项目由下列各方慷慨赞助:
过去提案国:
- 莱兹
许可证
许可证根据 麻省理工学院。 。 。 .