Open In App

Mongoose Documents vs Models

Last Updated : 28 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Mongoose, a popular Node library, is widely used for interacting with MongoDB, a NoSQL database. Mongoose simplifies the process of working with MongoDB by providing an object data modeling (ODM) framework. In the Mongoose ecosystem, two key concepts are Documents and Models. In this article, we’ll delve into the distinctions between Mongoose Documents and Models, and how they contribute to building robust and scalable MongoDB-driven applications.

Mongoose Models:

In Mongoose, a Model serves as a blueprint for creating Documents. Models are defined using the mongoose.model method and a Schema. A Schema defines the structure of the documents within a collection, specifying the fields, types, and other constraints. Here’s a simple example of creating a Mongoose model:

Syntax:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: String,
email: String,
age: Number
});
const User = mongoose.model('User', userSchema);

Explanation:

  1. Require Mongoose: Import the Mongoose library.
  2. Define Schema: Create a Mongoose schema by specifying the fields and their data types. You can also include additional options like required for validation and default for default values.
  3. Create Model: Use the mongoose.model method to create a model based on the defined schema. The first argument is the singular name of the collection your model is for, and the second argument is the schema.
  4. Export Model: Export the model so that it can be used in other parts of your application.

Example: Here’s an example of how you might use this model in another file:

Javascript




const YourModel = require("./path/to/your/model");
 
// Create a new instance of the model
const instance = new YourModel({
    fieldName1: "some value",
    fieldName2: 42,
});
 
// Save the instance to the database
instance.save((error, savedInstance) => {
    if (error) {
        console.error(error);
    } else {
        console.log("Instance saved:", savedInstance);
    }
});


This is a basic example, and you can customize it based on your specific requirements. The Mongoose documentation (https://mongoosejs.com/docs/) is a valuable resource for more advanced features and options.

Mongoose Documents:

Documents, on the other hand, are instances of Models. They represent individual records within a collection and adhere to the structure defined by the associated Schema. Documents can be created and manipulated using the corresponding Model. Here’s an example of creating a new user Document using the User model:

Syntax:

const newUser = new User({
username: 'john_doe',
email: 'john@example.com',
age: 25
});
newUser.save()
.then(savedUser => {
console.log('User saved:', savedUser);
})
.catch(error => {
console.error('Error saving user:', error);
});

Example: In this snippet, a new user Document is created using the User model and saved to the MongoDB database using the save method.

Javascript




const mongoose = require('mongoose');
 
// Define a schemaconst mongoose = require("mongoose");
 
// Define a schema
const yourSchema = new mongoose.Schema({
    name: String,
    age: Number,
    email: String,
});
 
// Create a Mongoose model using the schema
const YourModel = mongoose.model("YourModel", yourSchema);
 
// Create a new document instance
const document = new YourModel({
    name: "John Doe",
    age: 30,
    email: "john@example.com",
});
 
// Save the document to the database
document.save((error, savedDocument) => {
    if (error) {
        console.error(error);
    } else {
        console.log("Document saved:", savedDocument);
    }
});
 
const yourSchema = new mongoose.Schema({
  name: String,
  age: Number,
  email: String,
});
 
// Create a Mongoose model using the schema
const YourModel = mongoose.model('YourModel', yourSchema);
 
// Create a new document instance
const document = new YourModel({
  name: 'John Doe',
  age: 30,
  email: 'john@example.com',
});
 
// Save the document to the database
document.save((error, savedDocument) => {
  if (error) {
    console.error(error);
  } else {
    console.log('Document saved:', savedDocument);
  }
});


Differences between Mongoose Documents and Models:

Mongoose Model

Mongoose Document

A Mongoose model is a constructor function that represents a collection in MongoDB.

A Mongoose document is an instance of a model that represents a single document in a MongoDB collection.

It is responsible for creating and querying documents in the database.

Documents are created using the new keyword with the model constructor function.

You define a Mongoose model by creating a schema, which defines the structure and data types of the documents in the collection.

Each document has its own properties and methods and represents a record in the database.

Models have static methods that allow you to perform operations at the collection level, such as finding, updating, and deleting documents.

Documents have instance methods that allow you to perform operations on a specific document, such as saving, updating, and deleting.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads