For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt
Tutorial: Mongoose Get Started
Overview
Mongoose is an Object Data Modeling (ODM) library for MongoDB. You can use Mongoose to help with data modeling, schema enforcement, model validation, and general data manipulation. Because MongoDB has a flexible data model that allows you to alter and update databases in the future, there aren't rigid schemas. However, Mongoose enforces a semi-rigid schema from the beginning, so you must define a schema and model.
Schemas
A schema defines the structure of your collection documents. A Mongoose schema maps directly to a MongoDB collection.
The following example creates a new Schema named blog:
When you create a schema, you must define each field and its data types. The following types are permitted:
String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array
Int32
Decimal128
Double
Map
Models
Models take your schema and apply it to each document in its collection. Models are responsible for all document interactions such as create, read, update, and delete (CRUD) operations.
Tip:
The first argument you pass to the model is the singular form of your collection name. Mongoose automatically changes this to the plural form, transforms it to lowercase, and uses that for the database collection name.
The following example shows how to declare a model named Blog that uses the blog schema:
const Blog = mongoose.model('Blog', blog);
In the preceding example, Blog translates to the blogs collection in MongoDB.
Tutorial
In this tutorial, you will perform the following actions:
Set up your environment to use Mongoose
Connect to MongoDB
Create a Mongoose schema and model
Insert, update, find, and delete data
Project document fields
Validate your data
Use multiple schemas and middleware
Verify the prerequisites
Before you begin this tutorial, ensure you have the following components prepared:
An MongoDB Atlas account with a configured cluster. To view instructions, see the MongoDB Get Started guide.
This tutorial uses nodemon to run the code locally. Run the following commands in your terminal to initialize your project and install the necessary dependencies:
bash
mkdir mongodb-mongoose
cd mongodb-mongoose
npm init -y
npm i mongoose
npm i -D nodemon
Open your project in your preferred code editor. This tutorial uses ES Modules instead of CommonJS. You must add the module type to use ES Modules. Go to the package.json file and add the following code:
Start your application with nodemon by running the following command:
json
npm run dev
Note:
When you use nodemon, the code runs every time you save a file.
Connect to MongoDB
In the root level of your project, create a file named index.js and add the following code to the top of the file:
```javascript
import mongoose from 'mongoose';
mongoose.connect("")
```
Replace the <connection string> placeholder with your MongoDB Atlas connection string. For more information on how to find your connection string, see the Connect to Your Cluster tutorial in the Atlas documentation.
Create a schema and a model
Before you start adding and updating data in MongoDB, you must create a schema and model.
With Mongoose, you create a schema model file for each schema that is needed. First, create a folder called model to put all your schema files in, then create your first schema file called Blog.js. Open this file and add the following code:
```javascript
import mongoose from 'mongoose';
const { Schema, model } = mongoose;
const Blog = model('Blog', blog);
export default Blog;
```
This schema enables a timestamps option, which adds Mongoose-managed createdAt and updatedAt fields to the schema that are updated automatically. For more information, see the Timestamps page in the Mongoose documentation.
Perform CRUD operations
You now have your first model and schema set up, and you can start inserting data into the database. The following sections show you how to perform CRUD operations using Mongoose.
##### Insert Data
Go to index.js and add the following import statement to the top of your file:
```javascript
import Blog from './model/Blog.js';
```
Add the following code below the line that contains your connection string:
```javascript
// Creates a new blog post and inserts it into the database
const article = await Blog.create({
title: 'Awesome Post!',
slug: 'awesome-post',
published: true,
content: 'This is the best post ever',
tags: ['featured', 'announcement'],
});
console.log('Created article:', article);
```
The preceding code uses the Mongoose create() method to instantiate the object representing a blog article, and then saves it to the database. The returned document logs to the console, including its _id. Take note of this _id for use in future steps.
##### Update Data
To update data, you can directly edit the local object with Mongoose. Then, you can use the save() method to write the update to the database.
Add the following code to update the article you inserted in the previous section:
```javascript
// Updates the title of the article
article.title = 'The Most Awesomest Post!!';
await article.save();
console.log('Updated Article:', article);
```
Output:
console
Updated Article: {
title: 'The Most Awesomest Post!!',
slug: 'awesome-post',
published: true,
content: 'This is the best post ever',
tags: [ 'featured', 'announcement' ],
_id: new ObjectId('...'),
comments: [],
__v: 0
}
##### Find Data
To find a specific document, you can use the Mongoose findById() method to query for a document by specifying its _id.
Add following code to your index.js file to find a specific article by its _id:
```javascript
// Finds the article by its ID. Replace