🗄️ Node.js – MongoDB: CRUD Operations
Estimated reading: 3 minutes 29 views

➕ Node.js – MongoDB Insert – Add Documents to MongoDB Using Node.js


🧲 Introduction – Why Insert Data into MongoDB with Node.js?

In MongoDB, data is stored as documents in collections. To build functional apps—like user systems, e-commerce platforms, or analytics dashboards—you need to insert data into collections. Node.js makes this process seamless with the official mongodb driver.

🎯 In this guide, you’ll learn:

  • How to insert a single document using insertOne()
  • How to insert multiple documents using insertMany()
  • Handle insert callbacks and async/await
  • Best practices for inserting data securely

⚙️ Setup – MongoDB Connection

📁 db.js (Reusable Connection File)

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

const url = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(url);
const dbName = 'appDB';

async function getDB() {
  await client.connect();
  console.log('✅ Connected to MongoDB');
  return client.db(dbName);
}

module.exports = getDB;

➕ Insert a Single Document – insertOne()

📁 insertOne.js

const getDB = require('./db');

async function insertUser() {
  const db = await getDB();
  const result = await db.collection('users').insertOne({
    name: 'Alice',
    email: 'alice@example.com',
    age: 28
  });

  console.log('📦 Document inserted with _id:', result.insertedId);
}

insertUser();

🧪 Output:

✅ Connected to MongoDB  
📦 Document inserted with _id: 64f8a5...

✅ Automatically generates a unique _id.


📑 Insert Multiple Documents – insertMany()

const getDB = require('./db');

async function insertManyUsers() {
  const db = await getDB();
  const users = [
    { name: 'Bob', age: 30 },
    { name: 'Charlie', age: 22 },
    { name: 'Diana', age: 35 }
  ];

  const result = await db.collection('users').insertMany(users);
  console.log('🧾 Multiple documents inserted:', result.insertedCount);
}

insertManyUsers();

🧪 Output:

✅ Connected to MongoDB  
🧾 Multiple documents inserted: 3

📛 Error Handling – Duplicate _id

await db.collection('users').insertOne({
  _id: 'customID123',
  name: 'Eve'
});

// Trying to insert again with same _id
await db.collection('users').insertOne({
  _id: 'customID123',
  name: 'John'
});

🛑 This throws a duplicate key error:

MongoServerError: E11000 duplicate key error collection

🧱 Best Practices for Insert Operations

✅ Practice💡 Why It’s Important
Use insertMany for batch insertsReduces round-trips and improves performance
Always validate inputPrevents corrupt or unexpected documents
Handle insertedId(s) properlyUseful for linking records or debugging
Avoid custom _id unless neededMongoDB’s default _id is reliable and unique
Catch duplicate errors gracefullyEnsures robust error-handling and UX

📌 Summary – Recap & Next Steps

You’ve now learned how to insert one or many documents into MongoDB using Node.js. With these techniques, you can populate your database with any kind of structured data—users, products, posts, events, and more.

🔍 Key Takeaways:

  • Use insertOne() for single docs, insertMany() for bulk inserts
  • Validate data and handle duplicate key errors
  • Use async/await for cleaner, non-blocking operations
  • MongoDB creates _id if you don’t supply one

⚙️ Real-world relevance:
Used in user signups, form submissions, batch imports, admin uploads, and API endpoints.


❓FAQs – Inserting Documents in MongoDB with Node.js


What’s the difference between insertOne and insertMany?
insertOne inserts a single document; insertMany takes an array of documents.


Is it required to define _id manually?
✅ No. MongoDB will auto-generate a unique _id unless you explicitly provide one.


How do I get the inserted document’s ID?
✅ Use result.insertedId for insertOne or result.insertedIds for insertMany.


What happens if I try to insert a duplicate _id?
✅ You’ll receive a MongoServerError with a duplicate key violation.


Can I insert documents without all fields?
✅ Yes. MongoDB doesn’t enforce schemas unless you define one (e.g., using Mongoose).


Share Now :

Leave a Reply

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

Share

➕ Node.js – MongoDB Insert

Or Copy Link

CONTENTS
Scroll to Top