The "Cannot find module 'mongoose'" error occurs when Node.js cannot locate the mongoose package in your project. This typically happens when mongoose is not installed, was installed in the wrong location, or when the node_modules directory is missing or corrupted. The error prevents your application from importing mongoose for MongoDB operations.
The "Cannot find module 'mongoose'" error is a Node.js module resolution error that occurs when your application tries to import or require the mongoose package, but Node.js cannot locate it in the expected directories. Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js that provides a schema-based solution for modeling application data. When you use `require('mongoose')` or `import mongoose from 'mongoose'`, Node.js searches for the package in several locations: 1. The local `node_modules` directory in your project root 2. Parent directories' `node_modules` folders (walking up the tree) 3. Global `node_modules` directory (system-wide installations) If mongoose is not found in any of these locations, Node.js throws this error. This is a dependency resolution issue, not a MongoDB database error. Common scenarios where this error appears: - **Fresh project clone**: Repository cloned without running npm install - **Missing package.json entry**: mongoose not listed in dependencies - **Corrupted node_modules**: Dependencies installed incorrectly - **Wrong working directory**: Running scripts from incorrect location - **Global vs local installation**: Mongoose installed globally when local installation needed - **Package manager mismatch**: Mixing npm, yarn, and pnpm without proper lockfiles
The most common fix is to install mongoose locally in your project:
# Using npm
npm install mongoose
# Using yarn
yarn add mongoose
# Using pnpm
pnpm add mongooseVerify installation succeeded:
# Check that mongoose folder exists
ls node_modules/mongoose
# Verify package.json was updated
cat package.json | grep mongooseExpected output in package.json:
{
"dependencies": {
"mongoose": "^9.0.0"
}
}If you have a package.json with mongoose already listed:
# Install all dependencies
npm install
# This reads package.json and installs everythingEnsure you are running your Node.js application from the project root where package.json and node_modules are located:
# Check current directory
pwd
# List files to confirm you're in project root
ls -la
# Should see: package.json, node_modules/, etc.
# If in wrong directory, navigate to project root
cd /path/to/your/projectTest if mongoose is accessible:
# Open Node REPL from project root
node
# Try requiring mongoose
> require('mongoose')
# Should return mongoose object, not an error
# Exit REPL
> .exitCommon mistake - running scripts from subdirectories:
# Wrong (from subdirectory)
cd src/
node app.js # Cannot find module 'mongoose'
# Correct (from project root)
cd /path/to/project
node src/app.js # WorksIf mongoose is installed but still not found, perform a clean reinstall:
# Remove node_modules and lock files
rm -rf node_modules
rm package-lock.json # or yarn.lock or pnpm-lock.yaml
# Clear npm cache
npm cache clean --force
# Reinstall all dependencies
npm installFor yarn users:
# Remove dependencies
rm -rf node_modules
rm yarn.lock
# Clear yarn cache
yarn cache clean
# Reinstall
yarn installFor pnpm users:
# Remove dependencies
rm -rf node_modules
rm pnpm-lock.yaml
# Clear pnpm cache
pnpm store prune
# Reinstall
pnpm installVerify the installation:
# Check mongoose version
npm list mongoose
# Should show something like:
# [email protected] /path/to/project
# └── [email protected]If mongoose is not listed in your package.json, add it manually and install:
Check package.json:
cat package.jsonIf mongoose is missing from dependencies, add it:
{
"name": "your-project",
"version": "1.0.0",
"dependencies": {
"mongoose": "^9.0.0"
}
}Or use the save flag to install and add automatically:
# Install and save to package.json
npm install --save mongoose
# Or shorter form (--save is default in npm 5+)
npm install mongooseFor specific version:
# Install specific version
npm install [email protected]
# Install specific major version (latest 9.x.x)
npm install mongoose@^9.0.0
# Install latest version
npm install mongoose@latestAfter adding, commit package.json:
git add package.json package-lock.json
git commit -m "Add mongoose dependency"Verify your code is correctly importing mongoose:
CommonJS (require) - correct:
// Correct
const mongoose = require('mongoose');
// Incorrect - typo
const mongoose = require('mongose'); // Missing 'o'
// Incorrect - wrong package
const mongoose = require('mongodb'); // This is the MongoDB driver, not mongooseES6 Modules (import) - correct:
// Correct
import mongoose from 'mongoose';
// Also correct
import * as mongoose from 'mongoose';
// Incorrect - check spelling
import mongoose from 'mongoosee';If using TypeScript:
// Install type definitions
npm install --save-dev @types/mongoose
// Import in TypeScript
import mongoose from 'mongoose';
// or
import * as mongoose from 'mongoose';Check package.json type setting:
{
"type": "module" // If set, use ES6 imports
// If not set or "type": "commonjs", use require()
}Verify in your code files:
# Search for mongoose imports in your project
grep -r "require.*mongoose" .
grep -r "import.*mongoose" .If mongoose was installed globally instead of locally, reinstall it locally:
Check global installations:
# List global packages
npm list -g --depth=0
# If mongoose appears here, it's installed globally (wrong)Uninstall global mongoose (optional):
npm uninstall -g mongooseInstall mongoose locally (required):
# Make sure you're in project root
cd /path/to/your/project
# Install locally
npm install mongoose
# Verify local installation
ls node_modules/ | grep mongooseWhy global installation doesn't work:
- require('mongoose') searches local node_modules first
- Global packages are only for CLI tools, not application dependencies
- Each project should have its own local dependencies
Correct structure:
your-project/
├── node_modules/
│ ├── mongoose/ ← Local installation (correct)
│ └── ...
├── package.json
├── package-lock.json
└── src/
└── app.jsTest local import:
// In your app.js
const mongoose = require('mongoose');
console.log('Mongoose version:', mongoose.version);Understanding Node.js Module Resolution:
Node.js follows a specific algorithm to locate modules when you use require() or import:
1. Core Modules: First checks if it's a built-in Node.js module (fs, path, etc.)
2. File/Path Modules: If starts with './', '../', or '/', treats as file path
3. node_modules Resolution: Searches for module in node_modules directories:
- ./node_modules/mongoose
- ../node_modules/mongoose
- ../../node_modules/mongoose
- (continues up directory tree to root)
4. Global Modules: Finally checks global node_modules directory
Debugging Module Resolution:
# Enable Node.js debug mode to see module resolution
NODE_DEBUG=module node app.js
# This shows every path Node.js searches for modulesCheck Node.js module paths:
// In Node.js REPL or script
console.log(module.paths);
// Shows all directories Node.js will search
// Example output:
// [
// '/path/to/project/node_modules',
// '/path/to/node_modules',
// '/path/node_modules',
// '/node_modules',
// '/usr/local/lib/node_modules'
// ]Package Manager Specific Issues:
npm workspaces/monorepos:
// In root package.json
{
"workspaces": ["packages/*"]
}Each workspace needs its own mongoose installation or use workspace hoisting.
pnpm strict mode:
pnpm uses symlinks and stricter module resolution. Ensure mongoose is in dependencies:
# Check pnpm links
pnpm list mongoose
# If missing from current package
pnpm add mongooseyarn Plug'n'Play (PnP):
Yarn PnP changes module resolution. Check .pnp.cjs file and ensure mongoose is listed:
# Verify PnP setup
yarn dlx @yarnpkg/doctor
# If issues, disable PnP temporarily
echo 'nodeLinker: node-modules' >> .yarnrc.yml
yarn installTypeScript Configuration:
When using TypeScript, ensure proper module resolution:
// tsconfig.json
{
"compilerOptions": {
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}Docker/Container Considerations:
When building Docker images, ensure dependencies are installed:
FROM node:18
WORKDIR /app
# Copy package files first
COPY package*.json ./
# Install dependencies in container
RUN npm ci --only=production
# Then copy application code
COPY . .
CMD ["node", "app.js"]Common pitfall - copying node_modules from host:
# Wrong - don't do this
COPY . . # This copies host's node_modules
# Correct - install in container
COPY package*.json ./
RUN npm install
COPY . .CI/CD Pipeline Issues:
Ensure your CI/CD pipeline installs dependencies:
# Example GitHub Actions
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci # Use 'npm ci' for deterministic installs
- name: Run tests
run: npm testPerformance Optimization:
Use npm ci for faster, deterministic installs in production/CI:
# npm ci vs npm install
npm ci # Faster, requires package-lock.json, deletes node_modules first
npm install # Slower, updates package-lock.json if neededTroubleshooting Checklist:
1. ✅ package.json exists and contains mongoose in dependencies
2. ✅ node_modules/mongoose directory exists
3. ✅ Running from project root directory
4. ✅ No typos in require/import statement
5. ✅ npm install completed without errors
6. ✅ No version conflicts in package-lock.json
7. ✅ Not mixing package managers (npm/yarn/pnpm)
8. ✅ Node.js version compatible with mongoose version
Mongoose Version Compatibility:
Check Node.js version compatibility:
# Check Node.js version
node --version
# Mongoose 9.x requires Node.js 16.20.1+
# Mongoose 8.x requires Node.js 14.20.1+
# Mongoose 7.x requires Node.js 14.0.0+If you need a specific mongoose version for Node.js compatibility:
# Install specific version
npm install [email protected]unknown operator: $invalidOperator
How to fix "unknown operator: $invalidOperator" in MongoDB
StaleShardVersion: shard version mismatch
How to fix "StaleShardVersion: shard version mismatch" in MongoDB
MongoOperationTimeoutError: Operation timed out
How to fix "MongoOperationTimeoutError: Operation timed out" in MongoDB
MongoServerError: PlanExecutor error during aggregation :: caused by :: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting. Aborting operation.
How to fix "QueryExceededMemoryLimitNoDiskUseAllowed" in MongoDB
MissingSchemaError: Schema hasn't been registered for model
How to fix "MissingSchemaError: Schema hasn't been registered for model" in MongoDB/Mongoose