Home > Software design >  How to use mongoClient in different files
How to use mongoClient in different files

Time:08-12

In the application, in different files, I need to perform different functions with MongoDB. In one file I record users. And in the second one, you need to output all the documents in the collection to the console. How can I use mongoClient in another file. That connection was only in one file. I tried using module.exports but got an error - mongoClient.connect is not a function. How can i do this?

add_users.js:

const MongoClient = require("mongodb").MongoClient;

const url = "mongodb://localhost:27017/";
const mongoClient = new MongoClient(url);

module.exports = {
  mongoClient
};

let users = [{
    name: "Bob",
  },
  {
    name: "Alice",
  },
];

mongoClient.connect(function(err, client) {
  const db = client.db("expensesdb");
  const collection = db.collection("users");
  collection.insertMany(users, function(err, results) {
    if (err) {
      return console.log(err);
    }
    console.log(results);
    client.close();
  });
});

find_doc.js:

const mongoClient = require("./add_users");

mongoClient.connect(function (err, client) {
  const db = client.db("expensesdb");
  const collection = db.collection("users");

  if (err) return console.log(err);

  collection.find().toArray(function (err, results) {
    console.log(results);
    client.close();
  });
});

CodePudding user response:

You should change your import statement to:

const { mongoClient } = require("./add_users");
  • Related