You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击发布按钮向Posts模型插入数据时遇Mongoose超时错误求助

解决MongooseError: Operation posts.insertOne() buffering timed out问题

你的代码存在两个核心问题,直接导致了数据库操作超时:

1. 数据库连接建立后立即被关闭

在mongodb.js的connect函数中,finally块里的await mongoose.connection.close();会在连接完成后立刻关闭数据库连接,后续所有数据库操作都没有可用连接,最终触发缓冲超时。

修复后的mongodb.js:

import mongoose from "mongoose";

const connect = async () => {
    // 如果已有活跃连接,直接返回
    if (mongoose.connections[0].readyState === 1) return;
    try {
        await mongoose.connect(process.env.MONGODB_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
        console.log("Mongo Connection successfully established.");
    } catch (error) {
        throw new Error("Error connecting to Mongoose: " + error.message);
    }
    // 移除finally中的关闭连接逻辑
};

export default connect;

2. 数据库操作前未触发连接

在managepostdata.js的saveData和getData函数中,没有调用connect函数建立数据库连接,Mongoose会一直等待可用连接直到超时。

修复后的managepostdata.js:

'use server'
import connect from "@/app/lib/mongodb" // 取消注释导入连接函数
import AddPostModel from "@/app/models/AddPost"

const saveData = async (title, content, author) => {
    await connect(); // 先建立数据库连接
    let newaddpostobj = new AddPostModel({
        uid: Date.now().toString(36),
        title: title,
        content: content,
        author: author,
    })
    let res = await newaddpostobj.save()
    return res.id.toString()
}

const getData = async () => {
    await connect(); // 先建立数据库连接
    let res = await AddPostModel.find()
    return JSON.stringify(res)
}

export { saveData, getData }

额外优化:表单提交处理异步操作

在addpost/page.js的handleFormSubmit中,调用saveData时缺少await,无法正确处理返回结果或捕获错误:

const handleFormSubmit = async (e) => {
    e.preventDefault()
    const title = e.target[0].value
    const content = e.target[1].value
    const author = e.target[2].value
    try {
        let res = await saveData(title, content, author) // 添加await
        console.log("Post saved with ID:", res)
        e.target.reset() // 提交成功后重置表单
    } catch (error) {
        console.error("Failed to save post:", error)
        // 这里可以添加前端错误提示逻辑
    }
}

完成以上修改后,重新运行项目即可正常提交数据到MongoDB。

内容的提问来源于stack exchange,提问作者Shubham Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 06:55:22