mongodb connects everytime I made request to api
Answered
Golden Eagle posted this in #help-forum
Golden EagleOP
import mongoose from "mongoose";
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.mongodb!);
console.log(
} catch (error: any) {
console.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,
});
};
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,
});
};
Answered by Golden Eagle
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}`);
}
};17 Replies
yep, this is how serverless functions work. They do not share connections
Golden EagleOP
ok then
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.
@Golden Eagle ^
Golden EagleOP
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}`);
}
};Answer
@linesofcode <@698313542767738921> ^
Golden EagleOP
thank you
@linesofcode But they can be shared between multiple function execution for the lifetime of the container the function is running on
Thanks for correcting me here - I didn't know this