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.
Similar Reads
Mongoose Tutorial Mongoose is a popular ODM (Object Data Modeling) library for MongoDB and Node.js that simplifies database interactions by providing a schema-based solution to model application data. It is widely used to build scalable, structured, and efficient database-driven applications.Built on MongoDB for seam
6 min read
Mongoose Schemas
Mongoose Schemas Creating a ModelMongoose is one of the most popular Object Data Modeling (ODM) libraries for MongoDB, providing schema-based solutions to model our application's data. This allows us to define the structure of documents within a MongoDB collection, including validation, typecasting, and other powerful features that
5 min read
Mongoose Schemas and IndexesMongoose is a powerful Object Data Modeling (ODM) library for MongoDB in a Node.js environment. It provides a straightforward way to interact with MongoDB, including features like schema definition, model creation, and database query handling. One key feature of Mongoose is its ability to create and
5 min read
Mongoose Schemas Instance methodsMongoose is a powerful Object Data Modeling (ODM) library for MongoDB, designed to work in a Node.js environment. One of the key features of Mongoose is its ability to define instance methods on schema objects, which allow you to perform operations on individual documents. This guide will explore Mo
5 min read
Mongoose Schemas IdsMongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose automatically adds an _id property of type ObjectId to a document when it gets created. This can be overwritten with a custom id as well, but note that without an id, mongoose doesn't allow us to save or create a
2 min read
Mongoose Schemas VirtualsVirtuals are a powerful feature in Mongoose that allow us to add attributes to documents without actually storing them in the database. These properties can be dynamically calculated based on other fields, making it easier to manage and manipulate your data. In this comprehensive article, weâll dive
6 min read
Mongoose Schemas AliasesMongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schemas Aliases help in converting a short property name in the database into a longer, more verbal, property name to enhance code readability. Creating node application And Installing Mongoose: Step 1: Create a
2 min read
Mongoose Schemas With ES6 ClassesMongoose is a MongoDB object modeling and handling for a node.js environment. To load Mongoose schema from an ES6 Class, we can use a loadClass() method which is provided by Mongoose Schema itself. By using loadClass() method: ES6 class methods will become Mongoose methodsES6 class statics will bec
2 min read
Mongoose Schemas Query HelpersMongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schema Query Helpers are like instance methods for Mongoose queries. These query helpers can be used to filter out mongoose query results or perform additional operations on the existing result. Creating node appl
3 min read
Mongoose SchemaTypes
Mongoose Documents
Mongoose Queries
Mongoose QueriesMongoose is a powerful object modeling tool for MongoDB and Node.js. It provides a schema-based solution to model your data, simplifying interactions with MongoDB databases. Mongoose queries are essential for performing CRUD (Create, Read, Update, Delete) operations, making them indispensable for an
7 min read
Mongoose deleteMany() FunctionThe deleteMany() function is employed to remove all documents meeting specified conditions from a collection. Unlike the remove() function, deleteMany() deletes all matching documents without considering the single option. This method is essential for Node.js developers working with Mongoose, as it
4 min read
Mongoose Queries Model.replaceOne() FunctionThe Queries Model.replaceOne() function of the Mongoose API is used to replace an existing document with the given document. It replaces only the first document that is returned in the filter. Syntax: Model.replaceOne( filter, doc, options, callback ) Parameters: It accepts the following 4 parameter
3 min read
Find() Method in MongooseThe Mongoose find() method is one of the most widely used methods for querying MongoDB collections in Node.js. It provides a flexible and powerful way to fetch data from your MongoDB database. In this article, we will explore the find() method in detail, its syntax, parameters, and how to implement
5 min read
FindById Method in MongooseThe findById() method in Mongoose is one of the most commonly used methods for retrieving a document by its unique identifier (_id) in a MongoDB collection. This article will cover everything we need to know about how to use the findById() method, including syntax, examples, installation, and troubl
4 min read
Mongoose QueriesModel.findByIdAndDelete() MethodThe Mongoose Queries findByIdAndUpdate() method is used to search for a matching document, and delete it. It then returns the found document (if any) to the callback. This function uses this function with the id field. Installation of Mongoose Module: Step 1. You can visit the link to Install the mo
4 min read
Mongoose findByIdAndRemove() FunctionMongoDB is the most used cross-platform, document-oriented database that provides, high availability, high performance, and easy scalability. MongoDB works on the concept of collecting and documenting the data. findByIdAndRemove() stands proud as a convenient way to discover a file by its specific i
2 min read
Mongoose QueriesModel.findByIdAndDelete() MethodThe Mongoose Queries findByIdAndUpdate() method is used to search for a matching document, and delete it. It then returns the found document (if any) to the callback. This function uses this function with the id field. Installation of Mongoose Module: Step 1. You can visit the link to Install the mo
4 min read
FindOne() Method in MongooseThe findOne() method in Mongoose is one of the most commonly used functions for querying data from a MongoDB database. It provides a simple and efficient way to retrieve a single document that matches a specified query condition. This article will explore how to use the findOne() method, explain its
5 min read
Mongoose findOneAndDelete() FunctionThe findOneAndDelete() function in Mongoose is an efficient and commonly used method to find a document based on a specified filter and delete it from a MongoDB collection. This method simplifies the process of removing documents and is a key tool for developers working with Node.js and MongoDB. In
5 min read
Mongoose | findOneAndRemove() FunctionThe findOneAndRemove() function is used to find the element according to the condition and then remove the first matched element. Installation of mongoose module:You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongooseAfter installin
2 min read
Mongoose | findOneAndReplace() FunctionWhen working with MongoDB in Node.js, Mongoose is an essential tool for schema-based modeling and database operations. One of the most powerful and frequently used functions in Mongoose is findOneAndReplace(). This function helps in finding a document and replacing it with a new one. But how exactly
5 min read
Mongoose Queries Model.findOneAndUpdate() FunctionThe Queries Model.findOneAndUpdate() function of the Mongoose API is used to find and update an existing document with the information mentioned in the "update" object. It finds and updates only the first document that is returned in the filter. Syntax: Model.findOneAndUpdate(conditions, update, opt
3 min read
Mongoose Document Model.replaceOne() APIThe Model.replaceOne() method of the Mongoose API is used to replace any one document in a collection. This method works the same as the update method but it replaces MongoDB's existing document with the given document with any atomic operator i.e $set. Syntax: Model.replaceOne() Parameters: Â The Mo
3 min read
updateMany() Method in MongooseIn Mongoose, the updateMany() method is a powerful tool for performing bulk updates in MongoDB. It updates multiple documents that match a specified condition, applying the changes to all the matched documents in a single operation. Unlike updateOne(), which updates only the first matching document,
4 min read
Mongoose Queries Model.updateOne() FunctionThe Model.updateOne() function in Mongoose is a powerful method used to update a single document within a MongoDB collection. It allows you to specify the conditions for selecting a document and then provides a way to apply updates to that document. In this article, we will explore how updateOne() w
4 min read
Mongoose Populate
Mongoose Schema API
Mongoose Connection API
Mongoose Document API
Mongoose Model API