但是,有时我想通过仪表板菜单打开页面,但前端没有任何反应。没有加载屏幕等。如何防止该问题以使页面仍然加载?该问题并不总是发生,可能取决于数据库连接。按 F5 刷新后,一切恢复正常
我有以下代码,用于显示 MongoDB 中的元素:
export const dynamic = "force-dynamic";
async function Page() {
const count = await countAccounts();
return (
<RootLayout>
<p>{count}</p>
</RootLayout>
);
}
export default Page;
在服务下我有以下代码:
export const countAccounts = async (search: string): Promise<number> => {
await dbConnect();
const query = buildSearchQuery(searchFields, search);
const count = await Account.countDocuments(query).lean();
return count;
};
并且背后有一个 Mongoose 模型来访问数据库:
const AccountSchema = new mongoose.Schema<Account>(
{
id: { type: String, required: true, unique: true, index: true },
name: { type: String, required: true },
isActive: { type: Boolean, default: true },
},
{ timestamps: true }
);
export const Account =
mongoose.models.Account || mongoose.model("Account", AccountSchema);
数据库连接:
import mongoose, { Connection } from "mongoose";
interface CachedMongoose {
conn: null | Connection;
}
declare global {
var mongoose: CachedMongoose;
}
const { MONGODB_URI } = process.env;
if (!MONGODB_URI) throw new Error("❌ MONGODB_URI is not defined.");
let cached = global.mongoose;
if (!cached) {
cached = global.mongoose = { conn: null };
}
export const dbConnect = async () => {
if (cached.conn) return cached.conn;
await mongoose.connect(MONGODB_URI);
cached.conn = mongoose.connection;
return cached.conn;
};
我添加了力动态,希望这能解决一些问题。
让我为您标记问题: 在你的代码的下面部分
async function Page() { const count = await countAccounts();
您需要传递一个字符串作为 countAccounts() 函数的参数,因为您已使用其中所需的字符串参数声明了它
export const countAccounts = async (search: string): Promise => {
如果您想在获取期间传递查询参数,您可以构建一个在其中接受查询参数的API路由。其余代码看起来不错并且可以在我的计算机上运行。快乐编码..