
Mongodb Create Db in NodeJs
Creating a MongoDB database in Node.js is super simple β MongoDB creates a database automatically when you insert data into it! π
Letβs walk through it using both:
β Native MongoDB Driver
πͺ Mongoose (an ODM β Object Data Modeling tool)
β 1. Using Native MongoDB Driver
π¦ Step 1: Install the MongoDB Driver
npm install mongodb
βοΈ Step 2: Create a Database and Collection
const client = new MongoClient(uri);async function createDatabase() { try { await client.connect(); // Create (or get) the database const db = client.db('myNewDatabase'); // Create (or get) the collection const collection = db.collection('users'); // Insert a document to trigger DB + collection creation await collection.insertOne({ name: 'Alice', age: 25 }); console.log('Database and collection created with one document!'); } catch (err) { console.error(err); } finally { await client.close(); }}createDatabase();
π MongoDB does not create the database until you insert something.
πͺ 2. Using Mongoose (easier & structured)
π¦ Step 1: Install Mongoose
npm install mongoose
βοΈ Step 2: Define Schema and Save Data
const mongoose = require('mongoose');// Connect to DB (MongoDB will create it if it doesn't exist)mongoose.connect('mongodb://localhost:27017/myNewDatabase') .then(() => console.log('Connected to MongoDB!')) .catch(err => console.error(err));// Define schemaconst userSchema = new mongoose.Schema({ name: String, age: Number});// Create modelconst User = mongoose.model('User', userSchema);// Insert a user (this creates the DB & collection)const newUser = new User({ name: 'Bob', age: 30 });newUser.save().then(() => { console.log('User saved and database created!'); mongoose.disconnect();});
π Summary
Tool | Behavior |
---|---|
Native Driver | Manually create DB by calling db.collection() and inserting data |
Mongoose | Auto-creates DB + collection when a document is saved via a model |
Want to go further? I can help you:
Build a full REST API using MongoDB
Connect to MongoDB Atlas (cloud)
Do CRUD operations or relationships (like joins via
populate
)