logologo

Three-D

☕Sign in

    Recent Post:

    Categories:

    nextjsjavascriptthreejshonoreactjs
    featured post image

    snippets

    featured post image

    What is Currying?

    featured post image

    What is an IIFE?

    Defining MongoDB Schemas , Next.js

    July 1, 2024

    434

    image

    Think you know it all?

    Take quiz!

    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:

    1. Defining a Schema

    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);

    2. Connecting with Mongoose

    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;

    3. Using Schemas in API Routes

    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.