I've been attempting to fetch objects from MongoDB using Mongoose, but I keep encountering a 404 error.
router.get('/blogs/:id', function(req, res){
console.log('trying to get one blog post by id');
Blog.findOne({
_id: req.params.id
})
.exec(function (err, blog) {
if(err){
res.send('error occurred');
} else{
console.log(blog);
res.render('entry', {entries: entry});
}
})
});
Error message: **5abe5efa06ac64917363277a Failed to load resource: the server responded with a status of 404 (Not Found)**.
The documents exist in the database:
{
"_id" : ObjectId("5abe5efa06ac64917363277a"),
"title" : "this is the first blog",
"author" : "me",
"body" : "this is a post",
"comments" : [
ObjectId("5ac1fe92f2eb490c3c5b1357")
]
}
This is my entry.ejs view:
<% 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>
And here's how I have defined my schema:
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);
Using the following code, I am able to retrieve all blogs:
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;