Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
(node:19677) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'find' of undefined

I am currently working on a backend to a wishlist and I have been having this issue with my code

(node:19677) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'find' of undefined

I have tried redefining the wishlist import and even the user import but to no fix.

Below is my code for my wishlist at the moment.

 import mongoose from 'mongoose';
import express from 'express';
import wishlist from '../models/wishlist_model.js';
import User from '../models/user_model.js';
import { BooksSchema } from '../models/books_model';
import { wishlistSchema } from '../models/wishlist_model';


const Books = mongoose.model('Books', BooksSchema);
const app = express();


app.use(express.json());


//Create a wishlist
export const createWishlist = async (req, res, next) => {
    const wishOwner = await User.find({"username" : `${req.body.username}`})
    .exec()
    .then(user =>{
           if (user != 0) {
            const wish = new wishlist({
                wishlist_id: mongoose.Types.ObjectId(),
                _id: user[0]._id,
                username: req.body.username
            });
            wish.save().then(result=>{
                console.log(result);
                res.status(201).json({
                    msg: `Wishlist created for ${req.body.username}`
                })
            })
        }
        else{
            return res.status(400).json({msg:  "User does not exist"});
        }
            
    });
};


//Add units to Wishlist

export const addToWishlist = async (req, res, next) => {
    let bookToAdd = await Books.find({"isbn" : `${req.query.isbn}`},{"title" : 1 , "price" : 1}).exec()
    let bookTitle =  bookToAdd[0].title;
    let wishOwner = await User.find({"username" : `${req.query.username}`}).exec()
    let wishlist = await wishlist.find({"username" : `${req.query.username}`}).exec()
    let newWishBooks = wishlist[0].books;
    newWishBooks.push(bookTitle);


    await wishlist.updateOne( { "username": `${req.query.username}` },
    {
      $set: {
        books: newWishBooks
      }});


    res.json({ 
        msg: `Successfully added ${bookTitle} to ${wishOwner[0].username}'s Wishlist!`
    }
    );
}

Any help would be appreciated! Thank you

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You don't mention in which line the error occurs but by looking at it, I would say the problem is here:

let wishlist = await wishlist.find({"username" : `${req.query.username}`}).exec()

because wishlist is undefined when you're trying to use it. Maybe you wanted to use wishOwner?

about 4 years ago · Juan Pablo Isaza Relatório

0

Problably this line

let wishlist = await wishlist.find({"username" : `${req.query.username}`}).exec()

is causing error, because wishlist (the just declared variable) is undefined, as long the Wishlist (capital) may be the Model that you want to invoke to query database.

let wishlist = await Wishlist.find({"username" : `${req.query.username}`}).exec()
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda