Open In App

Mongoose Documents

Last Updated : 22 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB and Node.js, making it easier to interact with MongoDB databases. It provides a structured way to handle data, perform validation, and manage documents in MongoDB with ease. In this article, we will explain Mongoose Documents, how they work, and explore various methods to handle them effectively in your Node.js application.

What Are Mongoose Documents?

In Mongoose, a Document represents a single instance of a model. It is essentially a MongoDB document that is mapped to a Mongoose model. Each instance of a model corresponds to a document in the database, and you can perform CRUD (Create, Read, Update, Delete) operations on these documents. For instance, if you define a Mongoose model for "User", every time you create a new "User" instance, it becomes a Mongoose Document. Documents in Mongoose have properties and methods that help you manage and manipulate data efficiently.

Key Features of Mongoose Documents:

  • One-to-One Mapping: Each Mongoose document maps to a single MongoDB document.
  • CRUD Operations: Documents support a wide range of database operations like save(), find(), update(), and delete().
  • Schema Validation: Documents automatically validate data based on the defined schema before saving to MongoDB.
  • Methods and Virtuals: Mongoose documents can have instance methods and virtual fields that provide additional functionality.

Mongoose Document Operations

The following functions are used on the Document of the Mongoose:

1. Retrieving Mongoose Documents

To retrieve documents from the MongoDB database, Mongoose provides several query methods like findOne() and findById(). These methods allow you to fetch documents based on specific criteria.

const doc = await MyModel.findById(myid);

2. Saving Mongoose Documents

Once you create or modify a document, you need to save it to the database. Mongoose provides the save() method, which is asynchronous and must be awaited.

await doc.save()

3. Updating Mongoose Documents

You can update Mongoose documents using either the save() method or by performing direct updates through queries like findByIdAndUpdate()

await MyModel.deleteOne({ _id: doc._id });

doc.firstname = 'gfg';
await doc.save();

Updating using queries: The document can be updated by the queries without calling the save function.

await MyModel.findByIdAndUpdate(myid,{firstname: 'gfg'},function(err, docs){});

4. Validating Mongoose Documents

Before saving documents to MongoDB, Mongoose validates them based on the schema definitions. You can explicitly trigger validation using the validate() method.

const schema = new Schema({ name: String, age: Number});
const Person = mongoose.model('Person', schema);

let p1 = new Person({ name: 'gfg', age: 'bar' });
// Validation will be failed
await p1.validate();

let p2 = new Person({ name: 'gfg', age: 20 });
// Validation will be successful
await p2.validate();

5. Overwriting Mongoose Documents

You can overwrite an entire document with new data using the overwrite() method.

const doc = MyModel.findById(myid);
doc.overwrite({ fullname: 'gfg' });
await doc.save();

Example 1: Creating, Saving, and Updating Mongoose Documents

In the following example, we will create a model, save it to the database and then retrieve it, update the document and then save it using mongoose. We will be using node.js for this example. Node.js and npm should be installed.

Step 1: Initialize the Project

Create a folder and initialize it:

npm init

Step 2: Install mongoose in the project.

npm i mongoose

The project structure is as follows:

 

Step 3: Create a Model and Connect to MongoDB

Create a file called index.js. Inside the index.js, connect to your MongoDB database and define a simple User model.

index.js

const mongoose = require("mongoose");

// Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {});

// User model
const User = mongoose.model("User", {
name: { type: String },
age: { type: Number },
});

// Creating a new document
async function start() {
let user1 = new User({
name: "Geeks",
age: 20,
});
user1.save().then(async (doc) => {
if (doc) {
console.log("The document is saved successfully");
console.log(doc._id);
}
});
let user2 = await User.findOne({ name: "Geeks" });
user2.name = "GeeksforGeeks ";
user2.save().then(async (doc) => {
if (doc) {
console.log("The document is updated successfully");
console.log(doc._id);
}
});
}
start();

Step 4: Run the Application

Now run the code using the following command in the Terminal/Command Prompt to run the file.

node index.js

Output:

And the document in the MongoDB is as follows:

Example 2: Validating Mongoose Documents

In this example, we will try to validate a document explicitly by using "validate" method of mongoose schema. Mongoose internally calls this method before saving a document to the DB.

Step 1: Update the index.js File

We will update the index.js file to include schema validation.

const mongoose = require('mongoose')

// Database connection
mongoose.connect('mongodb://localhost:27017/query-helpers', {
dbName: 'event_db',
useNewUrlParser: true,
useUnifiedTopology: true
}, err => err ? console.log(err) : console.log('Connected to database'));

const personSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
age: {
type: Number,
min: 18
}
});

const Person = mongoose.model('Person', personSchema);

const person1 = new Person({ name: 'john', age: 'nineteen' });

(async () => {
await person1.validate();
})();

Step 2: Run the application

If the validation fails, Mongoose will throw an error and prevent the document from being saved to the database.

node index.js

Output:

Conclusion

Mongoose documents are essential in modeling and manipulating data within a MongoDB database in a Node.js application. They provide a structured approach to handle CRUD operations, data validation, and more. With this article, you now understand the core concepts of Mongoose documents and how to use them effectively. Whether you need to create, save, update, or validate documents, Mongoose simplifies these tasks, allowing you to focus on building powerful applications.


Next Article

Similar Reads