Welcome to The Coding College! This tutorial will teach you how to insert data into a MongoDB collection using Node.js. MongoDB’s flexibility allows you to store documents without the need for predefined schemas, making it a great fit for modern applications.
Prerequisites
Ensure you have the following setup before proceeding:
- MongoDB Installed: Download MongoDB.
- Node.js Installed: Download Node.js.
- MongoDB Driver Installed: Install it with:
npm install mongodb
Step 1: Establish a Connection to MongoDB
Create a file insertData.js
and set up the MongoDB connection:
const { MongoClient } = require('mongodb');
// Connection URL
const url = 'mongodb://localhost:27017'; // Default MongoDB URL
const client = new MongoClient(url);
// Database and Collection Names
const dbName = 'myNewDatabase';
const collectionName = 'users';
async function insertData() {
try {
// Connect to MongoDB
await client.connect();
console.log('Connected to MongoDB server.');
// Select the database and collection
const db = client.db(dbName);
const collection = db.collection(collectionName);
// Insert a single document
const user = { name: 'John Doe', email: '[email protected]', age: 30 };
const result = await collection.insertOne(user);
console.log('Document inserted with ID:', result.insertedId);
} catch (err) {
console.error('Error inserting data:', err.message);
} finally {
// Close the connection
await client.close();
console.log('Connection closed.');
}
}
insertData();
Step 2: Insert Multiple Documents
To insert multiple documents, use the insertMany()
method:
async function insertMultipleDocuments() {
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection(collectionName);
const users = [
{ name: 'Alice', email: '[email protected]', age: 25 },
{ name: 'Bob', email: '[email protected]', age: 28 },
{ name: 'Charlie', email: '[email protected]', age: 35 },
];
const result = await collection.insertMany(users);
console.log(`${result.insertedCount} documents inserted.`);
} catch (err) {
console.error('Error:', err.message);
} finally {
await client.close();
}
}
insertMultipleDocuments();
Step 3: Run the Script
Run your script using Node.js:
node insertData.js
Output
For single document insertion:
Connected to MongoDB server.
Document inserted with ID: 64c12345abcd6789ef123456
Connection closed.
For multiple document insertion:
Connected to MongoDB server.
3 documents inserted.
Connection closed.
Step 4: Verify Data
- Open MongoDB Shell or MongoDB Compass.
- Query the
users
collection:db.users.find().pretty()
You should see the inserted data displayed.
Best Practices
- Validation: Use validation rules in MongoDB to ensure data consistency.
- Indexes: Add indexes to frequently queried fields for performance optimization.
- Error Handling: Always handle errors gracefully in your application.
- Environment Variables: Use
.env
files for sensitive information like connection URLs.
Example Code for Reusability
To make your insertion script reusable, modularize the database connection logic:
const { MongoClient } = require('mongodb');
const connectToDatabase = async () => {
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
await client.connect();
return client;
};
module.exports = connectToDatabase;
Use it in your main script:
const connectToDatabase = require('./connectToDatabase');
async function insertData() {
const client = await connectToDatabase();
try {
const db = client.db('myNewDatabase');
const collection = db.collection('users');
const user = { name: 'John Doe', email: '[email protected]', age: 30 };
const result = await collection.insertOne(user);
console.log('Document inserted with ID:', result.insertedId);
} finally {
await client.close();
}
}
insertData();
Conclusion
Inserting data into MongoDB using Node.js is efficient and simple, thanks to its JSON-like document structure and flexible schema. For more detailed tutorials, check out The Coding College and keep enhancing your skills.