Reputation: 91
I am a beginner in Next.js and I want to use mongoose in Next.js, but I don't know where to connect to the database.
When I use Mongoose in Express, I connect to the database in app.js
, so MongoDB only connects once at startup.
// app.js
const express = require('express');
const mongoose = require("mongoose");
const userRouter = require('./routes/user_actions');
const app = express();
// Connect to MongoDB; this code will only run once when the app starts.
await mongoose.connect('mongodb://localhost:27017/user');
app.use('/user', userRouter);
module.exports = app;
But in Next.js, I don't know where to connect to the database. I connect to the database in the app/route.js
, but every request will connect to the database, which is not what I want. I wonder if it's possible to run the code once at startup in Next.js, like Express, instead of running the code once every time a request is made.
// app/route.js
import {NextResponse} from 'next/server'
import mongoose from 'mongoose'
// Connect to MongoDB; this code will run on every request.
mongoose.connect('mongodb://localhost:27017/user')
export async function POST(request: Request) {
const res = await request.json()
console.log(request);
console.log(res);
return NextResponse.json({hello: 'world'})
}
I noticed a similar question here, but there is no answer.
What should I do in Next.js?
Thanks.
Upvotes: 0
Views: 989
Reputation: 91
Use mongoose.connection.readyState
.
return:
if (mongoose.connection.readyState === 1) {
console.log("is already connected");
return;
}
mongoose.connect('mongodb://localhost:27017/user');
Upvotes: 0