Database Access in Node.js: Connecting Relational and NoSQL Databases
Learn how to access both relational and NoSQL databases in Node.js. This guide covers best practices, examples for MySQL, PostgreSQL, and MongoDB, and provides a comprehensive list of drivers and NPM commands for various databases.
Database Access
Node.js supports both relational and NoSQL databases, requiring specific drivers for each. Here’s a guide to popular databases and their drivers:
Best Practices and Considerations
- Connection Pooling: Use connection pooling to improve performance.
- Error Handling: Implement robust error handling to avoid failures.
- Asynchronous Operations: Handle async operations with promises or async/await.
- Security: Use parameterized queries, validate input, and manage passwords securely.
- ORMs and ODMs: Utilize ORMs like Sequelize and ODMs like Mongoose for easier database interactions.
- Performance Optimization: Optimize queries, use indexing, and consider caching.
MySQL:
Syntax
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test'
});
connection.connect(err => {
if (err) throw err;
console.log('Connected to MySQL!');
});
connection.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
});
connection.end();
Output
Connected to MySQL!
[ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]
PostgreSQL:
Syntax
const { Client } = require('pg');
const client = new Client({
host: 'localhost',
user: 'postgres',
password: 'password',
database: 'test'
});
client.connect()
.then(() => console.log('Connected to PostgreSQL!'))
.catch(err => console.error('Connection error', err.stack));
client.query('SELECT * FROM users', (err, res) => {
if (err) throw err;
console.log(res.rows);
client.end();
});
Output
Connected to PostgreSQL!
[ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]
NoSQL Databases
MongoDB:
Syntax
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
client.connect()
.then(() => {
console.log('Connected to MongoDB!');
const db = client.db('test');
return db.collection('users').find({}).toArray();
})
.then(users => {
console.log(users);
client.close();
})
.catch(err => console.error('Connection error', err));
Output
Connected to MongoDB!
[ { _id: ObjectId('...'), name: 'Alice' }, { _id: ObjectId('...'), name: 'Bob' } ]
Code Examples
Here are examples for connecting to different databases and performing CRUD operations:
Relational Databases
| Relational Databases | Driver | NPM Command |
|---|---|---|
| MS SQL Server | mssql | npm install mssql |
| Oracle | oracledb | npm install oracledb |
| MySQL | mysql | npm install mysql |
| PostgreSQL | pg | npm install pg |
| SQLite | node-sqlite3 | npm install node-sqlite3 |
NoSQL Databases
| NoSQL Databases | Driver | NPM Command |
|---|---|---|
| MongoDB | mongodb | npm install mongodb |
| Cassandra | cassandra-driver | npm install cassandra-driver |
| LevelDB | leveldb | npm install level levelup leveldown |
| RavenDB | ravendb | npm install ravendb |
| Neo4j | neo4j | npm install neo4j |
| Redis | redis | npm install redis |
| CouchDB | nano | npm install nano |
Note: The list of databases and drivers is extensive. Choose drivers based on your specific needs.