Skip to content

wedgwood/fastify-mongodb

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

About

Fastify MongoDB connection plugin

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%