I'm particularly new to NextJS, and I was wondering if I could ask for a bit of help with an issue that I am having.
I have 2 Mongoose schemas defined and have been using one schema in my page for a while with no issues. However, as soon as I import the 2nd schema, my page refuses to render with the attached error.
It doesn't matter which schema I import, but as soon as a second schema is imported, I get the same error for the second schema.
Here is each schema:
User.js
import mongoose from "mongoose";
const UserSchema = new mongoose.Schema({}, { strict: false });
export default mongoose.models.User || mongoose.model("User", UserSchema);
Album.js
import mongoose from "mongoose";
const AlbumSchema = new mongoose.Schema({}, { strict: false });
export default mongoose.models.Album || mongoose.model("Album", AlbumSchema);
And here is the page in which the error is occurring.
albums.js
import Layout from "@/Components/Dashboard/DashLayout";
import AlbumCard from "@/Components/Dashboard/Albums/AlbumCard";
import AlbumSchema from "@/models/Album";
import dbConnect from "@/utils/dcConnect";
export default function DashAlbums({ albums }) {
return (
// Page content removed for import
);
}
// Require authentication
DashAlbums.auth = true;
export async function getServerSideProps(context) {
dbConnect();
const albums = await AlbumSchema.find()
const data = albums.map(album => {
return { _id: album._id, name: album.name, cover: album.cover }
});
return { props: { albums: JSON.parse(JSON.stringify(data)) } }
}
Please could someone help me figure out where I have gone wrong?
I've tried only exporting the model, but NextJS doesn't like that and I don't have enough knowledge to figure out where I have gone wrong.
I think the problem is you cannot import the Mongoose schema code into the client components.
You have to write an API route, write this logic in api handler
dbConnect();
const albums = await AlbumSchema.find()
const data = albums.map(album => {
return { _id: album._id, name: album.name, cover: album.cover }
});
then in getServerSideProps
you make a request to that api path and return the correct result inside props
object