【问题标题】:NodeJS MongoDB Times Out Loading RouteNodeJS MongoDB 超时加载路由
【发布时间】:2026-01-21 19:25:02
【问题描述】:

将我的所有控制器路由和模型移动到它们自己的文件后,我遇到了麻烦。我似乎只在从数据库中加载任何内容时才超时,并且我的 console.log() 不再运行,该模型可以正常工作,并且它可以很好地发布 testPost(在控制器中)。我尝试添加 testPost,因为我的控制台中没有显示 console.log() 或错误。

控制器

//jshint esversion: 6 
const mongoose = require('mongoose');


const Post = require(`./../models/posts`);
//Initial Post to posts Model
const testPost = new Post ({
    postTitle: `Default Post`,
    postDate:  Date.now(),
    postBody: `If you're seeing this, It means your DB is connected and you're ready to go!`,
    postAuthor: `Admin`
});
const defaultPost = [testPost];


//View Single Post
exports.showOne = function(req, res){
    const requestedPostTitle = req.params.id;
    Post.findOne({postTitle: requestedPostTitle}, function(err, foundPost){
        if (!err && foundPost){
            const title = foundPost.postTitle;
            const date = foundPost.postDate;
            const content = foundPost.postBody;
            const author = foundPost.postAuthor;
            res.render(`./post/post`, {
                title: title,
                date: date,
                content:content,
                author:author
            });

        }
    });
};

型号

//jshint esversion: 6 
const mongoose = require(`mongoose`);

const postSchema = new mongoose.Schema ({

     {SCHEMA DATA}
    }
});

module.exports = mongoose.model(`Post`, postSchema);
exports.databaseName = `postsDB`; 

index.js 路由

app.get(`/posts`, postPages.showAll);
app.get(`/post/:id`, postPages.showOne);
app.get(`/post/compose`, postPages.compose);
app.post(`/post/compose`, postPages.create);

【问题讨论】:

  • 你目前只响应!err情况,你检查是否有错误吗?
  • 是的,没有任何显示,它发生在所有路线上,而不仅仅是 showOne
  • 在追着自己的尾巴以为我太早启动服务器后,我直接将其添加到mongoose.connect()中发现了一个错误;这表明我的端口被未正确退出的 mongod 请求阻止。我在 Linux 上,所以我杀了它,现在它又可以工作了。吸取教训,检查数据库启动时的错误。

标签: node.js mongodb mongoose


【解决方案1】:

首先,根据另一位 SO 用户引用的这篇精彩文章,我将我的数据库启动移动到它自己的名为 db.js 的文件中: https://theholmesoffice.com/mongoose-connection-best-practice/

将配置移入 db.js 后,我根据文章记录了错误:

// If the connection throws an error
mongoose.connection.on('error',function (err) {  
  console.log('Mongoose default connection error: ' + err);
}); 

我没有意识到如果没有这个,我不会在数据库启动时收到错误日志。

【讨论】:

    【解决方案2】:

    确保仅在与数据库建立连接后发送请求。

    【讨论】: