Home > Enterprise >  Why are new users being added to the database?
Why are new users being added to the database?

Time:08-12

Console application on Node.JS and MongoDB. In one file, I implemented adding users, and in the second, outputting all collection objects to the console. When executing the command - node scripts/get_all_users.js, users are displayed in the console and new ones are added, as when executing a file with adding a user. Although the code for adding users lies in another file. How can this problem be solved?

add_user.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",
  },
  {
    name: "Tom",
  },
];

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();
  });
});

get_all_users.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:

When you do this:

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

The code in add_users is executed. That code includes adding users:

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();
  });
});

Instead of importing mongoClient from add_users, just import it plainly the same way you currently do in add_users:

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

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

Or, to reduce duplication, create a mongo_client file which just creates the client, but doesn't add users:

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

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

module.exports = {
  mongoClient
};

And import that into both other files:

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