billouboq / fastify-mongodb

Fastify MongoDB connection plugin

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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'
}, err => {
  if (err) throw err
})

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

License:MIT License


Languages

Language:JavaScript 100.0%