Skip to content

Latest commit

 

History

History
50 lines (37 loc) · 1.51 KB

README.md

File metadata and controls

50 lines (37 loc) · 1.51 KB

fastify-mongodb

js-standard-style Build Status

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.

Install

npm i fastify-mongodb --save

Usage

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}`)
})

Acknowledgements

This project is kindly sponsored by:

License

Licensed under MIT.