- Node.js Tutorial
- NodeJS Home
- NodeJS Introduction
- NodeJS Setup
- NodeJS First App
- NodeJS REPL
- NodeJS Command Line
- NodeJS NPM
- NodeJS Callbacks
- NodeJS Events
- NodeJS Event-Loop
- NodeJS Event-Emitter
- NodeJS Global-Objects
- NodeJS Console
- NodeJS Process
- NodeJS Buffers
- NodeJS Streams
- Node.js File Handling
- Node.js File System
- Node.js Read/Write File
- Working with folders in Node.js
- HTTP and Networking
- Node.js HTTP Module
- Anatomy of an HTTP Transaction
- Node.js MongoDB
- MongoDB Get Started
- MongoDB Create Database
- MongoDB Create Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Update
- MongoDB Limit
- MongoDB Join
- Node.js MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert Into
- MySQL Select From
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Update
- MySQL Join
- Node.js Modules
- Node.js Modules
- Node.js Built-in Modules
- Node.js Utility Modules
- Node.js Web Module
- Node.js Advanced
- Node.js Debugger
- Node.js Scaling Application
- Node.js Packaging
- Node.js Express Framework
- Node.js RESTFul API
- Node.js Useful Resources
- Node.js Useful Resources
- Node.js Discussion
Node.js MongoDB Insert
In MongoDB, inserting data into collections is a fundamental operation. Unlike traditional SQL databases, MongoDB is schema-less, meaning you can insert documents with different structures into the same collection without defining a strict table schema beforehand. Using the official Node.js driver, you can efficiently add data as BSON (Binary JSON) documents.
Key Features of Insert Operations
- Schema Flexibility: You can insert a single document or multiple documents with varying fields in one operation.
- Automatic Indexing: Each document is automatically assigned a unique
_idfield by MongoDB if you don't provide one. This acts as the primary key. - Write Concerns: You can configure how much acknowledgment you need from the database server before a write is considered successful, which is vital for data integrity.
- Batch Performance: The
insertManymethod reduces the overhead of network round-trips by sending multiple records in a single request.
Step 1 Prerequisites
Before writing code, ensure you have a Node.js environment ready. You will need the mongodb package installed in your project folder. If you haven't initialized your project yet, run npm init -y first.
npm install mongodb
Step 2 Insert a Single Document
The insertOne method is your primary tool for adding a single object to your collection. This is commonly used for tasks like user registration or saving a specific application setting.
Example Code
const { MongoClient } = require('mongodb');
// Connection URL - use environment variables in production!
const url = 'mongodb://127.0.0.1:27017';
const dbName = 'mydatabase';
async function insertSingleDocument() {
const client = new MongoClient(url);
try {
// Connect to the MongoDB server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('users');
// Define the document to insert
const newUser = {
name: 'Alice',
age: 28,
email: '[email protected]',
createdAt: new Date()
};
// Perform the insert operation
const result = await collection.insertOne(newUser);
// The result object tells us the ID that MongoDB generated
console.log('Document inserted with _id:', result.insertedId);
} catch (err) {
console.error('Insert failed:', err);
} finally {
// Always close the connection to avoid memory leaks
await client.close();
}
}
insertSingleDocument().catch(console.error);
Output:
Connected successfully to server
Document inserted with _id: 61b0fcab12c5ae23f89e7a12
await or .then() when calling insertOne. Since database operations are asynchronous, failing to wait for the operation will lead to "Race Conditions" where your code proceeds before the data is actually saved.
Step 3 Insert Multiple Documents
When you have a list of data such as migrating records from a CSV file or bulk-uploading products the insertMany method is significantly faster than looping through an array and calling insertOne repeatedly.
Example Code
async function insertMultipleDocuments() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Array of documents to insert
const users = [
{ name: 'Bob', age: 32, role: 'Admin' },
{ name: 'Charlie', age: 45, role: 'User' },
{ name: 'Diana', age: 29, role: 'Editor' }
];
const result = await collection.insertMany(users);
console.log(`${result.insertedCount} documents were inserted.`);
console.log('Inserted IDs:', result.insertedIds);
} finally {
await client.close();
}
}
insertMultipleDocuments().catch(console.error);
Output:
3 documents were inserted.
Inserted IDs: { '0': 61b0fcab..., '1': 61b0fcab..., '2': 61b0fcab... }
insertMany is "ordered." This means if the 3rd document in a list of 10 fails (e.g., due to a validation error), MongoDB will stop and not attempt to insert the remaining 7. You can change this by passing { ordered: false } as an option.
Step 4 Verify Inserted Data
After running your Node.js scripts, it is good practice to verify that the data reached the database correctly. You can do this via the command line or a GUI tool.
- Via MongoDB Compass: Open the application, connect to
localhost:27017, and navigate tomydatabase > users. - Via Mongosh (Shell): Run the following commands in your terminal:
# Enter the shell
mongosh
# Switch to the database
use mydatabase
# Find all documents in the 'users' collection
db.users.find().pretty()
Step 5 Handle Duplicate Keys
The _id field is unique. While MongoDB usually generates an ObjectId for you, you can provide your own custom _id. However, if you try to insert a document with an _id that already exists in the collection, the driver will throw a MongoServerError.
Example Code
async function handleDuplicateKey() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Manually setting a numeric _id
const doc = { _id: 101, name: 'David', age: 29 };
await collection.insertOne(doc);
console.log('First insert successful.');
// Attempting to insert the same _id again
await collection.insertOne({ _id: 101, name: 'Emma', age: 34 });
} catch (error) {
if (error.code === 11000) {
console.error('Error: A document with this ID already exists!');
} else {
console.error('An unexpected error occurred:', error.message);
}
} finally {
await client.close();
}
}
handleDuplicateKey().catch(console.error);
Output:
First insert successful.
Error: A document with this ID already exists!
ObjectId. It is designed to be highly unique across distributed systems and includes a timestamp.
Summary
Mastering insertOne and insertMany is the foundation of building data-driven applications with Node.js and MongoDB. By leveraging the flexible nature of BSON documents, you can quickly evolve your data structures without complex migrations. Always remember to handle potential errors like duplicate keys and ensure your database connections are closed properly to keep your application performant.