Connecting with Databases in Node.js

Persist data in your applications by connecting to NoSQL and SQL databases with the most popular Node.js libraries.

MongoDB with Mongoose (ODM)

Mongoose is an Object-Document Mapper (ODM) for MongoDB. It provides a schema-based solution to model your application data, offering type casting, validation, query building, and business logic hooks.

npm install mongoose

Connecting is straightforward. You define a schema that maps to a MongoDB collection and use a model to interact with it.

PostgreSQL with Sequelize (ORM)

Sequelize is a promise-based Node.js Object-Relational Mapper (ORM) for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It allows you to interact with your SQL database using JavaScript objects.

npm install sequelize pg pg-hstore

You define models that represent tables in your database. Sequelize then provides methods to create, read, update, and delete records without writing raw SQL queries.

PostgreSQL with Knex.js (Query Builder)

Knex.js is a "batteries-included" SQL query builder for the same databases as Sequelize. Unlike a full ORM, Knex gives you more control over the SQL, acting as a middle ground between raw SQL and a high-level ORM.

npm install knex pg

It's excellent for developers who are comfortable with SQL but want the convenience of a JavaScript-based query interface to prevent SQL injection and manage connections.

When to Use Each Tool

  • Mongoose: The standard choice for MongoDB. Use it when you need robust data modeling, validation, and middleware logic for a NoSQL database.
  • Sequelize: Best for relational databases when you want to abstract away SQL entirely and work with JavaScript objects and methods. It speeds up development significantly.
  • Knex.js: Perfect for relational databases when you want more control than an ORM provides. If you like writing SQL but want a safer, programmatic way to do it, choose Knex.

Practice Zone


Interactive Test 1: Match the Tool

Drag the library to its corresponding database type.

Arrastra en el orden correspondiente.


Arrastra las opciones:

Mongoose (ODM)
Sequelize (ORM)
Knex.js (Query Builder)

Completa el código:

MongoDB (NoSQL)______
PostgreSQL (SQL)______
PostgreSQL (SQL)______
Unlock with Premium

Interactive Test 2: Complete the Connection

Complete the connection snippets for each library.

Rellena los huecos en cada casilla.


// MongoDB with Mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/');

// PostgreSQL with Sequelize
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('postgres://:@example.com:5432/dbname');

// PostgreSQL with Knex.js
const knex = require('knex')({
  client: '',
  connection: { host: '127.0.0.1', database: 'myapp' }
});
Unlock with Premium

Practice Example: Mongoose Setup

Write the code to connect to a MongoDB database, define a 'User' schema with a 'name' field, and save one user.

* Write the code below. Correct characters will be shown in green and incorrect ones in red.

// 1. Connect to MongoDB using Mongoose const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/testdb') .then(() => console.log('MongoDB connected!')) .catch(err => console.error(err)); // 2. Define a schema and model const userSchema = new mongoose.Schema({ name: String }); const User = mongoose.model('User', userSchema); // 3. Create and save a new user const newUser = new User({ name: 'John Doe' }); newUser.save().then(() => console.log('User saved!'));
Unlock with Premium

Knowledge Check

Which library is an ORM for relational databases like PostgreSQL?


Unlock with Premium