Step 23: Mongoose Schema & Model

We have connected our application to our MongoDB cluster in the cloud. Next, let's store some data!

As the first step, we will define a schema for "bookmark" documents. We can use a schema to require a specific set of fields, configure a field's content, or validate changes to a document based on its beginning and end states.

Update the src/mode/Bookmark.js file:

import mongoose from "mongoose";

const BookmarkSchema = new mongoose.Schema({
  title: { type: String, required: true },
  url: { type: String, required: true },
});

const Bookmark = mongoose.model("Bookmark", BookmarkSchema);

export default Bookmark;

We are using the Schema class from Mongoose to create a document schema for bookmarks. The code snippet above essentially establishes that a bookmark will have a title and a url, and both of these attributes are of type String and required.

Next, we create a model by calling the model function. The model is like a Data Access Object, exposing operations such as create, find, findById, findByIdAndUpdate, findByIdAndDelete and many more. We will work with these operations in the next section. For now, save and commit the changes!