将所有Controllers Routes和Models移入其各自的文件后,我遇到了麻烦。我似乎只有从数据库加载任何内容时都会超时,而我的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);
答案 0 :(得分:0)
首先,根据另一位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);
});
我没有意识到如果没有这个,我不会在数据库启动时得到错误日志。
答案 1 :(得分:-1)
确保仅在与数据库的连接建立后才发送请求。