Node.js Tutorial

Node.js MongoDB Create a Database

Node.js MongoDB Create a Database

Node.js MongoDB: Create a Database

Creating a MongoDB database from Node.js is simpler than you may think. Connect with the MongoClient ÔÇö and MongoDB creates the database automatically if it does not already exist.

Node.js Tutorial:-
Complete Python Course:-

Steps

  • Create a folder (e.g. MongoDatabase).
  • Create createdatabase.js inside it.
  • Install the driver: npm install mongodb.

createdatabase.js

const { MongoClient } = require('mongodb');
const url = "mongodb://localhost:27017";

MongoClient.connect(url, function(err, client) {
  if (err) throw err;
  const db = client.db("MongoDatabase");
  console.log("Database ready!");
  client.close();
});

Run It

node createdatabase.js
# Output: Database ready!

Modern async/await

const { MongoClient } = require('mongodb');

async function run() {
  const client = new MongoClient("mongodb://localhost:27017");
  await client.connect();
  const db = client.db("MongoDatabase");
  await db.collection("init").insertOne({ created: new Date() });
  console.log("Database ready!");
  await client.close();
}
run().catch(console.error);

Important Note

MongoDB does not actually persist the database until you insert at least one document. Connecting alone is not enough ÔÇö that is why the async example above writes a document to make the database visible in show dbs.

Download New Real Time Projects:- Click here
Complete Advance AI topics:-

Conclusion

Creating a MongoDB database from Node.js is just a connection plus your first insert. For modern code, prefer async/await. For more tutorials, stay tuned to .

node js mongodb connection example
how to connect mongodb with node js in vs code
connect mongodb with node js express
node js mongodb create a database example
node js mongodb create a database w3schools
mongodb nodejs
nodejs mongodb tutorial
connect mongodb with nodejs

Source Code Available

Interested in This Project?

Get the complete source code for this project at a very affordable price — perfect for your portfolio, college submission, or learning. Message us on WhatsApp and we'll get back to you instantly!

Full source code included Step-by-step setup guide Instant delivery on WhatsApp Instant reply on WhatsApp
Chat on WhatsApp

We usually reply within a few minutes

Leave a Reply

Your email address will not be published. Required fields are marked *

Chat with us