#mongodb connects everytime I made request to api

20 messages · Page 1 of 1 (latest)

hollow token
#

import mongoose from "mongoose";

const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.mongodb!);
console.log(MongoDB Connected: ${conn.connection.host});
} catch (error: any) {
console.error(MongoDB Connection Error: ${error});
process.exit(1);
}
};

connectDB();

export { userModel } from "./userModel";
import { userModel } from "@/lib/mongodb";
import { NextResponse } from "next/server";

export const POST = async (req: Request) => {
const { displayName, email, username, password } = await req.json();

if (!displayName || !email || !username || !password) {
return NextResponse.json(
{
error: "Please fill all fields",
},
{
status: 400,
},
);
}
const user = await userModel.create({
id: crypto.randomUUID(),
displayName,
username,
email,
password,
});

return NextResponse.json(user, {
status: 201,
});
};

steady geyserBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

spring plinth
#

yep, this is how serverless functions work. They do not share connections

hollow token
#

ok then

steady geyserBOT
#
✅ Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer

[Click here](#1207002741621395456 message)

dusk hemlock
#

Memoize your connection

#

The information above isn’t exactly accurate

#

Connections won’t be shared between serverless containers

#

But they can be shared between multiple function execution for the lifetime of the container the function is running on

#

Move the conn variable to globe scope

#

And then call your connectDb function whenever you need a connection

#

Inside that function it first checks if a connection has already been initialized (by check the global variable)

#

If it hasn’t then initialize a connection and assign to global variable

#

Subsequent serverless function calls which hit the same container

#

Will reuse the connection

#

If you write your code in this fashion.

#

@hollow token ^

hollow token
#
import mongoose from "mongoose";

let connected = false;

export const connectDB = async () => {
  if (connected) {
    console.log("Already connected to MongoDB");
    return;
  }

  try {
    const client = await mongoose.connect(process.env.mongodb!);
    console.log(`Connected to MongoDB: ${client.connection.host}`);
    connected = true;
    return client;
  } catch (error) {
    throw new Error(`Error connecting to MongoDB: ${error}`);
  }
};
steady geyserBOT
#
✅ Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer

[Click here](#1207002741621395456 message)

hollow token