Having trouble retrieving image URLs from MongoDB with Mongoose

I am currently facing an issue where I am trying to retrieve an image URL from my MongoDB database using Mongoose, and then display it with EJS. However, I keep getting undefined as the result.

When I use findById to fetch the data, this is what I receive:

[ 
    { 
        _id: 5b809b2c74e2f54c20ae30da,
        brand: 'honda',
        model: 'cbr250r',
        price: 20000,
        amount: 20,
        img: 'https://news.maxabout.com/wp-content/uploads/2016/12/22.png',
        backImg: 'https://wallpapercave.com/wp/wp3065342.png',
        views: 1,
        desc: 'this is a bike description' 
    } 
]

I am attempting to access the "backImg" property using the path: "item[0].backImg". However, when I log it in the console, it returns undefined. I have also tried "item.backImg"

This is the route file containing the function:

const router = require('express').Router();
const bodyParser=require('body-parser')
const urlencodedParser =bodyParser.urlencoded({extended:false})
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
const itemModel = require('../models/itemsModel')
const userModel = require('../models/userModel')

//items//
router.get('/:_id',(req,res)=>{
    console.log(req.params._id)
    let q = itemModel.find({_id:req.params._id})
    q.exec(function(err,item){
        if(err){
            console.log(err)
        } else {
            console.log(item)
            console.log(item[0].brand)
            console.log(item[0].backImg)
            console.log(item.backImg)
            res.render('./pages/items' , {item:item,user: req.user,} )
        }
    })
})

module.exports = router

Answer №1

It appears that the fields imported as undefined were not included in the item schema, causing the issue.

Answer №2

My opinion is that it should look something like this

..... // previous code
itemModel.findOne({_id:req.params._id})
.then((item)=>{
    if(!item){
        console.log("No record found");
    }
    console.log(item)
    console.log(item.brand)
    console.log(item.backImg)
})
.catch(err=>{
    console.log("Error",err)
})

In the provided snippet, I have utilized the findOne method from mongoose which retrieves a single object from the database. Additionally, there is a check to ensure that req.params._id is not undefined. Feel free to reach out if you have any inquiries.

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

Complete the modal window form

I'm currently facing an issue with populating a modal window form. To provide some context, when I click on a grid row to edit a user, I make an ajax call which fetches specific data related to that user. Here is the existing code snippet: <modal ...

Retrieve the source code of the current page using JavaScript and the Document Object Model (DOM)

Is there a way to retrieve the source of the current page using JavaScript and DOM? Do I need to utilize AJAX for this task? ...

Implementing Dynamic Parameter Injection in your REST API

In my nodejs project, I am required to make multiple ms graph api calls in order to retrieve specific data. Here are some examples of the API calls: https://graph.microsoft.com/v1.0/users/{userPrincipalName}/manager https://graph.microsoft.com/beta/users/ ...

show the stored value inside the useRef variable

One of my challenges involves a variable const prediction = useRef<any>(null); A button triggers a function that updates the variable's value: function showResult() { classifier.current.classify(capture, (result) => { ...

Altering the download directory for Chrome/Chromium with the help of Puppeteer

Currently, I am using Ubuntu 16.04 LTS to work on a web scraping project where I am attempting to download a file using Puppeteer. However, I am facing issues with changing the download location in both Chromium and Chrome browsers. Despite trying the foll ...

Learn the method for automatically checking a checkbox when a page is loaded in Angular

I have multiple checkboxes on a single page <div class="check-outer"> <label>Place of operation</label> <div class="checkDiv"> <div ng-repeat="place in places"> <div class="checkbox-wrapper"> ...

A guide to implementing bounds with dynamic markers in react-leaflet

I have a functional react component that currently displays two static markers within a bounding box that fits both markers inside. However, I am trying to figure out how to pass an array of latitude and longitude values to dynamically display the markers ...

Validating Paypal IPN with a Node.js Express Application

I need help with implementing Paypal IPN verification in my node.js app which utilizes the express framework. Below is a snippet of the code I have written: app.post('/paypal', function(req,res){ console.log("IN PAYPAL !! req.body : "+req.body) ...

Explore the world of HTML event listening through .NET integration

Imagine this scenario: within an HTML page, using an UpdatePanel, you have a loading animated gif spinning while ASP.NET processes data from a webservice. I'm curious if there's a way to create an Event in .NET code that can be detected on the H ...

Getting a Node module from the renderer in Electron: What you need to know

Is there a way to import a node module in my Electron app's renderer.js file? I'm attempting to utilize the Store object from the sindresorhus/electron-store package within my renderer.js file. This file is called through index.html as shown bel ...

Tips for employing clamp CSS to modify font size while maintaining alignment within a paper-inspired CSS grid

Currently, I am working on creating a responsive text section with a grid-like horizontal line resembling paper, and the challenge lies in aligning the text properly within this grid. While I can achieve this when the font size remains constant, I am curi ...

Enhancing Grails dynamic dropdown to include a pre-selected value in edit.gsp

One feature I have implemented is a dynamic dropdown menu in my _form.gsp file that appears in both the create and edit pages. While it currently works as intended, I am seeking a way to display the selected value on the edit page. _form.gsp <g:s ...

"Learn the correct method of passing JSON data through Ajax data parameters, even when including query

I've encountered a problem while working with JSON. Everything was going smoothly until I realized that passing JSON containing query-string URLs is causing an issue. Here's an example of the JSON: var json='{"nodeDataArray": [ {"info ...

Steps to resolve: Uncaught ReferenceError: app is undefined

I'm encountering a problem where I keep receiving the following error message: ReferenceError: app is not defined. Below is the code snippet causing the issue: import express from "express"; import chatbotControllers from "../c ...

What is the best way to apply a specific style based on the book ID or card ID when a click event occurs on a specific card in vue.js

My latest project involves creating a page that displays a variety of books, with the data being fetched from a backend API and presented as cards. Each book card features two button sections: the first section includes "ADD TO BAG" and "WISHLIST" buttons ...

Enclose chosen images with selection made

Below is the code snippet I am working with: <select multiple="multiple" class="image-picker show-html"> <option data-img-src="http://placehold.it/125x200" value="1">SportField 1</option> <option data-img-src="http://placehold ...

Revisit the promise in AngularJS after making adjustments to the page and reload

1) The login page redirects to the home page after a successful login. if (data.status == CONSTANTS.RETURN_SUCCESS) { $location.path("/home"); $route.reload(); } 2) I have implemented a promise to fetch data from the database before loading ...

Paste the results of a JavaScript function into an Excel spreadsheet (codenamed "assault")

I currently have a website that utilizes a JavaScript function to validate a text input with 5 characters. The HTML code for this functionality is as follows: <p class="form-control-static ret"> Input your Text: <input ty ...

Inaccurate ray tracing using an orthographic camera in three.js

Currently working on a 2D CAD drawing viewer using the three.js library. I need the ability to click on objects within the scene to perform operations. However, when utilizing an orthographic camera, I've noticed that the precision of the three.js ra ...

Most efficient way to use JavaScript to filter a checkboxlist

Our project does not require the use of any javascript libraries such as jQuery, Dojo, or Prototype so finding a solution may be more challenging. I am looking for detailed answers to this question explaining how it can be accomplished. As many of you may ...