Next.js Discord

Discord Forum

It takes the page around 3 seconds to load in even tho it takes around 0.50 seconds to get the data

Answered
Arboreal ant posted this in #help-forum
Open in Discord
Arboreal antOP
I have a dashboard page that lists all of the users server, it only takes 30-50 ms for monogdb to get the data but it takes 3 seconds to load the page, any idea on how to fix this?
import connectMongoDB from "@/app/lib/db";
import serverModel from "@/app/models/serverschema";
import { getUser } from "@/app/utilities/getUser";
import { cookies } from 'next/headers'
import { permanentRedirect } from 'next/navigation'
import './dashboard.css'

const DashBoard = async () => {


    const cookieStore = cookies()
    const sessionid = cookieStore.get('sessionid')
  
    const User = (await getUser(sessionid))
  
  
    if (!User) {
      permanentRedirect(`myurl`)
    }

    async function fetchServers() {
        connectMongoDB();
    
        try {
            const data = await serverModel.find({ ownerid: User.userid });
            return data;
        } catch(err) {
            return null; 
        }
    }
    

    const servers = await fetchServers()

    return (
       <> 
        <h1>My Servers</h1>
        <div>
            {servers.map((server) => (
                <div key={server.id} className="server-container">
                    <h2 className="server-name">{server.name}</h2>
                </div>
            ))}
        </div>
       </> 
    );
};
 
export default DashBoard;
Answered by Standard Chinchilla
use this:
import mongoose from "mongoose";

const DATABASE_URL = process.env.DATABASE_URL;

if (!DATABASE_URL) {
  throw new Error("Please define the DATABASE_URL environment variable inside .env.local");
}

let cached = global.mongoose;

if (!cached) {
  cached = global.mongoose = { conn: null, promise: null };
}

async function connectDB() {
  if (cached.conn) {
    return cached.conn;
  }

  if (!cached.promise) {
    const opts = {
      bufferCommands: false,
    };

    cached.promise = mongoose.connect(DATABASE_URL, opts).then((mongoose) => {
      return mongoose;
    });
  }
  cached.conn = await cached.promise;
  return cached.conn;
}

export default connectDB;
View full answer

17 Replies

Arboreal antOP
also i am running this on a dev server
Arboreal antOP
bump
Standard Chinchilla
how do you know the mongo response is only taking half a second
@Standard Chinchilla how do you know the mongo response is only taking half a second
Arboreal antOP
because i made another file with vanilla js and mongose and it mesured how many seconds it took to recive the data
@Standard Chinchilla how do you know the mongo response is only taking half a second
Arboreal antOP
and i also added this
            const startTime = Date.now();
            const data = await serverModel.find({ ownerid: User.userid });
            const endTime = Date.now();
            const elapsedTimeInSeconds = (endTime - startTime) / 1000; 
            console.log(`Data fetched in ${elapsedTimeInSeconds.toFixed(2)} seconds`);
Standard Chinchilla
what is the connectMongoDB function doing
@Standard Chinchilla what is the connectMongoDB function doing
Arboreal antOP
import mongoose from "mongoose";

const connectMongoDB = async ()  => {
    try {
    await mongoose.connect('my connection string');
 } catch (error) {
    console.log(error)
 }
}

export default connectMongoDB
Standard Chinchilla
can you measure the time for that
@Standard Chinchilla can you measure the time for that
Arboreal antOP
that took about 1.4 seconds
Standard Chinchilla
yes I don't think that's the best way to connect to mongo
essentially you are doing that everytime you call the database
Standard Chinchilla
use this:
import mongoose from "mongoose";

const DATABASE_URL = process.env.DATABASE_URL;

if (!DATABASE_URL) {
  throw new Error("Please define the DATABASE_URL environment variable inside .env.local");
}

let cached = global.mongoose;

if (!cached) {
  cached = global.mongoose = { conn: null, promise: null };
}

async function connectDB() {
  if (cached.conn) {
    return cached.conn;
  }

  if (!cached.promise) {
    const opts = {
      bufferCommands: false,
    };

    cached.promise = mongoose.connect(DATABASE_URL, opts).then((mongoose) => {
      return mongoose;
    });
  }
  cached.conn = await cached.promise;
  return cached.conn;
}

export default connectDB;
Answer
Standard Chinchilla
now when you use connectDB() if it's cached it will not reestablish a conection
Arboreal antOP
now it only takes 700 ms when i tried it with postman, in the browser it takes at least a second
welp i guess that fixed it, thanks
Standard Chinchilla
No problem G