Mongoose

9.4.1 · active · verified Sat Apr 18

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a MongoDB database, define a simple Mongoose schema and model, create a new document, save it, and then query for it.

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();

view raw JSON →