Create Database in Node

In MongoDB, databases are not explicitly created as you might expect in traditional SQL databases. Instead, databases are created implicitly when we first store data in them.

When using Mongoose, a popular MongoDB object modelling tool for Node.js, we typically interact with collections rather than databases directly.

However, we can specify the "database name" when connecting to MongoDB using "Mongoose".

Steps to Create Database using Mongoose:

  • Install Mongoose: we first need to Install the `mongoose` package in our Node.js project.

  • Connect to MongoDB: Using the `mongoose` package we can connect to our local or cloud (MongoDB Atlas) database.

  • Define Schema: We need to define a Mongoose schema to represent the structure of our `Collection`. This includes defining fields and their data types.

  • Create Model: Create a Mongoose model using the schema. Models represent collections in MongoDB and provide an interface for interacting with data.

  • Insert Data: After creating the `Model` we can insert data into the database.

Connect MongoDB with Specified Database Name:

Using the "mongoose.connect()" method we can connect to our MongoDB database by specifying the database name and URL.

If Connection is established successfully then it will print the message `Connected to MongoDB database your_database_name` in console.

if we encounter any error while connecting with the database we handle it in `catch` block.

Create file name `db.js` in the root directory of Project.

Example:

const mongoose = require("mongoose");

const uri = "mongodb://localhost:27017"; // MongoDB connection string

const dbName = "your_database_name"; // Database name

function connectDB(){
  mongoose
    .connect(`${uri}/${dbName}`)
    .then(() => {
      console.log(`Connected to MongoDB database '${dbName}'`);
      // Your code here
    })
    .catch((err) => {
      console.error("Error connecting to MongoDB:", err);
    });
};

module.exports = connectDB

Note: Please do not forget to Replace 'mongodb://localhost:27017' with your MongoDB connection string if using `Mongo Atlas`.

Create file name `server.js` in root directory:

Example:

let http = require("http");
const dbConnection = require("./db");

const PORT = 3002;

http
  .createServer(function (req, res) {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("Server Start Listening on 3002");
  })
  .listen(PORT, () => {
    console.log(`server listening on port ${PORT}!`);
    dbConnection();
  });

import the `db.js` file into `server.js` using `require` method.

Output:

server listening on port 3002!
Connected to MongoDB database 'your_database_name'