【发布时间】:2018-09-11 16:28:23
【问题描述】:
我正在尝试使用 mongoose 从 MongoDB 检索对象,但收到错误 404。
router.get('/blogs/:id', function(req, res){
console.log('getting one blog post by id');
Blog.findOne({
_id: req.params.id
})
.exec(function (err, blog) {
if(err){
res.send('error occured');
} else{
console.log(blog);
res.render('entry', {entries: entry});
}
})
});
错误消息:** 5abe5efa06ac64917363277a 加载资源失败:服务器响应状态为 404(未找到)。**
文档存在于数据库中:
{
"_id" : ObjectId("5abe5efa06ac64917363277a"),
"title" : "this is the first blog",
"author" : "me",
"body" : "this is a post",
"comments" : [
ObjectId("5ac1fe92f2eb490c3c5b1357")
]
}
这是我的 entry.ejs 视图:
<% include header %>
<div class="panel panel-default">
<div class="panel-heading">
<div class="text-muted pull-right">
<%= entry.published %>
</div>
<%= entry.author %> <a class="btn btn-default" href="blogs/<%= entry._id %>"> <%= entry.title %></a>
</div>
<div class="panel-body">
<%= entry.body %>
<div id="comments">
<% entry.comments.forEach(function(comment){ %>
<%= comment.commentAuthor + " : " + comment.comm %>
<% }) %>
</div>
<div>
</div>
</div>
<div class="panel-body">
<a class="btn btn-default" href="<%= entry._id %>/new-comment">Add new comment</a>
</div>
</div>
这是我定义架构的方式:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var exports = module.exports = {};
exports.commentSchema = new Schema({
commentAuthor: String,
comm: String,
date: { type: Date, default: Date.now }
});
exports.blogSchema = new Schema({
title: String,
author: String,
body: String,
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'commentSchema' }],
date: { type: Date, default: Date.now },
});
exports.Blog = mongoose.model('Blog',exports.blogSchema);
使用以下代码,我可以检索所有博客:
var express = require('express');
var router = express.Router();
var schema = require('../model/schema');
/* GET users listing. */
router.get('/', function(req, res, next) {
schema.Blog.find({}, function (err, blogs) {
if (err) {
console.log(err);
} else{
res.render('blogs', {entries: blogs});
}
});
});
module.exports = router;
【问题讨论】:
-
您发送的请求是什么?
-
此错误的可能原因可能是,您正在调用未在服务器端定义的端点。您可以通过在处理程序函数中记录一些内容来验证您的路线是否被正确命中
-
试试
<%= entry.author %> <a class="btn btn-default" href="blogs?id=<%= entry._id %>"> <%= entry.title %></a> -
修改href后还是一样的错误...
标签: javascript mongodb express mongoose server