I
I
Ivan2019-04-04 17:55:56
MongoDB
Ivan, 2019-04-04 17:55:56

How to move the connection to mongodb in node.js into a separate file?

There is a code:

const config = require('./config.json');
const url_db = config.mongodb.url;
const MongoClient = require("mongodb").MongoClient;
const mongoClient = new MongoClient(url_db, { useNewUrlParser: true });
mongoClient.connect(function(err, client){
    const collection = client.db("eshopdb").collection("games_eu");
    app.locals.collection = collection;
});

I would like to make the connection to mongodb in a separate file, connected via require in any other file, with connection monitoring, so as not to connect once again. You need to pass parameters such as url_db and collection_name to this file.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question