Mongoose Schema and Models
A Mongoose model is a wrapper of the Mongoose schema. A Mongoose schema defines the document's properties, default values, types of data, validators, etc. In contrast, a Mongoose model provides an interface for the database to create, query, update, delete records, and so on.
Creating a Mongoose schema and models mainly consists of three parts:
1. Referencing Mongoose: This is the same as the one we used while connecting our database, which implies that defining Schema and Model does not require an explicit connection to the database.
let mongoose = require('mongoose');
const { Schema } = mongoose;

You can also try this code with Online Javascript Compiler
Run Code
2. Schema Definition: We define a schema to decide the properties of the object, including default values, data types, if required, etc.,
const blogSchema = new Schema({
// String is shorthand for {type: String}
title: String,
date: { type: Date, default: Date.now },
body: String,
});

You can also try this code with Online Javascript Compiler
Run Code
Here blogSchema defines a few basic properties for a blog. We've defined a property title and body of the String SchemaType, and property date that will be of a Date SchemaType, and its default value is set to Date.now, which provides a current date.
Currently, 10 SchemaTypes are allowed in Mongoose:
- Array
- Boolean
- Buffer
- Date
- Mixed (A generic/flexible data type)
- Number
- ObjectId
- String
- Decimal 128
- Map
3. Creating and Exporting a Model: To use the Schema defined, we need to convert blogSchema into a Model we can work with.
To do this, we will use the mongoose.model(<CollectionName>, <CollectionSchema>) function. This function accepts two parameters CollectionName ( name of the collection) CollectionSchema ( schema defined for the collection) and returns a mongoose Model object.
let Blog = mongoose.model('Blog', blogSchema); //creating a Model
module.exports = Blog //Exporting the created module.

You can also try this code with Online Javascript Compiler
Run Code
Now that we have successfully created a Mongoose schema and models, we can use this blog model to efficiently perform operations like create, read, update, delete, etc., from our database.
Basic operations using mongoose schema and models
Mongoose schema and models perform basic operations on the MongoDB Collection, like create, query, update, delete, etc.
Note: We can perform all these operations in more than one way, but we will not discuss them here as they are not in the scope of this article.
- Create Records: Let's create an instance of the blog model and save it to the MongoDB database.
// Creating newBlog object using blog Model
var newBlog = new Blog({
title: "New Blog to create record",
body: "This is a sample blog created for coding ninja tutorial"
})
// Saving newBlog to database
newBlog.save()
.then(doc => {
console.log(doc)
})
.catch(err => {
console.error(err)
})

You can also try this code with Online Javascript Compiler
Run Code
The result is a document upon successful submission.
{
_id: 5a78fe3e2f44ba8f85a2409a,
title: "New Blog to create record",
body: "This is a sample blog created for coding ninja tutorial",
date: 08-12-2021 13:14
__v: 0
}

You can also try this code with Online Javascript Compiler
Run Code
In the returned document, we can see that we have the __id property which is auto-generated by Mongo and is the primary key of the collection. title, body, and date are the fields defined in the blogSchema schema with their value. __v is the version key property for each document when first created by Mongoose.
- Fetch Record: Let's try to fetch the record we saved to the database earlier. We will find the document using the find() method and pass the title as a search item.
// Fetching record from the database
Blog.find({
// search query
title: 'New Blog to create record'
})
.then(doc => {
console.log(doc)
})
.catch(err => {
console.error(err)
})

You can also try this code with Online Javascript Compiler
Run Code
The result returned is the same as the one while creating the document.
{
_id: 5a78fe3e2f44ba8f85a2409a,
title: "New Blog to create record",
body: "This is a sample blog created for coding ninja tutorial",
date: 08-12-2021 13:14
__v: 0
}

You can also try this code with Online Javascript Compiler
Run Code
- Update Record: Now, we will update the record we saved to the database earlier. We will update the document using the findOneAndUpdate() method.
// Fetching record from the database
Blog.findOneAndUpdate(
{
// Search query
title: "New Blog to create record",
},
{
// Field: values to update
title: "Blog updated in the record",
},
{
// To return the updated doc
new: true,
}
)
.then((doc) => {
// Updated doc returned
console.log(doc);
})
.catch((err) => {
// Error displayed
console.error(err);
});

You can also try this code with Online Javascript Compiler
Run Code
The updated document will be returned to the console.
{
_id: 5a78fe3e2f44ba8f85a2409a,
title: "Blog updated in the record",
body: "This is a sample blog created for coding ninja tutorial",
date: 08-12-2021 13:14
__v: 0
}

You can also try this code with Online Javascript Compiler
Run Code
- Delete Record: Let's see how to delete the record we saved to the database earlier. We will delete the record using the findOneAndRemove() method.
// Fetching record from the database
Blog.findOneAndRemove({
// Search query
title: "Blog updated in the record"
})
.then((doc) => {
console.log(doc)
})
.catch(err => {
console.error(err)
})

You can also try this code with Online Javascript Compiler
Run Code
The above code will delete the found record.
{
_id: 5a78fe3e2f44ba8f85a2409a,
title: "Blog updated in the record",
body: "This is a sample blog created for coding ninja tutorial",
date: 08-12-2021 13:14
__v: 0
}

You can also try this code with Online Javascript Compiler
Run Code
Frequently Asked Questions
1. What is the difference between Mongoose schema and Models?
Ans. A Mongoose schema defines the property of the document, default values, validators, etc. In contrast, the Mongoose model provides an interface to perform operations on the database like query, create, update, delete, etc.
2. What is schemaType?
Ans. A SchemaType is a configuration object for an individual property. A SchemaType says what type a specified path should have, whether it has any getters/setters, and what values are valid for that particular path.
Check this out : what is schema in dbms
Key Takeaways
In this blog, we learned about mongoose schema and models. We can create Schema and then convert it to a Model using mongoose.model() method. With Mongoose Schema and Models, we can perform all the basic operations ( query, create, update, delete, etc.) in the database.
If you want to learn advanced web development, Coding Ninjas has one of the best courses available, which you can find here.