0

I wanted to export the const database inside the MongoClient.connect function. I just tried to execute this code. However, this did not work.

module.exports.database = database

Does anyone have any guidance? I am trying to export this to another file that functions as a web scraper and I want to use this line to insert in the database.

database.collection('postInfo').insertMany(object)
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
require('dotenv').config();

// Connection URL
const url = process.env.MongoDB_URL;
let a = {};
//database name
const db = 'DB';

//use connect to connect to db
  MongoClient.connect(url, {useNewUrlParser: true}, function(err, client) {
    assert.equal(null, err);
    console.log("Connected successfully to server");

    const database = client.db(db);
    client.close();
  })
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
TanDev
  • 359
  • 3
  • 5
  • 13
  • 1
    Does this answer your question? [Asynchronous nodejs module exports](https://stackoverflow.com/questions/20238829/asynchronous-nodejs-module-exports) – jonrsharpe Aug 17 '20 at 13:00
  • Hey, It seems similar, however the solution seems complex. My issue is that I am trying to create a seperate db.js file with the above code. Alongside I have a scraper.js in which after scraping I want to add the contents from the scraper file to the database. If you know of a way I can do that, that should help as well. Thanks. – TanDev Aug 17 '20 at 13:11
  • I can share the entire code if that helps – TanDev Aug 17 '20 at 13:12
  • No, in general we want a [mre] not the whole code. You'll have to expose a *function*, either one that accepts a callback or returns a promise, not the database itself. – jonrsharpe Aug 17 '20 at 13:12
  • I think answer to this [question](https://stackoverflow.com/questions/24621940/how-to-properly-reuse-connection-to-mongodb-across-nodejs-application-and-module) might solve your problem. – Dashrath Chauhan Aug 17 '20 at 13:28

0 Answers0