Database Setup Guide
Overview
This guide will help you set up and connect to different types of databases in your Node.js application. We'll cover MongoDB, PostgreSQL, and MySQL, which are among the most popular database systems used with Node.js.
Prerequisites
- Node.js (version 14 or newer)
- npm or Yarn package manager
- Access to your chosen database system (local or cloud-hosted)
- Basic knowledge of JavaScript/Node.js and SQL (for relational databases)
Database Setup
MongoDB is a NoSQL document database that stores data in flexible, JSON-like documents. It's a popular choice for modern web applications due to its scalability and flexibility.
1. Install MongoDB Node.js Driver
npm install mongodb
2. Connect to MongoDB
// db.js
const { MongoClient } = require('mongodb');
// or with ES modules:
// import { MongoClient } from 'mongodb';
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri);
async function connectToDatabase() {
try {
await client.connect();
console.log('Connected to MongoDB');
return client.db('your_database_name');
} catch (error) {
console.error('Error connecting to MongoDB:', error);
throw error;
}
}
module.exports = { connectToDatabase, client };
// or with ES modules:
// export { connectToDatabase, client };
3. Create a document
async function createDocument() {
try {
const db = await connectToDatabase();
const collection = db.collection('users');
const result = await collection.insertOne({
name: 'John Doe',
email: 'john@example.com',
createdAt: new Date()
});
console.log(`Document created with ID: ${result.insertedId}`);
return result;
} catch (error) {
console.error('Error creating document:', error);
throw error;
}
}
4. Find documents
async function findDocuments(query = {}) {
try {
const db = await connectToDatabase();
const collection = db.collection('users');
const documents = await collection.find(query).toArray();
console.log(`Found ${documents.length} documents`);
return documents;
} catch (error) {
console.error('Error finding documents:', error);
throw error;
}
}
Environment Variables
It's important to store your database connection details as environment variables rather than hardcoding them in your application. Here's how to set up environment variables for your database connection:
# .env file # MongoDB MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/database # PostgreSQL PGUSER=postgres_user PGHOST=localhost PGDATABASE=my_database PGPASSWORD=postgres_password PGPORT=5432 # MySQL MYSQL_HOST=localhost MYSQL_USER=mysql_user MYSQL_PASSWORD=mysql_password MYSQL_DATABASE=my_database
Remember to install the dotenv
package and load these variables in your application:
require('dotenv').config();import 'dotenv/config';
Best Practices
- Always use connection pooling for SQL databases to manage connections efficiently
- Close database connections when they're no longer needed to prevent memory leaks
- Use parameterized queries to prevent SQL injection attacks
- Implement proper error handling for database operations
- Use migrations for managing database schema changes
- Consider using an ORM (Object-Relational Mapping) library like Sequelize, Prisma, or TypeORM for more complex applications
- Regularly backup your database to prevent data loss
Additional Resources
Need Help?
If you're having trouble setting up your database or need custom database design and optimization services, our team is here to help.
Contact Us