Connecting and Querying MongoDB in Express

In the process of developing web applications, connecting to and querying a database is a crucial part. In this article, we will explore how to connect to and query a MongoDB database in an Express application. MongoDB is a popular choice for storing data in Node.js applications due to its flexibility and scalability.


Connecting MongoDB with Express:

To get started, we need to install the Mongoose package via npm and configure the connection to the MongoDB database.

npm install express mongoose

Here's an example of how to connect MongoDB with Express:

const mongoose = require('mongoose');
const express = require('express');
const app = express();

// Connect to the MongoDB database
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('Connected to MongoDB');
    // Continue writing routes and logic in Express
  .catch((error) => {
    console.error('Error connecting to MongoDB:', error);

// ... Other routes and logic in Express

app.listen(3000, () => {
  console.log('Server started');


Querying Data from MongoDB:

After successfully connecting to MongoDB, we can perform data queries within the Express application. Here's an example of querying data from MongoDB using Mongoose:

const mongoose = require('mongoose');

// Define the schema and model
const userSchema = new mongoose.Schema({
  name: String,
  age: Number

const User = mongoose.model('User', userSchema);

// Query data from MongoDB
User.find({ age: { $gte: 18 } })
  .then((users) => {
    console.log('List of users:', users);
    // Continue processing the returned data
  .catch((error) => {
    console.error('Error querying data:', error);

In the above example, we define a schema for the "User" object and use the model to perform data queries. Here, we query all users with an age greater than or equal to 18 and log the returned results.


Conclusion: In this article, we have explored how to connect to and query a MongoDB database in an Express application. Using MongoDB as the database solution for Node.js applications provides us with a flexible and powerful option. By utilizing Mongoose, we can easily perform data queries and build reliable web applications.