ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Mongodb Create Db in NodeJs

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='22' AND `tutorial_submenu`='1399' AND `tutorial_status`=1 LIMIT 1

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:

  1. βœ… Native MongoDB Driver

  2. πŸͺ„ Mongoose (an ODM – Object Data Modeling tool)


βœ… 1. Using Native MongoDB Driver

πŸ“¦ Step 1: Install the MongoDB Driver

bash

npm install mongodb

βš™οΈ Step 2: Create a Database and Collection

js

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

bash

npm install mongoose

βš™οΈ Step 2: Define Schema and Save Data

js

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

ToolBehavior
Native DriverManually create DB by calling db.collection() and inserting data
MongooseAuto-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)

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql