Models Introduction
What are Models?
Mongoose models are a way to create and work with data in MongoDB. Models are defined using schemas, which define the structure of the data and the types of the data. Models are then used to interact with the database.
Why use Models?
Models are a way to interact with the database in a structured way. Models allow us to define the structure of the data we want to store and the types of the data. Models also provide a way to interact with the database in a consistent way.
How to use Models
To use models, we need to define schemas for the data we want to store. Schemas are defined in the src/app/_db/models
directory. Schemas are then used to create models that interact with the database. Models are exported and then used in server actions to interact with the database.
Example
Here is an example of a schema and model for a project:
const mongoose = require("mongoose");
export const projectModel = mongoose.Schema({
year: String,
projectName: String,
description: String,
type: String,
startDate: Date,
endDate: Date,
uid: {
type: mongoose.Schema.Types.ObjectId,
ref: "users"
}
});
export const Project = mongoose.models.projects || mongoose.model("projects", projectModel);