Skip to content

Instantly share code, notes, and snippets.

@brianzelip
Created January 19, 2022 18:28
Show Gist options
  • Save brianzelip/6deb77132751a0363f3b07ca62399329 to your computer and use it in GitHub Desktop.
Save brianzelip/6deb77132751a0363f3b07ca62399329 to your computer and use it in GitHub Desktop.
Use Mongoose.js as Fastify plugin
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment