ExpressJS Middleware Method to make variable available in other (module) files












0















I am playing around with making a NodeJS app that combines REST API functionality with MongoDB CRUD persistence. I'm pretty new to NodeJS.



Right now I've managed to connect to the Database and figured out that the rest of my code belongs inside the callback - ie only process REST request after the DB is up and available.



The challenge I'm running into in this case is understanding how to "attach" the 'client' (from mongodb.connect) to the 'request'. I need to somehow make it available in other files because I want to keep my routes separate as a best practice.



The same question applies to any variables in the main server.js file which I need to be able to access in my modules.
Here is the relevant code:



//server.js
const express = require('express')
const mongodb = require('mongodb')
const bodyParser = require('body-parser')
const routes = require('./routes')

const url = 'mongodb://localhost:27017/testDB'
let app = express();
app.use(logger('dev'))
app.use(bodyParser.json())

mongodb.connect(url, {useNewUrlParser:true},(error, dbClient) => {
if (error) {
console.log(`Error: ${error}`)
process.exit(1)
}

//connected
console.log(`Connected to mongoDB`)
//what do I do here to make sure my routes can access dbClient?
app.get('/accounts', routes.getAccounts(req, res) )

app.listen(3000)
})


//./routes/index.js
const bodyParser = require('body-parser')
const errorhandler = require('errorhandler')
const mongodb = require('mongodb')
const logger = require('morgan')

module.exports = {
getAccounts: (req, res) => {
console.log("in getAccounts")
//how can I use dbClient in here?
}
}


Thank you in advance for your help!
My apologies if anything about my post isn't according to the normal standards, I'm brand new here! All critique appreciated, coding and otherwise!










share|improve this question

























  • This article will help you. Use connection pooling. Do not create a new connection for each incoming request. compose.com/articles/connection-pooling-with-mongodb

    – Matt Long
    Nov 25 '18 at 20:20






  • 1





    @MattLong Thanks for the tip, I didn't know such a thing existed but it makes a lot of sense. Raises a lot of questions too and I will dive deeper into the docs.

    – Lazer Porter
    Nov 25 '18 at 23:34
















0















I am playing around with making a NodeJS app that combines REST API functionality with MongoDB CRUD persistence. I'm pretty new to NodeJS.



Right now I've managed to connect to the Database and figured out that the rest of my code belongs inside the callback - ie only process REST request after the DB is up and available.



The challenge I'm running into in this case is understanding how to "attach" the 'client' (from mongodb.connect) to the 'request'. I need to somehow make it available in other files because I want to keep my routes separate as a best practice.



The same question applies to any variables in the main server.js file which I need to be able to access in my modules.
Here is the relevant code:



//server.js
const express = require('express')
const mongodb = require('mongodb')
const bodyParser = require('body-parser')
const routes = require('./routes')

const url = 'mongodb://localhost:27017/testDB'
let app = express();
app.use(logger('dev'))
app.use(bodyParser.json())

mongodb.connect(url, {useNewUrlParser:true},(error, dbClient) => {
if (error) {
console.log(`Error: ${error}`)
process.exit(1)
}

//connected
console.log(`Connected to mongoDB`)
//what do I do here to make sure my routes can access dbClient?
app.get('/accounts', routes.getAccounts(req, res) )

app.listen(3000)
})


//./routes/index.js
const bodyParser = require('body-parser')
const errorhandler = require('errorhandler')
const mongodb = require('mongodb')
const logger = require('morgan')

module.exports = {
getAccounts: (req, res) => {
console.log("in getAccounts")
//how can I use dbClient in here?
}
}


Thank you in advance for your help!
My apologies if anything about my post isn't according to the normal standards, I'm brand new here! All critique appreciated, coding and otherwise!










share|improve this question

























  • This article will help you. Use connection pooling. Do not create a new connection for each incoming request. compose.com/articles/connection-pooling-with-mongodb

    – Matt Long
    Nov 25 '18 at 20:20






  • 1





    @MattLong Thanks for the tip, I didn't know such a thing existed but it makes a lot of sense. Raises a lot of questions too and I will dive deeper into the docs.

    – Lazer Porter
    Nov 25 '18 at 23:34














0












0








0








I am playing around with making a NodeJS app that combines REST API functionality with MongoDB CRUD persistence. I'm pretty new to NodeJS.



Right now I've managed to connect to the Database and figured out that the rest of my code belongs inside the callback - ie only process REST request after the DB is up and available.



The challenge I'm running into in this case is understanding how to "attach" the 'client' (from mongodb.connect) to the 'request'. I need to somehow make it available in other files because I want to keep my routes separate as a best practice.



The same question applies to any variables in the main server.js file which I need to be able to access in my modules.
Here is the relevant code:



//server.js
const express = require('express')
const mongodb = require('mongodb')
const bodyParser = require('body-parser')
const routes = require('./routes')

const url = 'mongodb://localhost:27017/testDB'
let app = express();
app.use(logger('dev'))
app.use(bodyParser.json())

mongodb.connect(url, {useNewUrlParser:true},(error, dbClient) => {
if (error) {
console.log(`Error: ${error}`)
process.exit(1)
}

//connected
console.log(`Connected to mongoDB`)
//what do I do here to make sure my routes can access dbClient?
app.get('/accounts', routes.getAccounts(req, res) )

app.listen(3000)
})


//./routes/index.js
const bodyParser = require('body-parser')
const errorhandler = require('errorhandler')
const mongodb = require('mongodb')
const logger = require('morgan')

module.exports = {
getAccounts: (req, res) => {
console.log("in getAccounts")
//how can I use dbClient in here?
}
}


Thank you in advance for your help!
My apologies if anything about my post isn't according to the normal standards, I'm brand new here! All critique appreciated, coding and otherwise!










share|improve this question
















I am playing around with making a NodeJS app that combines REST API functionality with MongoDB CRUD persistence. I'm pretty new to NodeJS.



Right now I've managed to connect to the Database and figured out that the rest of my code belongs inside the callback - ie only process REST request after the DB is up and available.



The challenge I'm running into in this case is understanding how to "attach" the 'client' (from mongodb.connect) to the 'request'. I need to somehow make it available in other files because I want to keep my routes separate as a best practice.



The same question applies to any variables in the main server.js file which I need to be able to access in my modules.
Here is the relevant code:



//server.js
const express = require('express')
const mongodb = require('mongodb')
const bodyParser = require('body-parser')
const routes = require('./routes')

const url = 'mongodb://localhost:27017/testDB'
let app = express();
app.use(logger('dev'))
app.use(bodyParser.json())

mongodb.connect(url, {useNewUrlParser:true},(error, dbClient) => {
if (error) {
console.log(`Error: ${error}`)
process.exit(1)
}

//connected
console.log(`Connected to mongoDB`)
//what do I do here to make sure my routes can access dbClient?
app.get('/accounts', routes.getAccounts(req, res) )

app.listen(3000)
})


//./routes/index.js
const bodyParser = require('body-parser')
const errorhandler = require('errorhandler')
const mongodb = require('mongodb')
const logger = require('morgan')

module.exports = {
getAccounts: (req, res) => {
console.log("in getAccounts")
//how can I use dbClient in here?
}
}


Thank you in advance for your help!
My apologies if anything about my post isn't according to the normal standards, I'm brand new here! All critique appreciated, coding and otherwise!







node.js express






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 19:58









Neil Lunn

99.1k23175184




99.1k23175184










asked Nov 25 '18 at 19:53









Lazer PorterLazer Porter

34




34













  • This article will help you. Use connection pooling. Do not create a new connection for each incoming request. compose.com/articles/connection-pooling-with-mongodb

    – Matt Long
    Nov 25 '18 at 20:20






  • 1





    @MattLong Thanks for the tip, I didn't know such a thing existed but it makes a lot of sense. Raises a lot of questions too and I will dive deeper into the docs.

    – Lazer Porter
    Nov 25 '18 at 23:34



















  • This article will help you. Use connection pooling. Do not create a new connection for each incoming request. compose.com/articles/connection-pooling-with-mongodb

    – Matt Long
    Nov 25 '18 at 20:20






  • 1





    @MattLong Thanks for the tip, I didn't know such a thing existed but it makes a lot of sense. Raises a lot of questions too and I will dive deeper into the docs.

    – Lazer Porter
    Nov 25 '18 at 23:34

















This article will help you. Use connection pooling. Do not create a new connection for each incoming request. compose.com/articles/connection-pooling-with-mongodb

– Matt Long
Nov 25 '18 at 20:20





This article will help you. Use connection pooling. Do not create a new connection for each incoming request. compose.com/articles/connection-pooling-with-mongodb

– Matt Long
Nov 25 '18 at 20:20




1




1





@MattLong Thanks for the tip, I didn't know such a thing existed but it makes a lot of sense. Raises a lot of questions too and I will dive deeper into the docs.

– Lazer Porter
Nov 25 '18 at 23:34





@MattLong Thanks for the tip, I didn't know such a thing existed but it makes a lot of sense. Raises a lot of questions too and I will dive deeper into the docs.

– Lazer Porter
Nov 25 '18 at 23:34












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53471305%2fexpressjs-middleware-method-to-make-variable-available-in-other-module-files%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53471305%2fexpressjs-middleware-method-to-make-variable-available-in-other-module-files%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

404 Error Contact Form 7 ajax form submitting

How to know if a Active Directory user can login interactively

TypeError: fit_transform() missing 1 required positional argument: 'X'