Error: Cannot find module 'mongoose'— Fixed [Complete Guide 2026]
⚡ Quickest Fix — 60 seconds
Navigate to your project and install mongoose:
cd your-project-folder
npm install mongooseThen connect to MongoDB in your entry file:
const mongoose = require('mongoose')
mongoose.connect(process.env.MONGODB_URI)
.then(() => console.log('MongoDB connected'))
.catch(err => console.error('Connection failed:', err.message))What Causes Cannot find module 'mongoose'?
Error: Cannot find module 'mongoose'
Require stack:
- /Users/you/projects/api/server.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:94:18)
at Object.<anonymous> (/Users/you/projects/api/server.js:3:19)mongoose is an npm package for connecting to and querying MongoDB. It is not built into Node.js and must be installed separately. This error means Node.js cannot find mongoose in your node_modules directory.
| Cause | Fix |
|---|---|
| mongoose was never installed | Fix 1 — npm install mongoose |
| Wrong directory — node_modules elsewhere | Fix 3 — cd to correct folder |
| Cloned repo — node_modules not committed | Fix 3 — npm install |
| Corrupted node_modules | Fix 4 — clean reinstall |
| Production — missing node_modules on server | Run npm install on server |
Install mongoose
Most common fixcd your-project-folder
npm install mongoose
# Verify it installed
ls node_modules | grep mongoose
# Check version
npm list mongooseAfter installing, mongoose should appear in your package.json dependencies:
{
"dependencies": {
"mongoose": "^8.2.0"
}
}Always run npm install from the directory containing package.json — not from a parent or child directory.
Connect to MongoDB Correctly
Complete working setup after installingInstalling mongoose only makes the module available. You still need to call mongoose.connect() with your MongoDB connection string to establish the database connection.
Local MongoDB
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/mydb')
.then(() => console.log('Connected to local MongoDB'))
.catch(err => console.error('Connection error:', err.message))MongoDB Atlas (cloud)
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/mydbrequire('dotenv').config()
const mongoose = require('mongoose')
mongoose.connect(process.env.MONGODB_URI)
.then(() => console.log('Connected to MongoDB Atlas'))
.catch(err => console.error('Connection error:', err.message))With connection event handlers
mongoose.connect(process.env.MONGODB_URI)
mongoose.connection.on('connected', () => {
console.log('Mongoose connected to MongoDB')
})
mongoose.connection.on('error', (err) => {
console.error('Mongoose connection error:', err)
})
mongoose.connection.on('disconnected', () => {
console.log('Mongoose disconnected')
})Never hardcode MongoDB credentials in source code. Always use process.env.MONGODB_URI from a .env file.
Wrong Directory or After Git Clone
node_modules missingIf you just cloned a repository, node_modules will not exist — it is never committed to git. Run npm install to recreate it.
# Correct workflow after cloning
git clone https://github.com/user/my-api.git
cd my-api
npm install # recreates node_modules
node server.js# Verify mongoose is in node_modules
ls node_modules | grep mongooseReinstall All Dependencies
Corrupted node_modulesrm -rf node_modules package-lock.json
npm installRemove-Item -Recurse -Force node_modules
Remove-Item package-lock.json
npm installDefine Schemas and Models Correctly
After installing and connecting — set up modelsAfter mongoose is installed and connected, here is the complete pattern for defining schemas and using models:
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Name is required'],
},
email: {
type: String,
required: [true, 'Email is required'],
unique: true,
lowercase: true,
},
createdAt: {
type: Date,
default: Date.now,
},
})
module.exports = mongoose.model('User', userSchema)const User = require('../models/User')
// Create user
const user = await User.create({ name: 'John', email: 'john@example.com' })
// Find all users
const users = await User.find()
// Find by ID
const user = await User.findById(req.params.id)
// Update
await User.findByIdAndUpdate(id, { name: 'Jane' }, { new: true })
// Delete
await User.findByIdAndDelete(id)mongoose with ES Modules
Using import/export syntaxIf your project uses ES Modules ("type": "module" in package.json), use import syntax instead of require:
import mongoose from 'mongoose'
import dotenv from 'dotenv'
dotenv.config()
await mongoose.connect(process.env.MONGODB_URI)
console.log('MongoDB connected')import mongoose from 'mongoose'
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true },
})
export default mongoose.model('User', userSchema)After Installing — Common Connection Errors
Once mongoose is installed, you may hit connection errors. Here is the most common ones and their quick fixes:
| Error | Cause & Fix |
|---|---|
| ECONNREFUSED 127.0.0.1:27017 | MongoDB not running locally — start it: brew services start mongodb-community |
| Authentication failed | Wrong username/password in connection string — check Atlas Database Access |
| ServerSelectionTimeout | IP not whitelisted in Atlas Network Access — add your IP |
| Connection string invalid | Missing +srv for Atlas — use: mongodb+srv://user:pass@cluster.mongodb.net/db |
How to Prevent This Error
- Add mongoose to package.json with npm install mongoose
- Store MongoDB URI in .env — never hardcode credentials
- Always run npm install after cloning a repository
- Add node_modules to .gitignore
- Commit package.json and package-lock.json to git
- In production deployments, ensure npm install runs before starting the app
- For CI/CD, use npm ci instead of npm install for faster, deterministic installs
Frequently Asked Questions
How do I install mongoose in Node.js?+−
Cannot find module mongoose after npm install?+−
How do I connect mongoose to MongoDB Atlas?+−
Mongoose connected but queries not working?+−
Which mongoose version should I use?+−
Cannot find module mongoose in production?+−
Need Expert Help?
We Build Production-Grade Node.js & MongoDB Apps
Softplix is a full-stack development agency. Need help with MongoDB architecture or a complex Node.js backend? We can help.
Talk to an Engineer