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.jsinside 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