I am encountering an issue with MongoDB where the find() method is returning multiple results instead of the specific value I am looking for

Currently developing a social media platform similar to Facebook and in the process of implementing profile picture uploads. Within my User schema, there is a specific field called profilePicture. The concept involves users visiting their profile page, uploading an image, and having the URL of that image stored in their profilePicture attribute.

User Schema:

const userSchema = new mongoose.Schema({
  username: String,
  profilePicture: String,
});

Presented below is an example of how a User's data appears within the database.

_id: 642716b83w306234dx8d6cab
username: "Dagger"
profilePicture: "public\images\uploads\a7c770ff72d830a4fb0c8f6963ab9aa8"

In relation to retrieving the profile picture through a GET request, I am utilizing User.find() to search for the profilePicture.

router.get("/:user/profile-picture", (req, res) => {
  User.find({}, "profilePicture").exec(function (err, profilePicture) {
    if (err) {
      return next(err);
    }
    res.render("picture", { user, id, picture, profilePicture });
  });
});

However, upon trying to display the image on the EJS page using the img tag, nothing appears.

<div class="avatar">
  <img src="<%= profilePicture %>.jpg" alt="logo" />
</div>

Upon inspection, it becomes evident that the value of <%= profilePicture %> lists out all Users in the database. How can this be refined to only display the value matching

"public\images\uploads\a7c770ff72d830a4fb0c8f6963ab9aa8"
?

Answer №1

To search for a specific user, you can utilize the findOne() method and specify the parameter you wish to use as a filter.

For instance:

User.findOne({ username: 'Sword'}, "avatar").exec(...)

If you want this process to be dynamic, replace the hard-coded 'Sword' with a variable that represents the user whose photo you want to retrieve.

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

The file import is restricted based on the user's input

I am facing an issue with my small vue.js app. My goal is to import a specific json file based on user input. import content from "@/posts/posts/" + new URL(location.href).searchParams.get('id') + ".json"; Every time I attem ...

Converting an object into an array in JavaScript for the purpose of adding an item to it

Looking to update a data object by adding a new item? Convert the object into an array, add the item, and then switch it back to an object to achieve that. Here's the initial data object: { Activity: 'digitalLoan', digitalLoan_type: &ap ...

What is the best way to prioritize loading JSON models first in three.js and declare a variable before initializing?

I am looking to efficiently load multiple JSON models and store them in global variables for easy access. This will streamline tasks like copying, translating, and more without the need to reload a model each time. After trying various methods, I have not ...

Troubleshooting a TypeScript Problem with React Context

In my AppContext.tsx file, I have defined the following import React, { useState, createContext } from "react"; import { Iitem } from "../utils/interfaces"; interface AppContext { showModal: boolean; setShowModal: React.Dispatch< ...

"An ng-repeat directive with a filter applied results in an empty

After successfully implementing the ng-repeat loop below: <div ng-repeat="einschItem in einschaetzungen.alldata | filter: { savedatum: lolatage[tagarrayindex].tagestring } | orderBy : '-savetimestamp'"> I wanted to check if the filtered r ...

The entire component is not displayed in Vue

Just starting out with Vue. I'm looking to create a component that encompasses the entire page except for the header and footer Vue.component('main-block', {template: ` <section id="first-block">...</section> <secti ...

Understanding TypeScript typing when passing arguments to the Object.defineProperty function

After reviewing all the suggested answers, including: in Typescript, can Object.prototype function return Sub type instance? I still couldn't find a solution, so I'm reaching out with a new question. My goal is to replicate Infix notation in J ...

Efficient Local Database with Javascript

When storing a substantial amount of data, such as a big hashmap in JavaScript, what would be the optimal format for quick retrieval while also supporting Unicode? Would XML or JSON be better suited for this purpose? ...

Kendo UI Scheduler: The system encountered an overflow while converting to a date and time format

Working on a project using .NET MVC and the Kendo UI Scheduler, an open-source tool. The goal is to save, read, update, and delete events from the scheduler into the database using JavaScript. Encountering some challenges in the process - when attempting ...

How can I identify where a Mesh and Particle System intersect in Three.js?

I have a unique setup where I have a particle system utilizing sprites, housed in an Object3D akin to the "interactive / points" example from three.js. Additionally, I have a simple sphere mesh that tracks my cursor's movements. Check out the example ...

What causes a Module Error to occur in my AngularJS application when I attempt to include multiple routes?

When there is a single .when() route in my app.js, the testApp module loads successfully and the site functions as expected. However, if I add additional routes (such as about and contact) using .when(), the module fails to load. Here is the error message ...

How can I successfully implement the Add To Calendar Button Package?

Recently, I decided to incorporate this particular component into my application. Although it seemed simple enough at first, I'm now faced with a puzzling TypeError originating from within the package. The react component I am constructing is as foll ...

The GitHub-hosted package encounters a failure during the npm publish process

Last week everything was running smoothly, but now I am encountering an error and not sure what went wrong. (Apologies for the formatting as there are many lines of log) Running Node version: v10.15.3 Using npm version: 6.4.1 After executing npm publish ...

Divide the string into separate JSON and non-JSON components

Here is a string I have: const str = '{ "foo": { "bar": { "baz": 5 } } } Some additional text'; Is there a reliable method in JavaScript to separate the JSON part from the non-JSON part of this string? The string always starts with valid JSON, ...

Finding the IST date time (YYYY-MM-DD HH:mm:ss) in a Node.js environment is a common requirement. Let's

I recently used the code below to retrieve the current time and date in IST: const x = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '') Output: 2020-09-01 17:49:48 However, I actually need to obtain the time in IST ...

Transformation of intricate object

I am currently in search of a reliable utility (such as Lodash) that can assist me in transforming deeply nested objects like the example shown below: Source Data: [{ "category": "blogs", "results": { "__type": "SearchProvider.SearchResultCon ...

Is it possible to create dynamic meta tags in Angular that will appear in a Twitter-style card preview?

My project involves building a dynamic website using a Java app that serves up a REST-ish JSON API along with an Angular9 front end. A key requirement is the ability to share specific URLs from the app on platforms like Twitter and Slack, which support Twi ...

What is the process for transforming a string into a Cairo felt (field element)?

In order to work with Cairo, all data must be represented as a felt. Learn more here Is there a way to convert a string into a felt using JavaScript? ...

Issue with CornerstoneJs React restoreImageIdToolState causing annotations to fail to load automatically post-execution

Once this code is executed, I need the annotations to appear without having to hover over the cornerstoneViewport. const restore = () => { let element; const stack = { currentImageIdIndex: 0, imageIds, }; console.log(dico ...

Implementing a click event on header elements within a full calendar component in a React application

I'm currently integrating full calendar into my project. I need to implement click events on the header buttons such as prev, next, today, and others. This is how I've set up full calendar with the specified header buttons: <FullCalendar d ...