Skip to main content

Creating a Model in Mongoose

Creating a Model in Mongoose | Rustcode

Creating a Model in Mongoose

In Mongoose, a Model is a compiled representation of your Schema. It provides an interface to create, read, update, and delete documents from a MongoDB collection, following the structure defined in the schema. This article explains how to create models, their usage, and best practices.


What is a Mongoose Model?

  • A Model in Mongoose is a constructor compiled from a schema definition.
  • It allows creating instances of documents that follow the schema's structure and provides methods to interact with the MongoDB collection.
  • Models provide powerful APIs for CRUD operations and querying.

How to Create a Model

Use mongoose.model() by passing the name and schema:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({
  name: String,
  email: String,
  age: Number
});

const User = mongoose.model('User', userSchema);
  • The first argument ('User') is the singular name of the collection your model represents.
  • The second argument is the schema that defines the structure.

Collection Name and Model

  • Mongoose automatically looks for the plural, lowercased version of your model name to find the MongoDB collection (e.g., User → collection users).
  • You can override the collection name explicitly by passing a third argument:
const User = mongoose.model('User', userSchema, 'myUsersCollection');

Using Models to Work with Documents

Models provide methods to create, retrieve, update, and delete documents.

// Create a new user
const newUser = new User({
  name: 'Alice',
  email: 'alice@example.com',
  age: 30
});

newUser.save()
  .then(user => console.log('User saved:', user))
  .catch(err => console.error('Error saving user:', err));

// Query users
User.find({ age: { $gte: 18 } })
  .then(users => console.log('Adult users:', users))
  .catch(err => console.error(err));

Difference between Schema and Model

  • Schema: Defines the document structure, fields, validations, and middleware.
  • Model: Compiled from the schema, used for creating and querying documents in the database.
  • Schemas are blueprints; models are classes based on those blueprints.

Quick Reference Table

Concept Description Usage
Schema Defines the structure and validation rules for documents Blueprint for data
Model Constructor compiled from a schema to interact with MongoDB Create/read/update/delete documents
mongoose.model(name, schema, [collection]) Creates a model for a schema Initialization of the Model

Best Practices

  • Use singular, capitalized names for models (e.g., User, Product).
  • Keep schema definitions separate and import them when creating models.
  • Explicitly specify collection names if your MongoDB collection is non-standard.
  • Use model methods and statics for encapsulating database logic.
  • Reuse models via mongoose.model() to avoid recompilation errors.

Conclusion

Creating a model in Mongoose is the bridge between your schema definitions and the MongoDB collections. Models empower you to manage your data with an intuitive API while ensuring consistency with your defined schemas. Understanding models is essential for efficient MongoDB interaction in Node.js applications.

Comments