Node.jsMongoDBError Fix2026 Updated

Error: Cannot find module 'mongoose'— Fixed [Complete Guide 2026]

January 20265 min readNode.js · MongoDB · All OS

⚡ Quickest Fix — 60 seconds

Navigate to your project and install mongoose:

terminal
cd your-project-folder
npm install mongoose

Then connect to MongoDB in your entry file:

server.js
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'?

Terminal Error
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.

CauseFix
mongoose was never installedFix 1 — npm install mongoose
Wrong directory — node_modules elsewhereFix 3 — cd to correct folder
Cloned repo — node_modules not committedFix 3 — npm install
Corrupted node_modulesFix 4 — clean reinstall
Production — missing node_modules on serverRun npm install on server
1

Install mongoose

Most common fix
1 min
terminal
cd your-project-folder
npm install mongoose

# Verify it installed
ls node_modules | grep mongoose

# Check version
npm list mongoose

After installing, mongoose should appear in your package.json dependencies:

package.json
{
  "dependencies": {
    "mongoose": "^8.2.0"
  }
}

Always run npm install from the directory containing package.json — not from a parent or child directory.

2

Connect to MongoDB Correctly

Complete working setup after installing
3 min

Installing 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

server.js
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)

.env
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/mydb
server.js
require('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

server.js
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.

3

Wrong Directory or After Git Clone

node_modules missing
1 min

If you just cloned a repository, node_modules will not exist — it is never committed to git. Run npm install to recreate it.

terminal
# Correct workflow after cloning
git clone https://github.com/user/my-api.git
cd my-api
npm install          # recreates node_modules
node server.js
terminal
# Verify mongoose is in node_modules
ls node_modules | grep mongoose
4

Reinstall All Dependencies

Corrupted node_modules
3 min
macOS / Linux
rm -rf node_modules package-lock.json
npm install
Windows PowerShell
Remove-Item -Recurse -Force node_modules
Remove-Item package-lock.json
npm install
5

Define Schemas and Models Correctly

After installing and connecting — set up models
3 min

After mongoose is installed and connected, here is the complete pattern for defining schemas and using models:

models/User.js
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)
routes/users.js
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)
6

mongoose with ES Modules

Using import/export syntax
2 min

If your project uses ES Modules ("type": "module" in package.json), use import syntax instead of require:

server.js (ES Module)
import mongoose from 'mongoose'
import dotenv from 'dotenv'

dotenv.config()

await mongoose.connect(process.env.MONGODB_URI)
console.log('MongoDB connected')
models/User.js (ES Module)
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:

ErrorCause & Fix
ECONNREFUSED 127.0.0.1:27017MongoDB not running locally — start it: brew services start mongodb-community
Authentication failedWrong username/password in connection string — check Atlas Database Access
ServerSelectionTimeoutIP not whitelisted in Atlas Network Access — add your IP
Connection string invalidMissing +srv for Atlas — use: mongodb+srv://user:pass@cluster.mongodb.net/db

How to Prevent This Error

Frequently Asked Questions

How do I install mongoose in Node.js?+
Run npm install mongoose in your project directory. Then require it: const mongoose = require('mongoose') and connect with mongoose.connect(process.env.MONGODB_URI). Always handle connection errors with .catch().
Cannot find module mongoose after npm install?+
Verify you are in the correct project directory. Run ls node_modules | grep mongoose to confirm it installed. If missing, run npm install mongoose again from the folder containing package.json.
How do I connect mongoose to MongoDB Atlas?+
Set your connection string in .env: MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/dbname. Then call mongoose.connect(process.env.MONGODB_URI) in your app. Make sure your IP is whitelisted in Atlas Network Access.
Mongoose connected but queries not working?+
Make sure you are running queries after the connection is established. Use await mongoose.connect() or check mongoose.connection.readyState === 1 before querying.
Which mongoose version should I use?+
Use the latest version: npm install mongoose@latest. Mongoose 7+ and 8+ require Node.js 14+ and MongoDB 4.4+. Check npm info mongoose version for the current stable release.
Cannot find module mongoose in production?+
Your production server is missing node_modules. Make sure your deployment pipeline runs npm install before starting the app. Check that mongoose is in dependencies (not devDependencies) in package.json.

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