![]() |
VOOZH | about |
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.
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.
save(), find(), update(), and delete().The following functions are used on the Document of the Mongoose:
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);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()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){});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();
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();
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.
Create a folder and initialize it:
npm initnpm i mongooseThe project structure is as follows:
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();
Now run the code using the following command in the Terminal/Command Prompt to run the file.
node index.jsOutput:
And the document in the MongoDB is as follows:
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.
index.js FileWe 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();
})();
If the validation fails, Mongoose will throw an error and prevent the document from being saved to the database.
node index.jsOutput:
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.