Get Data from MongoDB in Node.js

Mateen Kiani

Mateen Kiani

Published on Thu Jul 10 2025·5 min read

get-data-from-mongodb-in-node.js

Working with MongoDB in Node.js has become a standard for modern web apps, powering everything from social platforms to real‐time analytics. Yet many developers focus on query methods and overlook connection pooling and its impact on performance. But have you considered how connection pooling affects the speed and reliability of fetching data from your database?

Optimizing your pool settings and understanding driver internals can smooth data retrieval, avoid bottlenecks, and reduce errors. By mastering this aspect, you can make informed decisions, deliver faster responses, and prevent unwanted surprises in production.

Setup Database Connection

Connecting to MongoDB is the first step in retrieving data. Here is how to set it up in Node.js:

  1. Install the MongoDB driver or the ODM of your choice:
    • For the native driver run npm install mongodb
  2. Initialize the MongoClient with your connection URL.
  3. Use the client to connect and access your database.
const { MongoClient } = require('mongodb')
const uri = 'mongodb://localhost:27017'
async function connectDb() {
const client = new MongoClient(uri, { useUnifiedTopology: true })
await client.connect()
return client.db('testDb')
}

Tip: Use a central module to export a single instance of your db connection. You can also refer to set up your Node.js project for project structure ideas.

Define Data Schema

MongoDB is schemaless, but defining a schema in your code helps maintain consistency. Mongoose is a popular ODM that adds schema support:

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/testDb')
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number
})
const User = mongoose.model('User', userSchema)

This schema enforces field types and adds built‐in validation. When you call User.find, Mongoose casts query values to match schema types. Schemas also support indexes and virtuals, which can speed up queries and shape returned data.

Basic Data Queries

Fetching data begins with simple queries. The native driver and Mongoose share similar methods:

// Native driver example
async function getAllUsers(db) {
return db.collection('users').find().toArray()
}
// Mongoose example
async function getAllUsersMongoose() {
return User.find()
}

Common methods:

  • find(): returns a cursor or promise with all matching documents
  • findOne(): returns the first match or null
  • findOneAndUpdate(): atomically updates and returns the document

Tip: Always call toArray on cursors to get a plain array in the native driver.

Advanced Query Techniques

Once you have the basics, you can refine data retrieval:

  • Projection: select only needed fields
  • Sorting: order results by one or more fields
  • Limiting: fetch a subset for pagination
async function getRecentUsers(db) {
return db.collection('users')
.find({}, { projection: { name: 1, email: 1 } })
.sort({ createdAt: -1 })
.limit(10)
.toArray()
}

Key operators:

OperatorPurpose
$gtGreater than
$ltLess than
$inMatches any in an array
$regexPattern matching

Using these techniques helps you return only the data you need in the order you want.

Handling Async Calls

Node.js supports callbacks, promises, and async/await. Modern code typically uses async/await for clarity:

async function fetchUsers() {
try {
const db = await connectDb()
const users = await db.collection('users').find().toArray()
console.log(users)
} catch (err) {
console.error(err)
}
}

Async/await flattens nested callbacks and makes error handling straightforward. If you prefer callbacks or streams, you can still mix approaches. Just remember to close the client when done:

await client.close()

Error Handling Tips

Robust error handling ensures your app remains stable:

  • Validate connection strings and handle connection errors
  • Wrap queries in try/catch blocks
  • Log errors with context
  • Use timeouts for long-running queries

Pro tip: Follow general JavaScript error handling best practices to avoid uncaught exceptions.

By anticipating common failures, you can retry operations or return meaningful messages to clients.

Optimizing Performance

To speed up data retrieval:

  • Create indexes on frequently queried fields
  • Use connection pooling settings (maxPoolSize)
  • Cache hot data when possible
  • Avoid unbounded queries without limits
const client = new MongoClient(uri, { maxPoolSize: 20 })

Monitoring tools like database profiler can reveal slow queries. Regularly review and adjust indexes as your data grows.

Conclusion

Retrieving data from MongoDB in Node.js is more than calling find or findOne. It's about understanding how connections, schemas, queries, and async calls work together to build reliable apps. Starting with a clean connection setup, you can enforce structure with schemas and optimize query results. Whether you use the native driver or Mongoose, mastering projection, sorting, and pagination keeps your endpoints lean and responsive. Proper async/await usage clarifies your code flow, and robust error handling prevents crashes in production.

By weaving these practices into your development process, you not only fetch data—you shape a fast, stable, and maintainable data layer. Set up reusable modules, add monitoring early, and revisit your indexes regularly. With these tools, you’ll turn database operations from a liability into a competitive advantage. Ready to commit code? Connect to MongoDB and fetch your first dataset today, knowing you have the patterns to handle growth. Share your feedback or questions in your team discussions or on GitHub issues to keep improving your data access strategy. Stay curious, keep monitoring, and adjust as your app evolves.


Mateen Kiani
Mateen Kiani
kiani.mateen012@gmail.com
I am a passionate Full stack developer with around 3 years of experience in MERN stack development and 1 year experience in blockchain application development. I have completed several projects in MERN stack, Nextjs and blockchain, including some NFT marketplaces. I have vast experience in Node js, Express, React and Redux.