Recent Post:
Categories:
Defining schemas for your MongoDB collections can help maintain data integrity and consistency. Here’s how you can set up and use schemas in your Next.js application:
While MongoDB is schema-less, you can define schemas using libraries like Mongoose to enforce structure.
code
// lib/models/Post.js
import mongoose from 'mongoose';
const PostSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
});
export default mongoose.models.Post || mongoose.model('Post', PostSchema);
Connect Mongoose to your MongoDB database.
code
// lib/mongoose.js
import mongoose from 'mongoose';
const uri = process.env.MONGO_URL;
async function connect() {
if (mongoose.connection.readyState >= 1) return;
return mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
}
export default connect;
Use the defined schemas in your API routes for CRUD operations.
code
// pages/api/posts.js
import connect from '../../lib/mongoose';
import Post from '../../lib/models/Post';
export default async function handler(req, res) {
await connect();
if (req.method === 'GET') {
const posts = await Post.find({});
res.status(200).json(posts);
} else if (req.method === 'POST') {
const post = new Post(req.body);
await post.save();
res.status(201).json(post);
} else {
res.setHeader('Allow', ['GET', 'POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
By defining and using schemas, you can ensure that your MongoDB collections maintain a consistent structure, making your data management more reliable.