Skip to content

Instantly share code, notes, and snippets.

@brianzelip
Created January 19, 2022 18:28
Show Gist options
  • Select an option

  • Save brianzelip/6deb77132751a0363f3b07ca62399329 to your computer and use it in GitHub Desktop.

Select an option

Save brianzelip/6deb77132751a0363f3b07ca62399329 to your computer and use it in GitHub Desktop.

Revisions

  1. brianzelip created this gist Jan 19, 2022.
    18 changes: 18 additions & 0 deletions fastify-mongoose-plugin.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    const dotenv = require('dotenv').config();
    const mongoose = require('mongoose');
    const fp = require('fastify-plugin');

    async function mongooseConnect(fastify, options, done) {
    try {
    await mongoose.connect(process.env.DB_URI);
    console.log('DB connected!');
    } catch (err) {
    console.log(err);
    }

    fastify.decorate('db', mongoose.connection); // usage example: `fastify.db.users.find({})`

    done();
    }

    module.exports = fp(mongooseConnect);