Next.js Discord

Discord Forum

Exporting problem with MongoDB

Answered
Asiatic Lion posted this in #help-forum
Open in Discord
Asiatic LionOP
I came for the first time and added MongoDB to my project and the dev process was working fine, but when I tried to export, I got an error.

nextjs version: 13.5.2
mongoose version: 7.6.2

/lib/connectDB ( I tested many codes, but now my code is this )
import mongoose from "mongoose";

const connectDB = async () => await mongoose.connect(process.env.MONGODB_URI);

export default connectDB;

pages/api/getAllRecords.js ( An example of an api code related to the code above )
import connectDB from "../../lib/connectDB"; // Import the database connection function
import MessageTrigger from "../../../models/messageTriggers"; // Import the Mongoose model

export default async function handler(req, res) {
    await connectDB(); // Connect to the database
    if (req.method === "GET") {
        try {
            // Fetch all records from the database
            const allRecords = await MessageTrigger.find();

            res.status(200).json({ success: true, data: allRecords });
        } catch (error) {
            res.status(500).json({ success: false, error: error.message });
        }
    } else {
        res.status(405).json({ success: false, message: "Method Not Allowed" });
    }
}
Answered by Ray
api route is not supported in static exports
View full answer

14 Replies

Spectacled bear
What's the complete error when you run in dev npm run dev?
@Spectacled bear What's the complete error when you run in dev `npm run dev`?
Asiatic LionOP
When running in npm run dev, it doesn't show any error and it runs perfectly
Spectacled bear
does it also happen when you do npm run build && npm run start?

If there are no errors using npm run start:
Do you have a reason for using export instead of start?
Asiatic LionOP
Yes, I just tested it and it gave the same error again
Spectacled bear
I think this needs more context about your app structure & code to be solved
@Spectacled bear I think this needs more context about your app structure & code to be solved
Asiatic LionOP
So, what should I do now?
Spectacled bear
1. delete the .next directory at the root of your project
2. run npm run build
3. run npm run start
@Spectacled bear 1. delete the `.next` directory at the root of your project 2. run `npm run build` 3. run `npm run start`
Asiatic LionOP
It gave the same error again
In the npm run build
@Ray are you fetching self api in `getStaticProps`?
Asiatic LionOP
no
Answer
@Ray api route is not supported in static exports
Asiatic LionOP
I know, but my project is not static exports
@Asiatic Lion I know, but my project is not static exports
you trying to use next export?