Wednesday, 3 June 2020

Separate Routes file on Fastify with MongoDB

I am new to the Fastify Ecosystem, and I have been using the official fastify-mongodb plugin for connecting to MongoDB. I have had previous experience with Express+Mongoose, but fastify-mongodb does things quite differently.I wanted to have a different routes.js file containing all the routes, but I cannot figure out how to connect to the db.This works, if I put it on server.js :const Fastify = require('fastify'); const server = Fastify({ logger: true }); server.register(require('fastify-mongodb'), { forceClose: true, url: process.env.MONGO_URL }) server.get('/test', function (req, reply) { const db = this.mongo.db reply.send(db) }) But, if I use a separate route and do something like:routes.js:const routes = async (server, options) => { server.register(require('fastify-mongodb'), { forceClose: true, url: process.env.MONGO_URL }) server.get('/test', function (req, reply) { const db = this.mongo.db reply.send(db) }) ... And then on server.js:server.register(require('./routes')) it simply doesn't work. this.mongo becomes undefined.What exactly am I doing wrong? Is there any way to achieve Mongoose-style schema and modularity with Fastify-MongoDB?

Submitted June 04, 2020 at 12:18AM by Mycroft2046

No comments:

Post a Comment