Rewriting an ExpressJS app as a NextJS app (Part 3)


Mon Feb 22 2021

Rewriting an ExpressJS app as a NextJS app (Day 3: Implementing MongoDB and adding CRUD Functions)

Fixing the overwrite error

As stated in my previous blog post, I ran into a problem where my NextJS app threw an error at me claiming that I was trying to overwrite the collection whenever I went to MongoDB Atlas to look at the data. At first, I decided to move on and deal with it later, as it would be rare for me to go to MongoDB Atlas after deploying.

It wasn't until I created a Read REST API using Mongoose that I realized that this was going to be a problem as my app would only let me see the data once unless I restarted the development server. After going to MongooseJS's official site and reading docs on how to get around this, I figured out that I needed to create a connection rather than just use a connection. Then I needed to move everything related to Mongoose under the try statement and made sure that I added an await statement to the const since my CRUD functions were async functions. My APIs ended up looking something like this:


import mongoose from 'mongoose'


export default async function(req, res){
    
    
    try {
        mongoose.set('useFindAndModify', false)
        const connection = await mongoose.createConnection(process.env.MONGODB_CONNECTION, {
            useNewUrlParser: true,
            useUnifiedTopology: true
        }).catch(function(err){
            console.log("error:", err)
        })
        
        const Schema = mongoose.Schema
        const cardSchema = new Schema({
            title: String,
            note: String,
            user: String
        })
        const Card = connection.model('Notes', cardSchema)
        const card = new Card({
            title: req.body.title,
            note: req.body.note,
            user: req.body.user
        })
        card.save()
        res.status(200).json({status: "everything's good"})
    } catch(error){

        res.status(500).json({Error: error.message})
    }
}

I made sure that the rest of the CRUD functions had the same format except for the creation part. CRUD functions could then be made in a way similar to the way one would do so in ExpressJS.

Making the web app usable

After making pages that made use of the APIs, I ran into a problem where the data would not be fetched if I were to refresh the page. To fix that, I added a const called loadingCondition that was equal to the state of true. While true, I would allow the data to be fetched. Once that was complete, I made sure that the state of loadingCondition was set to false, making sure that the data would not need to be fetched again.

With everything in place, I then committed the changes, deployed it to Vercel, and took the Nameservers from Vercel to GoDaddy to change the domain name to studythat.site