Mongoose: Unable to fetch item using its specific identification - Error 404

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;

Answer №1

When passing a string to the query which is expecting an ObjectId, you will encounter an error.

Consider the following solutions:

Method 1:

    import mongoose from 'mongoose';
    (or)
    var mongoose = require('mongoose');

    router.get('/blogs/:id', function(req, res){
    console.log('retrieving one blog post by id');
    Blog.findOne({
       _id: mongoose.Types.ObjectId(req.params.id)
    })
       .exec(function (err, blog) {
           if(err){
               res.send('an error occurred');
           } else{
               console.log(blog);
               res.render('entry', {entries: entry});
           }
       })
    });

Method 2:

var ObjectId = require('mongoose').Types.ObjectId; 

router.get('/blogs/:id', function(req, res){
console.log('retrieving one blog post by id');
Blog.findOne({
   _id: new ObjectId(req.params.id)
})
   .exec(function (err, blog) {
       if(err){
           res.send('an error occurred');
       } else{
           console.log(blog);
           res.render('entry', {entries: entry});
       }
   })
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why isn't useEffect recognizing the variable change?

Within my project, I am working with three key files: Date Component Preview Page (used to display the date component) useDateController (hook responsible for managing all things date related) In each of these files, I have included the following code sn ...

Tips for toggling the visibility of an element when a button is clicked in React

In my todo list, I need to display the details of each item when clicked on a button. There are two buttons available: "View Details" and "Hide Details". Below is the code snippet: class Todos extends React.Component{ construc ...

Identifying the device name in Safari on iOS 13 despite the inaccurate display of the user agent - a step-by-step guide

Following the release of Apple's iOS 13, I discovered that window.navigator.userAgent in Safari on iPad iOS 13 is identical to that on MacOS. It appears like this: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) ...

The base64 conversion for the image is overflowing from the upload image field in react-draft-wysiwyg

I have a functional react-draft-wysiwyg editor application that allows me to add images. However, I am currently encountering an issue which is detailed below: https://i.stack.imgur.com/HTjAc.png This is the code snippet of what I have attempted so far. ...

Modifying data on the fly for a Highcharts series

My chart is currently functioning well with data in the options. However, when I leave the data empty for a series and attempt the following code (in order to change the data based on a click event), it fails to work. Any suggestions on how I can rectify ...

Learn how to pass variables with templates when sending emails via nodemailer in NodeJS with Express

Utilizing nodemailer to distribute emails to users upon registration. The function is outlined below: const setAndSendMsg = (recipients, users, subject, template) => { const htmlFile = checkTemplate(template) const message = { from: mail ...

What is the best way to display the outcome in a popup window?

I am looking to display the result in a pop-up window. Code: <?php $con=mysqli_connect("localhost","root","1234","fyp"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = ...

The issue arises when the jQuery $.get() method fails to deliver the expected response to the client, despite returning a status code of

I am having trouble with sending a REQUEST to a server in order to retrieve a message. I have tried using the jQuery method $.get(), and it seems to have successfully reached the server. However, I am facing an issue where I am unable to send a RESPONSE b ...

Error code TS7053 occurs when an element implicitly has an 'any' type because a string expression cannot be used to index an empty object

I have implemented a code snippet that sorts items into groups based on their first character. For example, if the array of item looks like this: {name: 'Foo'} {name: 'Bar'} {name: 'Baz'} The expected result should be: B: ...

Using jQuery to arrange information from an API into a table

Currently, I am in the process of learning jQuery as it is a new concept for me. I have attempted to make a request to an example API and received an array of objects that need to be listed in a table. However, I am facing difficulty in sorting it within t ...

You cannot use .addCursorFlag() with Mongoose Typescript

Here is my mongoose model that retrieves data from the database using a cursor. The cursor has a timeout of 10 minutes as per the documentation. const cursor = this.importRecordModel.find().cursor() I attempted to add the following code at the end of the ...

What is the best way to send data from a header component to a separate container component?

Utilizing React-router-dom, I am able to seamlessly switch between components in the following setup: <Router> <div> <Header /> <NavigationBar /> <Switch> <Route exact path ...

What is the best way to implement switchMap when dealing with a login form submission?

Is there a better way to prevent multiple submissions of a login form using the switchMap operator? I've attempted to utilize subjects without success. Below is my current code. import { Subject } from 'rxjs'; import { Component, Output } ...

javascript mysql and php clash when it comes to loading

I am encountering an issue where I cannot fetch data from my phpMyAdmin database using php code when loading the map api that utilizes javascript. Currently, only the map javascript is being loaded. I have valuable data stored in my database and any assis ...

Tips for applying textures dynamically to MeshPhongMaterial?

When trying to apply a texture on a THREE.MeshPhongMaterial, the texture fails to load. Here's the code snippet: let earth_geometry = new THREE.SphereGeometry(450, 10, 10) let earth_material = new THREE.MeshPhongMaterial({ emissive: 0xffffff }) ...

Exploring Angular2's ability to interpret directive templates using the ng-container

Recently delving into angular2, I ventured into creating dynamic forms and generating fields by following the guide provided in this URL. The result was as expected. The dynamic form component renders each field one by one using ng-container, like shown b ...

The function _plugins_vuetify__WEBPACK_IMPORTED_MODULE_136__.default is not usable as a constructor

I have created a Vue application using vue cli 3 and incorporated Vuetify. To optimize the size of my bundle, I decided to modify the way Vuetify is imported: The versions I am working with are vuetify 1.5.5 and vue 3.7.0 import Vue from 'vue'; ...

The request to upload an image to Cloudinary using AngularJS is being blocked due to the origin http://localhost.com:8000 not being allowed by Access-Control-Allow-Origin

I've been attempting to upload images to Cloudinary through my Angular controller without using any libraries. The POST requests are unsigned, and interestingly, I was successful when I tested it with jQuery on a static HTML page. Here is the code sn ...

Access the Express server by connecting to its IP address

Is it feasible to connect to an express server using the server's UP address? If so, how would one go about doing this? (Examples of code snippets would be greatly appreciated) ...

Swapping the image source using a Vue dropdown menu

Recently I started using Vue and decided to implement a dropdown menu component (). The component pulls its list items from a JSON array structured as follows: <template> <div id="app"> <div id='container'> ...