Mongoose
Mongoose is a popular MongoDB object modeling tool (ODM) for Node.js and Deno, designed for asynchronous environments. It provides a schema-based solution to model application data, offering powerful validation, querying, and middleware capabilities. The current stable version is 9.4.1, with frequent patch and minor releases addressing bug fixes and new features.
Common errors
-
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
cause Mongoose could not connect to the MongoDB server, likely because it is not running or is listening on a different address/port.fixEnsure your MongoDB instance is running and accessible at the specified connection URI (e.g., `mongodb://127.0.0.1:27017/`). -
ValidationError: User validation failed: name: Path `name` is required.
cause You attempted to save a document that is missing a required field, or a field failed schema validation rules.fixProvide values for all required fields as defined in your Mongoose Schema before saving the document. Check other validation rules like `minlength`, `maxlength`, `enum`, etc. -
CastError: Cast to ObjectId failed for value "invalid-id" at path "_id"
cause Mongoose attempted to cast an invalid value (e.g., a non-string or malformed string) into an `ObjectId` type, typically during a query for a document by its `_id`.fixEnsure that the value you are providing for `_id` or any other `ObjectId` field is a valid 24-character hexadecimal string or an actual `ObjectId` instance. -
MongooseError: Options cannot be null or undefined. Received: null
cause You passed `null` or `undefined` as an options object to a Mongoose method (e.g., `Model.find(query, null)`).fixProvide a valid options object (even an empty one `{}`) or omit the options parameter entirely if no options are needed. -
Cannot find module 'mongoose'
cause The `mongoose` package is not installed in your project's `node_modules` directory, or there's an issue with module resolution in an ESM context.fixInstall the package using `npm install mongoose`, `yarn add mongoose`, or `pnpm add mongoose`. If using ESM, ensure your `package.json` is configured correctly (e.g., `type: module`).
Warnings
- breaking Mongoose 9.x requires Node.js version 20.19.0 or higher.
- breaking Mongoose 9.0 introduced significant backwards-incompatible changes.
- deprecated The `document.getChanges()` method is deprecated in favor of `document.$getChanges()`.
- gotcha As of Mongoose 9.3.2, passing `null` or `undefined` as options to certain Mongoose methods will now throw an error.
- gotcha A fix for running setters on default values during upsert operations was reverted in 9.4.1. If you relied on this short-lived behavior, it will no longer apply.
Install
-
npm install mongoose -
yarn add mongoose -
pnpm add mongoose
Imports
- mongoose
import mongoose from 'mongoose';
Quickstart
import mongoose, { Schema, model } from 'mongoose';
async function main() {
// Replace with your MongoDB connection string
const uri = process.env.MONGO_URI ?? 'mongodb://127.0.0.1:27017/test';
try {
await mongoose.connect(uri);
console.log('Connected to MongoDB!');
interface IUser {
name: string;
email: string;
}
const UserSchema = new Schema<IUser>({
name: { type: String, required: true },
email: { type: String, required: true, unique: true }
});
const UserModel = model<IUser>('User', UserSchema);
// Create a new user
const newUser = new UserModel({
name: 'Alice Wonderland',
email: 'alice@example.com'
});
await newUser.save();
console.log('User saved:', newUser);
// Find a user
const foundUser = await UserModel.findOne({ email: 'alice@example.com' });
console.log('User found:', foundUser);
} catch (error) {
console.error('MongoDB connection or operation error:', error);
process.exit(1);
} finally {
await mongoose.disconnect();
console.log('Disconnected from MongoDB.');
}
}
main();