Mongoose (Node.js)

Mongoose is an Object Data Modeling (ODM) library for MongoDB in Node.js. It defines schemas for your documents, gives models a clean query API, and adds validation and middleware on top of the MongoDB driver.

Node.js

MongoDB stores schemaless JSON-like documents, which is flexible but error-prone. Mongoose adds structure: you define a Schema describing each field's type and rules, compile it into a Model, and then use that model to create, query, update, and delete documents with a friendly API and built-in validation.

A typical flow is connect with mongoose.connect(uri), define a schema (new mongoose.Schema({...})), make a model (mongoose.model('User', schema)), then call methods like User.create(), User.find(), User.findById(), and doc.save(). These return Promises, so you use them with async/await.

Mongoose also provides schema-level validation, default values, virtuals (computed properties), middleware/hooks (e.g. hash a password before save), and population (joining referenced documents). For SQL databases you would instead use an ORM like Prisma or Sequelize.

Syntax

const User = mongoose.model("User", schema);
await User.find();

Examples

JavaScript

const mongoose = require("mongoose");
await mongoose.connect(process.env.MONGO_URI);

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, unique: true },
});
const User = mongoose.model("User", userSchema);

await User.create({ name: "Ana", email: "[email protected]" });

Learn it in a lesson

See also

Back to the Dictionary