Database Operations for node.js to perform CRUD operations on databases
Node.js provides a robust and efficient platform for performing database operations. With a wide range of database drivers and libraries available, developers can seamlessly connect to various databases like MongoDB, MySQL, PostgreSQL, and more.
Node.js’s asynchronous nature and non-blocking I/O model make it an excellent choice for handling database operations, allowing applications to efficiently handle concurrent requests and scale effectively.
Whether it’s performing CRUD (Create, Read, Update, Delete) operations, executing complex queries, or managing database transactions, Node.js offers a versatile and powerful environment for working with databases.
Node.js’s rich ecosystem includes numerous database libraries and ORM (Object-Relational Mapping) frameworks that simplify database operations and provide higher-level abstractions.

These libraries, such as Mongoose for MongoDB, Sequelize for SQL-based databases, and Knex.js for query building, offer features like data validation, schema management, and query optimization, which expedite the development process.
Furthermore, the availability of database-specific modules and drivers ensures compatibility with different database systems, enabling developers to choose the most suitable option for their specific use cases.
Overall, Node.js empowers developers to build database-driven applications efficiently, ensuring seamless integration and efficient management of data.
Here’s an example of Node.js code that showcases CRUD (Create, Read, Update, Delete) operations on databases like MongoDB, MySQL, and PostgreSQL:
MongoDB Example (using the official MongoDB Node.js driver):
const { MongoClient } = require('mongodb');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'mydatabase';
// CRUD operations
async function performCRUDOperations() {
// Connect to the MongoDB server
const client = new MongoClient(url);
try {
await client.connect();
console.log('Connected to MongoDB server');
const db = client.db(dbName);
const collection = db.collection('mycollection');
// Create
await collection.insertOne({ name: 'John', age: 30 });
// Read
const result = await collection.find({ name: 'John' }).toArray();
console.log('Read result:', result);
// Update
await collection.updateOne({ name: 'John' }, { $set: { age: 35 } });
// Delete
await collection.deleteOne({ name: 'John' });
} catch (error) {
console.error('Error:', error);
} finally {
// Close the connection
await client.close();
console.log('Disconnected from MongoDB server');
}
}
performCRUDOperations().catch(console.error);
MySQL Example (using the mysql module):
const mysql = require('mysql');
// MySQL connection configuration
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydatabase',
});
// Connect to MySQL server
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL server:', err);
return;
}
console.log('Connected to MySQL server');
// CRUD operations
// Create
connection.query('INSERT INTO mytable (name, age) VALUES (?, ?)', ['John', 30], (error, results) => {
if (error) {
console.error('Error creating record:', error);
return;
}
console.log('Record created:', results);
});
// Read
connection.query('SELECT * FROM mytable WHERE name = ?', ['John'], (error, results) => {
if (error) {
console.error('Error reading records:', error);
return;
}
console.log('Read result:', results);
});
// Update
connection.query('UPDATE mytable SET age = ? WHERE name = ?', [35, 'John'], (error, results) => {
if (error) {
console.error('Error updating record:', error);
return;
}
console.log('Record updated:', results);
});
// Delete
connection.query('DELETE FROM mytable WHERE name = ?', ['John'], (error, results) => {
if (error) {
console.error('Error deleting record:', error);
return;
}
console.log('Record deleted:', results);
});
// Disconnect from MySQL server
connection.end((err) => {
if (err) {
console.error('Error disconnecting from MySQL server:', err);
return;
}
console.log('Disconnected from MySQL server');
});
});
PostgreSQL Example (using the pg module):

const { Pool } = require('pg');
// PostgreSQL connection configuration
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'mydatabase',
password: 'password',
port: 5432,
});
// CRUD operations
// Create
async function createRecord() {
try {
const client = await pool.connect();
const query = 'INSERT INTO mytable (name, age) VALUES ($1, $2)';
const values = ['John', 30];
await client.query(query, values);
console.log('Record created');
client.release();
} catch (error) {
console.error('Error creating record:', error);
}
}
// Read
async function readRecords() {
try {
const client = await pool.connect();
const query = 'SELECT * FROM mytable WHERE name = $1';
const values = ['John'];
const result = await client.query(query, values);
console.log('Read result:', result.rows);
client.release();
} catch (error) {
console.error('Error reading records:', error);
}
}
// Update
async function updateRecord() {
try {
const client = await pool.connect();
const query = 'UPDATE mytable SET age = $1 WHERE name = $2';
const values = [35, 'John'];
await client.query(query, values);
console.log('Record updated');
client.release();
} catch (error) {
console.error('Error updating record:', error);
}
}
// Delete
async function deleteRecord() {
try {
const client = await pool.connect();
const query = 'DELETE FROM mytable WHERE name = $1';
const values = ['John'];
await client.query(query, values);
console.log('Record deleted');
client.release();
} catch (error) {
console.error('Error deleting record:', error);
}
}
// Perform CRUD operations
async function performCRUDOperations() {
try {
await createRecord();
await readRecords();
await updateRecord();
await deleteRecord();
} catch (error) {
console.error('Error:', error);
} finally {
await pool.end();
console.log('Disconnected from PostgreSQL server');
}
}
performCRUDOperations().catch(console.error);
In this PostgreSQL example, we create separate functions for each CRUD operation: createRecord()
, readRecords()
, updateRecord()
, and deleteRecord()
.
Each function establishes a connection to the PostgreSQL database using a connection pool, performs the corresponding SQL query, and logs the results or any errors encountered.
Finally, the performCRUDOperations()
function is called to execute the CRUD operations in a sequential manner.
It also handles the connection pool's termination using pool.end()
and logs the disconnection from the PostgreSQL server.
Remember to install the required modules for each database (e.g., npm install mongodb mysql pg
) and update the connection configurations (e.g., username, password, database name, etc.) to match your specific setup.

Learn more IT here
Comments
Post a Comment