Mongoose Documents vs Models
Last Updated :
28 Dec, 2023
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:
- Require Mongoose: Import the Mongoose library.
- 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.
- 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.
- 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" );
const instance = new YourModel({
fieldName1: "some value" ,
fieldName2: 42,
});
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' );
const yourSchema = new mongoose.Schema({
name: String,
age: Number,
email: String,
});
const YourModel = mongoose.model( "YourModel" , yourSchema);
const document = new YourModel({
name: "John Doe" ,
age: 30,
email: "john@example.com" ,
});
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,
});
const YourModel = mongoose.model( 'YourModel' , yourSchema);
const document = new YourModel({
name: 'John Doe' ,
age: 30,
email: 'john@example.com' ,
});
document.save((error, savedDocument) => {
if (error) {
console.error(error);
} else {
console.log( 'Document saved:' , savedDocument);
}
});
|
Differences between Mongoose Documents and Models:
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.
|
Share your thoughts in the comments
Please Login to comment...