The Model.findById() function is producing an undefined result

I am currently working on implementing a favorite toggle feature that saves favorites in an array. I have created a Schema and a router for this functionality. However, when I attempt to test it on insomnia, I am receiving 'undefined' in my console.log(isFavorite). I'm not sure what I might be doing wrong.

const userSchema = new Schema({
    username: String,
    email: String,
    password: String,
    favorites: [{ type: Schema.Types.ObjectId, ref: "Places" }],
  },
  {
    timestamps: true,
  });

// route

router.put("/favorites/:placeId", (req, res) => {

  const userId = "5ebd13df31430045957db8c3";

  User.findById(userId).then( (user) => {

    const isFavorite = user.favorites.find( (favorite) => {
      return favorite === req.params.placeId;
    });

    console.log(isFavorite);
    console.log(req.params.placeId);

    if (isFavorite) {
      User.findOneAndUpdate(
        { _id: userId },
        {
          $pull: { favorites: req.params.placeId },
        },
        {
          new: true,
        })
        .then((user) => res.json(user))
        .catch((err) => res.status(400).json(err));
    } else {
      User.findOneAndUpdate(
        { _id: userId },
        {
          $push: { favorites: req.params.placeId },
        },
        {
          new: true,
        })
        .then((user) => res.json(user))
        .catch((err) => res.status(400).json(err));
    }
  });
});

Answer №1

this section needs improvement:

Instead of:
User.findById(userId).then((user) => {
    const isFavorite = user.favorites.find((favorite) => {
      return favorite === req.params.placeId;
    });

try using populate() method:

let favorites = await User.findById(userId).populate('favorites');

Then, you can filter favorites by placeId

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

I seem to be facing a challenge with retrieving results in my app when using mongoose - what could be causing this issue

mongoose.connect('mongodb://localhost:27017/codealong'); When I attempt to connect to MongoDB and post data, the process is successful but I do not receive any results in my browser. Instead, all I see is an empty square bracket [ ]. These are ...

Using Node.js to retrieve a p12 certificate from the certificate repository

Is there a way to retrieve the p12 certificate from the certificate store after it has been installed? I am facing a situation where both the private key and certificate are combined in a p12 certificate and then stored in the Windows certificate store. ...

Nuxt Vuex global state update does not cause v-for loop components to re-render

I am struggling to effectively use Vuex global state with re-rendering child components in Vue.js. The global state is being mutated, but the data does not update in the v-for loop. Initially, all data is rendered correctly. However, when new data is intr ...

The array.slice() method fails to work properly when I try to start it from any index other than 0

I am currently working with an array called $scope.results which contains 8 objects. I have also created a custom simple pagination and a function called selectAll() that I'm trying to get to work together. Please refrain from suggesting the use of b ...

What is Mozilla's reasoning for deeming Conditional catch-blocks as non-conventional?

I recently came across a document on Mozilla that described the try...catch conditional as "non-standard and is not on a standards track. Do not use it in production" However, I am curious to understand the reason behind this statement. I also want t ...

The console is displaying the array, but it is not being rendered in HTML format in AngularJS

Can you please review my App.js file and let me know if there are any mistakes? I have provided the necessary files index.html and founditemtemplate.html below. Although it is returning an array of objects in the console, it is not displaying them as inten ...

When using Selenium WebDriver, the WebElement .findElement method can sometimes cause errors in JavaScript

Successfully locating the element, I am able to retrieve the text within the container. However, when attempting to fetch the titles of products by iterating through the array of WebElements inside the container, the .findElement() consistently throws an e ...

The Antd Tooltip becomes unresponsive when a component is clicked and moved

Having an issue with a button that has an Antd tooltip, here is the setup: <Tooltip title="Some text"> <button onClick={openNotes}><Icon icon="notes" /></button> </Tooltip> Upon clicking the button, the ...

Generate and display a random element on a webpage using Javascript or jQuery on page refresh

Currently, I am developing a website for my unique custom themes on a blogging platform. One of the features I am looking to add is a review section, where only one random review will display per page refresh. My question is, can anyone assist me in crea ...

Guide on creating a nested commenting platform with express.js

My goal is to set up a system for displaying multi-level comments, where a comment can have replies, which in turn can also have replies, and so on. Currently, I am using SQLite for this purpose. Below is the approach I have taken so far: Model const Comme ...

Create a random word from a single string within the data in Nuxt.js

I am in need of assistance. In my Vue Nuxtjs project, I am fetching random words generated from my backend Laravel application through an API response. I need to generate multiple random words from a single string value in the data obtained from my Axios r ...

guidelines for rendering a Vue component within a Vue file using vue-server-renderer

Starting the rendering component with vuejs is my goal. I currently have a basic node server set up. const Vue = require('vue'); const server = require('express')(); const template = require('fs').readFileSync('index. ...

What is the best way to send an object from the front end to the backend using res.send?

In my current project, I am establishing communication between the frontend and backend. The process involves the backend sending an expression to the frontend for computation, after which the computed answer needs to be sent back to the backend. For exam ...

storing the user type in ReactJs for the duration of the session

In my development stack, I am utilizing ReactJs, Nodejs, and mysql for the backend. User sessions are being managed through express-session with cookies set in the browser. My challenge lies in displaying components based on user roles such as admin or reg ...

Angular UI grid: Arranging numbers in a straight line at the decimal point

I am interested in aligning decimal numbers in Angular UI Grid as shown below. 11.293 .89 233424 .34345 I have considered different approaches such as using a cell template with aligned divs or transparent 0s. Has anyone successfully imp ...

When the web driver fails to function as expected

After installing the selenium-webdriver via npm, I downloaded the IE component from this link and added it to my path on Windows 8. Upon opening IE, I had to set all security zones to high, ensuring they were consistent. However, due to restrictions in th ...

Issue with Ionic Native File: File.writeFile function - file is not being created and there is no callback response

I've exhausted all the different solutions I could find, but unfortunately, the file isn't getting saved and nothing seems to be happening. The callback functions aren't being called - neither success nor error. Here are the solutions I&apo ...

Ensure that the pattern meets the regular expression criteria

Must consist of at least 3 characters in lowercase, with a maximum of 2 numbers and no special characters allowed. I attempted to use ^[a-zA-Z0-9]*$ but I couldn't restrict the number of numbers used. Could someone provide assistance, please? ...

Choosing a particular 2D array based on another variable in jQuery and JavaScript

Within my project, I am utilizing 2D arrays to append specific divs under particular circumstances. In an effort to streamline and enhance the code, I attempted to create a variable that would determine which array to utilize based on the id of an HTML < ...

Defining the password in the MySQL connection URL

I recently developed an ExpressJS MVC application using MySQL as the database, utilizing the Yeoman generator. I now find myself stuck trying to update the MySQL connection strings in the config.js file. Specifically, I am unsure how to include my password ...