Fastify MongoDB connection plugin, with this you can share the same MongoDb connection pool in every part of your server.
Under the hood the official mongodb driver is used, the options that you pass to register
will be passed to the Mongo client. Pass the url option is required.
npm i fastify-mongodb --save
Add it to you project with register
and you are done!
You can access the Mongo database via fastify.mongo.db
and ObjectId via fastify.mongo.ObjectId
.
const fastify = require('fastify')
fastify.register(require('fastify-mongodb'), {
url: 'mongodb://mongo/db'
})
fastify.get('/user/:id', (req, reply) => {
const { db } = fastify.mongo
db.collection('users', onCollection)
function onCollection (err, col) {
if (err) return reply.send(err)
col.findOne({ id: req.params.id }, (err, user) => {
reply.send(user)
})
}
})
fastify.listen(3000, err => {
if (err) throw err
console.log(`server listening on ${fastify.server.address().port}`)
})
This project is kindly sponsored by:
Licensed under MIT.